blob: da629c4e0d197dc80aef3d41c2cb495ed09b7cc9 [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
2027 if (!Type->isConstantSizeType()) {
2028 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002029 // FIXME: Better diagnostic.
2030 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002031 return false;
2032 }
2033
2034 Size = Info.Ctx.getTypeSizeInChars(Type);
2035 return true;
2036}
2037
2038/// Update a pointer value to model pointer arithmetic.
2039/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002040/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002041/// \param LVal - The pointer value to be updated.
2042/// \param EltTy - The pointee type represented by LVal.
2043/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002044static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2045 LValue &LVal, QualType EltTy,
2046 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002047 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002048 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002049 return false;
2050
2051 // Compute the new offset in the appropriate width.
2052 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002053 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002054 return true;
2055}
2056
Richard Smith66c96992012-02-18 22:04:06 +00002057/// Update an lvalue to refer to a component of a complex number.
2058/// \param Info - Information about the ongoing evaluation.
2059/// \param LVal - The lvalue to be updated.
2060/// \param EltTy - The complex number's component type.
2061/// \param Imag - False for the real component, true for the imaginary.
2062static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2063 LValue &LVal, QualType EltTy,
2064 bool Imag) {
2065 if (Imag) {
2066 CharUnits SizeOfComponent;
2067 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2068 return false;
2069 LVal.Offset += SizeOfComponent;
2070 }
2071 LVal.addComplex(Info, E, EltTy, Imag);
2072 return true;
2073}
2074
Richard Smith27908702011-10-24 17:54:18 +00002075/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002076///
2077/// \param Info Information about the ongoing evaluation.
2078/// \param E An expression to be used when printing diagnostics.
2079/// \param VD The variable whose initializer should be obtained.
2080/// \param Frame The frame in which the variable was created. Must be null
2081/// if this variable is not local to the evaluation.
2082/// \param Result Filled in with a pointer to the value of the variable.
2083static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2084 const VarDecl *VD, CallStackFrame *Frame,
2085 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002086 // If this is a parameter to an active constexpr function call, perform
2087 // argument substitution.
2088 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002089 // Assume arguments of a potential constant expression are unknown
2090 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002091 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002092 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002093 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002094 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002095 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002096 }
Richard Smith3229b742013-05-05 21:17:10 +00002097 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002098 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002099 }
Richard Smith27908702011-10-24 17:54:18 +00002100
Richard Smithd9f663b2013-04-22 15:31:51 +00002101 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002102 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002103 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002104 if (!Result) {
2105 // Assume variables referenced within a lambda's call operator that were
2106 // not declared within the call operator are captures and during checking
2107 // of a potential constant expression, assume they are unknown constant
2108 // expressions.
2109 assert(isLambdaCallOperator(Frame->Callee) &&
2110 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2111 "missing value for local variable");
2112 if (Info.checkingPotentialConstantExpression())
2113 return false;
2114 // FIXME: implement capture evaluation during constant expr evaluation.
2115 Info.Diag(E->getLocStart(),
2116 diag::note_unimplemented_constexpr_lambda_feature_ast)
2117 << "captures not currently allowed";
2118 return false;
2119 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002120 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002121 }
2122
Richard Smithd0b4dd62011-12-19 06:19:21 +00002123 // Dig out the initializer, and use the declaration which it's attached to.
2124 const Expr *Init = VD->getAnyInitializer(VD);
2125 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002126 // If we're checking a potential constant expression, the variable could be
2127 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002128 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002129 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002130 return false;
2131 }
2132
Richard Smithd62306a2011-11-10 06:34:14 +00002133 // If we're currently evaluating the initializer of this declaration, use that
2134 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002135 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002136 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002137 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002138 }
2139
Richard Smithcecf1842011-11-01 21:06:14 +00002140 // Never evaluate the initializer of a weak variable. We can't be sure that
2141 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002142 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002143 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002144 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002145 }
Richard Smithcecf1842011-11-01 21:06:14 +00002146
Richard Smithd0b4dd62011-12-19 06:19:21 +00002147 // Check that we can fold the initializer. In C++, we will have already done
2148 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002149 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002150 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002151 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 Notes.size() + 1) << VD;
2153 Info.Note(VD->getLocation(), diag::note_declared_at);
2154 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002155 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002156 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002157 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002158 Notes.size() + 1) << VD;
2159 Info.Note(VD->getLocation(), diag::note_declared_at);
2160 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002161 }
Richard Smith27908702011-10-24 17:54:18 +00002162
Richard Smith3229b742013-05-05 21:17:10 +00002163 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002164 return true;
Richard Smith27908702011-10-24 17:54:18 +00002165}
2166
Richard Smith11562c52011-10-28 17:51:58 +00002167static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002168 Qualifiers Quals = T.getQualifiers();
2169 return Quals.hasConst() && !Quals.hasVolatile();
2170}
2171
Richard Smithe97cbd72011-11-11 04:05:33 +00002172/// Get the base index of the given base class within an APValue representing
2173/// the given derived class.
2174static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2175 const CXXRecordDecl *Base) {
2176 Base = Base->getCanonicalDecl();
2177 unsigned Index = 0;
2178 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2179 E = Derived->bases_end(); I != E; ++I, ++Index) {
2180 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2181 return Index;
2182 }
2183
2184 llvm_unreachable("base class missing from derived class's bases list");
2185}
2186
Richard Smith3da88fa2013-04-26 14:36:30 +00002187/// Extract the value of a character from a string literal.
2188static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2189 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002190 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2191 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2192 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002193 const StringLiteral *S = cast<StringLiteral>(Lit);
2194 const ConstantArrayType *CAT =
2195 Info.Ctx.getAsConstantArrayType(S->getType());
2196 assert(CAT && "string literal isn't an array");
2197 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002198 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002199
2200 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002201 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002202 if (Index < S->getLength())
2203 Value = S->getCodeUnit(Index);
2204 return Value;
2205}
2206
Richard Smith3da88fa2013-04-26 14:36:30 +00002207// Expand a string literal into an array of characters.
2208static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2209 APValue &Result) {
2210 const StringLiteral *S = cast<StringLiteral>(Lit);
2211 const ConstantArrayType *CAT =
2212 Info.Ctx.getAsConstantArrayType(S->getType());
2213 assert(CAT && "string literal isn't an array");
2214 QualType CharType = CAT->getElementType();
2215 assert(CharType->isIntegerType() && "unexpected character type");
2216
2217 unsigned Elts = CAT->getSize().getZExtValue();
2218 Result = APValue(APValue::UninitArray(),
2219 std::min(S->getLength(), Elts), Elts);
2220 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2221 CharType->isUnsignedIntegerType());
2222 if (Result.hasArrayFiller())
2223 Result.getArrayFiller() = APValue(Value);
2224 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2225 Value = S->getCodeUnit(I);
2226 Result.getArrayInitializedElt(I) = APValue(Value);
2227 }
2228}
2229
2230// Expand an array so that it has more than Index filled elements.
2231static void expandArray(APValue &Array, unsigned Index) {
2232 unsigned Size = Array.getArraySize();
2233 assert(Index < Size);
2234
2235 // Always at least double the number of elements for which we store a value.
2236 unsigned OldElts = Array.getArrayInitializedElts();
2237 unsigned NewElts = std::max(Index+1, OldElts * 2);
2238 NewElts = std::min(Size, std::max(NewElts, 8u));
2239
2240 // Copy the data across.
2241 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2242 for (unsigned I = 0; I != OldElts; ++I)
2243 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2244 for (unsigned I = OldElts; I != NewElts; ++I)
2245 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2246 if (NewValue.hasArrayFiller())
2247 NewValue.getArrayFiller() = Array.getArrayFiller();
2248 Array.swap(NewValue);
2249}
2250
Richard Smithb01fe402014-09-16 01:24:02 +00002251/// Determine whether a type would actually be read by an lvalue-to-rvalue
2252/// conversion. If it's of class type, we may assume that the copy operation
2253/// is trivial. Note that this is never true for a union type with fields
2254/// (because the copy always "reads" the active member) and always true for
2255/// a non-class type.
2256static bool isReadByLvalueToRvalueConversion(QualType T) {
2257 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2258 if (!RD || (RD->isUnion() && !RD->field_empty()))
2259 return true;
2260 if (RD->isEmpty())
2261 return false;
2262
2263 for (auto *Field : RD->fields())
2264 if (isReadByLvalueToRvalueConversion(Field->getType()))
2265 return true;
2266
2267 for (auto &BaseSpec : RD->bases())
2268 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2269 return true;
2270
2271 return false;
2272}
2273
2274/// Diagnose an attempt to read from any unreadable field within the specified
2275/// type, which might be a class type.
2276static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2277 QualType T) {
2278 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2279 if (!RD)
2280 return false;
2281
2282 if (!RD->hasMutableFields())
2283 return false;
2284
2285 for (auto *Field : RD->fields()) {
2286 // If we're actually going to read this field in some way, then it can't
2287 // be mutable. If we're in a union, then assigning to a mutable field
2288 // (even an empty one) can change the active member, so that's not OK.
2289 // FIXME: Add core issue number for the union case.
2290 if (Field->isMutable() &&
2291 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2292 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2293 Info.Note(Field->getLocation(), diag::note_declared_at);
2294 return true;
2295 }
2296
2297 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2298 return true;
2299 }
2300
2301 for (auto &BaseSpec : RD->bases())
2302 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2303 return true;
2304
2305 // All mutable fields were empty, and thus not actually read.
2306 return false;
2307}
2308
Richard Smith861b5b52013-05-07 23:34:45 +00002309/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002310enum AccessKinds {
2311 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002312 AK_Assign,
2313 AK_Increment,
2314 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002315};
2316
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002317namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002318/// A handle to a complete object (an object that is not a subobject of
2319/// another object).
2320struct CompleteObject {
2321 /// The value of the complete object.
2322 APValue *Value;
2323 /// The type of the complete object.
2324 QualType Type;
2325
Craig Topper36250ad2014-05-12 05:36:57 +00002326 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002327 CompleteObject(APValue *Value, QualType Type)
2328 : Value(Value), Type(Type) {
2329 assert(Value && "missing value for complete object");
2330 }
2331
Aaron Ballman67347662015-02-15 22:00:28 +00002332 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002333};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002334} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002335
Richard Smith3da88fa2013-04-26 14:36:30 +00002336/// Find the designated sub-object of an rvalue.
2337template<typename SubobjectHandler>
2338typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002339findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002340 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002341 if (Sub.Invalid)
2342 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002343 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002344 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002345 if (Info.getLangOpts().CPlusPlus11)
2346 Info.Diag(E, diag::note_constexpr_access_past_end)
2347 << handler.AccessKind;
2348 else
2349 Info.Diag(E);
2350 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002351 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002352
Richard Smith3229b742013-05-05 21:17:10 +00002353 APValue *O = Obj.Value;
2354 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002355 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002356
Richard Smithd62306a2011-11-10 06:34:14 +00002357 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002358 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2359 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002360 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002361 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2362 return handler.failed();
2363 }
2364
Richard Smith49ca8aa2013-08-06 07:09:20 +00002365 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002366 // If we are reading an object of class type, there may still be more
2367 // things we need to check: if there are any mutable subobjects, we
2368 // cannot perform this read. (This only happens when performing a trivial
2369 // copy or assignment.)
2370 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2371 diagnoseUnreadableFields(Info, E, ObjType))
2372 return handler.failed();
2373
Richard Smith49ca8aa2013-08-06 07:09:20 +00002374 if (!handler.found(*O, ObjType))
2375 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002376
Richard Smith49ca8aa2013-08-06 07:09:20 +00002377 // If we modified a bit-field, truncate it to the right width.
2378 if (handler.AccessKind != AK_Read &&
2379 LastField && LastField->isBitField() &&
2380 !truncateBitfieldValue(Info, E, *O, LastField))
2381 return false;
2382
2383 return true;
2384 }
2385
Craig Topper36250ad2014-05-12 05:36:57 +00002386 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002387 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002388 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002389 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002390 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002391 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002392 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002393 // Note, it should not be possible to form a pointer with a valid
2394 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002395 if (Info.getLangOpts().CPlusPlus11)
2396 Info.Diag(E, diag::note_constexpr_access_past_end)
2397 << handler.AccessKind;
2398 else
2399 Info.Diag(E);
2400 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002401 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002402
2403 ObjType = CAT->getElementType();
2404
Richard Smith14a94132012-02-17 03:35:37 +00002405 // An array object is represented as either an Array APValue or as an
2406 // LValue which refers to a string literal.
2407 if (O->isLValue()) {
2408 assert(I == N - 1 && "extracting subobject of character?");
2409 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002410 if (handler.AccessKind != AK_Read)
2411 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2412 *O);
2413 else
2414 return handler.foundString(*O, ObjType, Index);
2415 }
2416
2417 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002418 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002419 else if (handler.AccessKind != AK_Read) {
2420 expandArray(*O, Index);
2421 O = &O->getArrayInitializedElt(Index);
2422 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002423 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002424 } else if (ObjType->isAnyComplexType()) {
2425 // Next subobject is a complex number.
2426 uint64_t Index = Sub.Entries[I].ArrayIndex;
2427 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002428 if (Info.getLangOpts().CPlusPlus11)
2429 Info.Diag(E, diag::note_constexpr_access_past_end)
2430 << handler.AccessKind;
2431 else
2432 Info.Diag(E);
2433 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002434 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002435
2436 bool WasConstQualified = ObjType.isConstQualified();
2437 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2438 if (WasConstQualified)
2439 ObjType.addConst();
2440
Richard Smith66c96992012-02-18 22:04:06 +00002441 assert(I == N - 1 && "extracting subobject of scalar?");
2442 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002443 return handler.found(Index ? O->getComplexIntImag()
2444 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002445 } else {
2446 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002447 return handler.found(Index ? O->getComplexFloatImag()
2448 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002449 }
Richard Smithd62306a2011-11-10 06:34:14 +00002450 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002451 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002452 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002453 << Field;
2454 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002455 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002456 }
2457
Richard Smithd62306a2011-11-10 06:34:14 +00002458 // Next subobject is a class, struct or union field.
2459 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2460 if (RD->isUnion()) {
2461 const FieldDecl *UnionField = O->getUnionField();
2462 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002463 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002464 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2465 << handler.AccessKind << Field << !UnionField << UnionField;
2466 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002467 }
Richard Smithd62306a2011-11-10 06:34:14 +00002468 O = &O->getUnionValue();
2469 } else
2470 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002471
2472 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002473 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002474 if (WasConstQualified && !Field->isMutable())
2475 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002476
2477 if (ObjType.isVolatileQualified()) {
2478 if (Info.getLangOpts().CPlusPlus) {
2479 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002480 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2481 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002482 Info.Note(Field->getLocation(), diag::note_declared_at);
2483 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002484 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002485 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002486 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002487 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002488
2489 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002490 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002491 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002492 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2493 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2494 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002495
2496 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002497 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002498 if (WasConstQualified)
2499 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002500 }
2501 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002502}
2503
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002504namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002505struct ExtractSubobjectHandler {
2506 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002507 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002508
2509 static const AccessKinds AccessKind = AK_Read;
2510
2511 typedef bool result_type;
2512 bool failed() { return false; }
2513 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002514 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002515 return true;
2516 }
2517 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002518 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002519 return true;
2520 }
2521 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002522 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002523 return true;
2524 }
2525 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002526 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002527 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2528 return true;
2529 }
2530};
Richard Smith3229b742013-05-05 21:17:10 +00002531} // end anonymous namespace
2532
Richard Smith3da88fa2013-04-26 14:36:30 +00002533const AccessKinds ExtractSubobjectHandler::AccessKind;
2534
2535/// Extract the designated sub-object of an rvalue.
2536static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002537 const CompleteObject &Obj,
2538 const SubobjectDesignator &Sub,
2539 APValue &Result) {
2540 ExtractSubobjectHandler Handler = { Info, Result };
2541 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002542}
2543
Richard Smith3229b742013-05-05 21:17:10 +00002544namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002545struct ModifySubobjectHandler {
2546 EvalInfo &Info;
2547 APValue &NewVal;
2548 const Expr *E;
2549
2550 typedef bool result_type;
2551 static const AccessKinds AccessKind = AK_Assign;
2552
2553 bool checkConst(QualType QT) {
2554 // Assigning to a const object has undefined behavior.
2555 if (QT.isConstQualified()) {
2556 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2557 return false;
2558 }
2559 return true;
2560 }
2561
2562 bool failed() { return false; }
2563 bool found(APValue &Subobj, QualType SubobjType) {
2564 if (!checkConst(SubobjType))
2565 return false;
2566 // We've been given ownership of NewVal, so just swap it in.
2567 Subobj.swap(NewVal);
2568 return true;
2569 }
2570 bool found(APSInt &Value, QualType SubobjType) {
2571 if (!checkConst(SubobjType))
2572 return false;
2573 if (!NewVal.isInt()) {
2574 // Maybe trying to write a cast pointer value into a complex?
2575 Info.Diag(E);
2576 return false;
2577 }
2578 Value = NewVal.getInt();
2579 return true;
2580 }
2581 bool found(APFloat &Value, QualType SubobjType) {
2582 if (!checkConst(SubobjType))
2583 return false;
2584 Value = NewVal.getFloat();
2585 return true;
2586 }
2587 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2588 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2589 }
2590};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002591} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002592
Richard Smith3229b742013-05-05 21:17:10 +00002593const AccessKinds ModifySubobjectHandler::AccessKind;
2594
Richard Smith3da88fa2013-04-26 14:36:30 +00002595/// Update the designated sub-object of an rvalue to the given value.
2596static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002597 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002598 const SubobjectDesignator &Sub,
2599 APValue &NewVal) {
2600 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002601 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002602}
2603
Richard Smith84f6dcf2012-02-02 01:16:57 +00002604/// Find the position where two subobject designators diverge, or equivalently
2605/// the length of the common initial subsequence.
2606static unsigned FindDesignatorMismatch(QualType ObjType,
2607 const SubobjectDesignator &A,
2608 const SubobjectDesignator &B,
2609 bool &WasArrayIndex) {
2610 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2611 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002612 if (!ObjType.isNull() &&
2613 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002614 // Next subobject is an array element.
2615 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2616 WasArrayIndex = true;
2617 return I;
2618 }
Richard Smith66c96992012-02-18 22:04:06 +00002619 if (ObjType->isAnyComplexType())
2620 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2621 else
2622 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002623 } else {
2624 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2625 WasArrayIndex = false;
2626 return I;
2627 }
2628 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2629 // Next subobject is a field.
2630 ObjType = FD->getType();
2631 else
2632 // Next subobject is a base class.
2633 ObjType = QualType();
2634 }
2635 }
2636 WasArrayIndex = false;
2637 return I;
2638}
2639
2640/// Determine whether the given subobject designators refer to elements of the
2641/// same array object.
2642static bool AreElementsOfSameArray(QualType ObjType,
2643 const SubobjectDesignator &A,
2644 const SubobjectDesignator &B) {
2645 if (A.Entries.size() != B.Entries.size())
2646 return false;
2647
George Burgess IVa51c4072015-10-16 01:49:01 +00002648 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002649 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2650 // A is a subobject of the array element.
2651 return false;
2652
2653 // If A (and B) designates an array element, the last entry will be the array
2654 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2655 // of length 1' case, and the entire path must match.
2656 bool WasArrayIndex;
2657 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2658 return CommonLength >= A.Entries.size() - IsArray;
2659}
2660
Richard Smith3229b742013-05-05 21:17:10 +00002661/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002662static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2663 AccessKinds AK, const LValue &LVal,
2664 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002665 if (!LVal.Base) {
2666 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2667 return CompleteObject();
2668 }
2669
Craig Topper36250ad2014-05-12 05:36:57 +00002670 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002671 if (LVal.CallIndex) {
2672 Frame = Info.getCallFrame(LVal.CallIndex);
2673 if (!Frame) {
2674 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2675 << AK << LVal.Base.is<const ValueDecl*>();
2676 NoteLValueLocation(Info, LVal.Base);
2677 return CompleteObject();
2678 }
Richard Smith3229b742013-05-05 21:17:10 +00002679 }
2680
2681 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2682 // is not a constant expression (even if the object is non-volatile). We also
2683 // apply this rule to C++98, in order to conform to the expected 'volatile'
2684 // semantics.
2685 if (LValType.isVolatileQualified()) {
2686 if (Info.getLangOpts().CPlusPlus)
2687 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2688 << AK << LValType;
2689 else
2690 Info.Diag(E);
2691 return CompleteObject();
2692 }
2693
2694 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002695 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002696 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002697
2698 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2699 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2700 // In C++11, constexpr, non-volatile variables initialized with constant
2701 // expressions are constant expressions too. Inside constexpr functions,
2702 // parameters are constant expressions even if they're non-const.
2703 // In C++1y, objects local to a constant expression (those with a Frame) are
2704 // both readable and writable inside constant expressions.
2705 // In C, such things can also be folded, although they are not ICEs.
2706 const VarDecl *VD = dyn_cast<VarDecl>(D);
2707 if (VD) {
2708 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2709 VD = VDef;
2710 }
2711 if (!VD || VD->isInvalidDecl()) {
2712 Info.Diag(E);
2713 return CompleteObject();
2714 }
2715
2716 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002717 if (BaseType.isVolatileQualified()) {
2718 if (Info.getLangOpts().CPlusPlus) {
2719 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2720 << AK << 1 << VD;
2721 Info.Note(VD->getLocation(), diag::note_declared_at);
2722 } else {
2723 Info.Diag(E);
2724 }
2725 return CompleteObject();
2726 }
2727
2728 // Unless we're looking at a local variable or argument in a constexpr call,
2729 // the variable we're reading must be const.
2730 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002731 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002732 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2733 // OK, we can read and modify an object if we're in the process of
2734 // evaluating its initializer, because its lifetime began in this
2735 // evaluation.
2736 } else if (AK != AK_Read) {
2737 // All the remaining cases only permit reading.
2738 Info.Diag(E, diag::note_constexpr_modify_global);
2739 return CompleteObject();
2740 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002741 // OK, we can read this variable.
2742 } else if (BaseType->isIntegralOrEnumerationType()) {
2743 if (!BaseType.isConstQualified()) {
2744 if (Info.getLangOpts().CPlusPlus) {
2745 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2746 Info.Note(VD->getLocation(), diag::note_declared_at);
2747 } else {
2748 Info.Diag(E);
2749 }
2750 return CompleteObject();
2751 }
2752 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2753 // We support folding of const floating-point types, in order to make
2754 // static const data members of such types (supported as an extension)
2755 // more useful.
2756 if (Info.getLangOpts().CPlusPlus11) {
2757 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2758 Info.Note(VD->getLocation(), diag::note_declared_at);
2759 } else {
2760 Info.CCEDiag(E);
2761 }
2762 } else {
2763 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002764 if (Info.checkingPotentialConstantExpression() &&
2765 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2766 // The definition of this variable could be constexpr. We can't
2767 // access it right now, but may be able to in future.
2768 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith3229b742013-05-05 21:17:10 +00002769 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2770 Info.Note(VD->getLocation(), diag::note_declared_at);
2771 } else {
2772 Info.Diag(E);
2773 }
2774 return CompleteObject();
2775 }
2776 }
2777
2778 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2779 return CompleteObject();
2780 } else {
2781 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2782
2783 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002784 if (const MaterializeTemporaryExpr *MTE =
2785 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2786 assert(MTE->getStorageDuration() == SD_Static &&
2787 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002788
Richard Smithe6c01442013-06-05 00:46:14 +00002789 // Per C++1y [expr.const]p2:
2790 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2791 // - a [...] glvalue of integral or enumeration type that refers to
2792 // a non-volatile const object [...]
2793 // [...]
2794 // - a [...] glvalue of literal type that refers to a non-volatile
2795 // object whose lifetime began within the evaluation of e.
2796 //
2797 // C++11 misses the 'began within the evaluation of e' check and
2798 // instead allows all temporaries, including things like:
2799 // int &&r = 1;
2800 // int x = ++r;
2801 // constexpr int k = r;
2802 // Therefore we use the C++1y rules in C++11 too.
2803 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2804 const ValueDecl *ED = MTE->getExtendingDecl();
2805 if (!(BaseType.isConstQualified() &&
2806 BaseType->isIntegralOrEnumerationType()) &&
2807 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2808 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2809 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2810 return CompleteObject();
2811 }
2812
2813 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2814 assert(BaseVal && "got reference to unevaluated temporary");
2815 } else {
2816 Info.Diag(E);
2817 return CompleteObject();
2818 }
2819 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002820 BaseVal = Frame->getTemporary(Base);
2821 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002822 }
Richard Smith3229b742013-05-05 21:17:10 +00002823
2824 // Volatile temporary objects cannot be accessed in constant expressions.
2825 if (BaseType.isVolatileQualified()) {
2826 if (Info.getLangOpts().CPlusPlus) {
2827 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2828 << AK << 0;
2829 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2830 } else {
2831 Info.Diag(E);
2832 }
2833 return CompleteObject();
2834 }
2835 }
2836
Richard Smith7525ff62013-05-09 07:14:00 +00002837 // During the construction of an object, it is not yet 'const'.
2838 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2839 // and this doesn't do quite the right thing for const subobjects of the
2840 // object under construction.
2841 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2842 BaseType = Info.Ctx.getCanonicalType(BaseType);
2843 BaseType.removeLocalConst();
2844 }
2845
Richard Smith6d4c6582013-11-05 22:18:15 +00002846 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002847 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002848 //
2849 // FIXME: Not all local state is mutable. Allow local constant subobjects
2850 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002851 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2852 Info.EvalStatus.HasSideEffects) ||
2853 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002854 return CompleteObject();
2855
2856 return CompleteObject(BaseVal, BaseType);
2857}
2858
Richard Smith243ef902013-05-05 23:31:59 +00002859/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2860/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2861/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002862///
2863/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002864/// \param Conv - The expression for which we are performing the conversion.
2865/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002866/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2867/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002868/// \param LVal - The glvalue on which we are attempting to perform this action.
2869/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002870static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002871 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002872 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002873 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002874 return false;
2875
Richard Smith3229b742013-05-05 21:17:10 +00002876 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002877 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002878 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002879 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2880 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2881 // initializer until now for such expressions. Such an expression can't be
2882 // an ICE in C, so this only matters for fold.
2883 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2884 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002885 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002886 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002887 }
Richard Smith3229b742013-05-05 21:17:10 +00002888 APValue Lit;
2889 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2890 return false;
2891 CompleteObject LitObj(&Lit, Base->getType());
2892 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002893 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002894 // We represent a string literal array as an lvalue pointing at the
2895 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002896 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002897 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2898 CompleteObject StrObj(&Str, Base->getType());
2899 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002900 }
Richard Smith11562c52011-10-28 17:51:58 +00002901 }
2902
Richard Smith3229b742013-05-05 21:17:10 +00002903 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2904 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002905}
2906
2907/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002908static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002910 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002911 return false;
2912
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002913 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002914 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002915 return false;
2916 }
2917
Richard Smith3229b742013-05-05 21:17:10 +00002918 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2919 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002920}
2921
Richard Smith243ef902013-05-05 23:31:59 +00002922static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2923 return T->isSignedIntegerType() &&
2924 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2925}
2926
2927namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002928struct CompoundAssignSubobjectHandler {
2929 EvalInfo &Info;
2930 const Expr *E;
2931 QualType PromotedLHSType;
2932 BinaryOperatorKind Opcode;
2933 const APValue &RHS;
2934
2935 static const AccessKinds AccessKind = AK_Assign;
2936
2937 typedef bool result_type;
2938
2939 bool checkConst(QualType QT) {
2940 // Assigning to a const object has undefined behavior.
2941 if (QT.isConstQualified()) {
2942 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2943 return false;
2944 }
2945 return true;
2946 }
2947
2948 bool failed() { return false; }
2949 bool found(APValue &Subobj, QualType SubobjType) {
2950 switch (Subobj.getKind()) {
2951 case APValue::Int:
2952 return found(Subobj.getInt(), SubobjType);
2953 case APValue::Float:
2954 return found(Subobj.getFloat(), SubobjType);
2955 case APValue::ComplexInt:
2956 case APValue::ComplexFloat:
2957 // FIXME: Implement complex compound assignment.
2958 Info.Diag(E);
2959 return false;
2960 case APValue::LValue:
2961 return foundPointer(Subobj, SubobjType);
2962 default:
2963 // FIXME: can this happen?
2964 Info.Diag(E);
2965 return false;
2966 }
2967 }
2968 bool found(APSInt &Value, QualType SubobjType) {
2969 if (!checkConst(SubobjType))
2970 return false;
2971
2972 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2973 // We don't support compound assignment on integer-cast-to-pointer
2974 // values.
2975 Info.Diag(E);
2976 return false;
2977 }
2978
2979 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2980 SubobjType, Value);
2981 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2982 return false;
2983 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2984 return true;
2985 }
2986 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002987 return checkConst(SubobjType) &&
2988 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2989 Value) &&
2990 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2991 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002992 }
2993 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2994 if (!checkConst(SubobjType))
2995 return false;
2996
2997 QualType PointeeType;
2998 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2999 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003000
3001 if (PointeeType.isNull() || !RHS.isInt() ||
3002 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00003003 Info.Diag(E);
3004 return false;
3005 }
3006
Richard Smith861b5b52013-05-07 23:34:45 +00003007 int64_t Offset = getExtValue(RHS.getInt());
3008 if (Opcode == BO_Sub)
3009 Offset = -Offset;
3010
3011 LValue LVal;
3012 LVal.setFrom(Info.Ctx, Subobj);
3013 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3014 return false;
3015 LVal.moveInto(Subobj);
3016 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003017 }
3018 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3019 llvm_unreachable("shouldn't encounter string elements here");
3020 }
3021};
3022} // end anonymous namespace
3023
3024const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3025
3026/// Perform a compound assignment of LVal <op>= RVal.
3027static bool handleCompoundAssignment(
3028 EvalInfo &Info, const Expr *E,
3029 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3030 BinaryOperatorKind Opcode, const APValue &RVal) {
3031 if (LVal.Designator.Invalid)
3032 return false;
3033
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003034 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00003035 Info.Diag(E);
3036 return false;
3037 }
3038
3039 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3040 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3041 RVal };
3042 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3043}
3044
3045namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003046struct IncDecSubobjectHandler {
3047 EvalInfo &Info;
3048 const Expr *E;
3049 AccessKinds AccessKind;
3050 APValue *Old;
3051
3052 typedef bool result_type;
3053
3054 bool checkConst(QualType QT) {
3055 // Assigning to a const object has undefined behavior.
3056 if (QT.isConstQualified()) {
3057 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
3058 return false;
3059 }
3060 return true;
3061 }
3062
3063 bool failed() { return false; }
3064 bool found(APValue &Subobj, QualType SubobjType) {
3065 // Stash the old value. Also clear Old, so we don't clobber it later
3066 // if we're post-incrementing a complex.
3067 if (Old) {
3068 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003069 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003070 }
3071
3072 switch (Subobj.getKind()) {
3073 case APValue::Int:
3074 return found(Subobj.getInt(), SubobjType);
3075 case APValue::Float:
3076 return found(Subobj.getFloat(), SubobjType);
3077 case APValue::ComplexInt:
3078 return found(Subobj.getComplexIntReal(),
3079 SubobjType->castAs<ComplexType>()->getElementType()
3080 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3081 case APValue::ComplexFloat:
3082 return found(Subobj.getComplexFloatReal(),
3083 SubobjType->castAs<ComplexType>()->getElementType()
3084 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3085 case APValue::LValue:
3086 return foundPointer(Subobj, SubobjType);
3087 default:
3088 // FIXME: can this happen?
3089 Info.Diag(E);
3090 return false;
3091 }
3092 }
3093 bool found(APSInt &Value, QualType SubobjType) {
3094 if (!checkConst(SubobjType))
3095 return false;
3096
3097 if (!SubobjType->isIntegerType()) {
3098 // We don't support increment / decrement on integer-cast-to-pointer
3099 // values.
3100 Info.Diag(E);
3101 return false;
3102 }
3103
3104 if (Old) *Old = APValue(Value);
3105
3106 // bool arithmetic promotes to int, and the conversion back to bool
3107 // doesn't reduce mod 2^n, so special-case it.
3108 if (SubobjType->isBooleanType()) {
3109 if (AccessKind == AK_Increment)
3110 Value = 1;
3111 else
3112 Value = !Value;
3113 return true;
3114 }
3115
3116 bool WasNegative = Value.isNegative();
3117 if (AccessKind == AK_Increment) {
3118 ++Value;
3119
3120 if (!WasNegative && Value.isNegative() &&
3121 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3122 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003123 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003124 }
3125 } else {
3126 --Value;
3127
3128 if (WasNegative && !Value.isNegative() &&
3129 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3130 unsigned BitWidth = Value.getBitWidth();
3131 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3132 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003133 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003134 }
3135 }
3136 return true;
3137 }
3138 bool found(APFloat &Value, QualType SubobjType) {
3139 if (!checkConst(SubobjType))
3140 return false;
3141
3142 if (Old) *Old = APValue(Value);
3143
3144 APFloat One(Value.getSemantics(), 1);
3145 if (AccessKind == AK_Increment)
3146 Value.add(One, APFloat::rmNearestTiesToEven);
3147 else
3148 Value.subtract(One, APFloat::rmNearestTiesToEven);
3149 return true;
3150 }
3151 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3152 if (!checkConst(SubobjType))
3153 return false;
3154
3155 QualType PointeeType;
3156 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3157 PointeeType = PT->getPointeeType();
3158 else {
3159 Info.Diag(E);
3160 return false;
3161 }
3162
3163 LValue LVal;
3164 LVal.setFrom(Info.Ctx, Subobj);
3165 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3166 AccessKind == AK_Increment ? 1 : -1))
3167 return false;
3168 LVal.moveInto(Subobj);
3169 return true;
3170 }
3171 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3172 llvm_unreachable("shouldn't encounter string elements here");
3173 }
3174};
3175} // end anonymous namespace
3176
3177/// Perform an increment or decrement on LVal.
3178static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3179 QualType LValType, bool IsIncrement, APValue *Old) {
3180 if (LVal.Designator.Invalid)
3181 return false;
3182
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003183 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003184 Info.Diag(E);
3185 return false;
3186 }
3187
3188 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3189 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3190 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3191 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3192}
3193
Richard Smithe97cbd72011-11-11 04:05:33 +00003194/// Build an lvalue for the object argument of a member function call.
3195static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3196 LValue &This) {
3197 if (Object->getType()->isPointerType())
3198 return EvaluatePointer(Object, This, Info);
3199
3200 if (Object->isGLValue())
3201 return EvaluateLValue(Object, This, Info);
3202
Richard Smithd9f663b2013-04-22 15:31:51 +00003203 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003204 return EvaluateTemporary(Object, This, Info);
3205
Richard Smith3e79a572014-06-11 19:53:12 +00003206 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003207 return false;
3208}
3209
3210/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3211/// lvalue referring to the result.
3212///
3213/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003214/// \param LV - An lvalue referring to the base of the member pointer.
3215/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003216/// \param IncludeMember - Specifies whether the member itself is included in
3217/// the resulting LValue subobject designator. This is not possible when
3218/// creating a bound member function.
3219/// \return The field or method declaration to which the member pointer refers,
3220/// or 0 if evaluation fails.
3221static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003222 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003223 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003224 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003225 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003226 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003227 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003228 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003229
3230 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3231 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003232 if (!MemPtr.getDecl()) {
3233 // FIXME: Specific diagnostic.
3234 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003235 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003236 }
Richard Smith253c2a32012-01-27 01:14:48 +00003237
Richard Smith027bf112011-11-17 22:56:20 +00003238 if (MemPtr.isDerivedMember()) {
3239 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003240 // The end of the derived-to-base path for the base object must match the
3241 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003242 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003243 LV.Designator.Entries.size()) {
3244 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003245 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003246 }
Richard Smith027bf112011-11-17 22:56:20 +00003247 unsigned PathLengthToMember =
3248 LV.Designator.Entries.size() - MemPtr.Path.size();
3249 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3250 const CXXRecordDecl *LVDecl = getAsBaseClass(
3251 LV.Designator.Entries[PathLengthToMember + I]);
3252 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003253 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3254 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003255 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003256 }
Richard Smith027bf112011-11-17 22:56:20 +00003257 }
3258
3259 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003260 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003261 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003262 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003263 } else if (!MemPtr.Path.empty()) {
3264 // Extend the LValue path with the member pointer's path.
3265 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3266 MemPtr.Path.size() + IncludeMember);
3267
3268 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003269 if (const PointerType *PT = LVType->getAs<PointerType>())
3270 LVType = PT->getPointeeType();
3271 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3272 assert(RD && "member pointer access on non-class-type expression");
3273 // The first class in the path is that of the lvalue.
3274 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3275 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003276 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003277 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003278 RD = Base;
3279 }
3280 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003281 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3282 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003283 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003284 }
3285
3286 // Add the member. Note that we cannot build bound member functions here.
3287 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003288 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003289 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003290 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003291 } else if (const IndirectFieldDecl *IFD =
3292 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003293 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003294 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003295 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003296 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003297 }
Richard Smith027bf112011-11-17 22:56:20 +00003298 }
3299
3300 return MemPtr.getDecl();
3301}
3302
Richard Smith84401042013-06-03 05:03:02 +00003303static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3304 const BinaryOperator *BO,
3305 LValue &LV,
3306 bool IncludeMember = true) {
3307 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3308
3309 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3310 if (Info.keepEvaluatingAfterFailure()) {
3311 MemberPtr MemPtr;
3312 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3313 }
Craig Topper36250ad2014-05-12 05:36:57 +00003314 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003315 }
3316
3317 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3318 BO->getRHS(), IncludeMember);
3319}
3320
Richard Smith027bf112011-11-17 22:56:20 +00003321/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3322/// the provided lvalue, which currently refers to the base object.
3323static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3324 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003325 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003326 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003327 return false;
3328
Richard Smitha8105bc2012-01-06 16:39:00 +00003329 QualType TargetQT = E->getType();
3330 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3331 TargetQT = PT->getPointeeType();
3332
3333 // Check this cast lands within the final derived-to-base subobject path.
3334 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003335 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003336 << D.MostDerivedType << TargetQT;
3337 return false;
3338 }
3339
Richard Smith027bf112011-11-17 22:56:20 +00003340 // Check the type of the final cast. We don't need to check the path,
3341 // since a cast can only be formed if the path is unique.
3342 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003343 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3344 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003345 if (NewEntriesSize == D.MostDerivedPathLength)
3346 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3347 else
Richard Smith027bf112011-11-17 22:56:20 +00003348 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003349 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003350 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003351 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003352 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003353 }
Richard Smith027bf112011-11-17 22:56:20 +00003354
3355 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003356 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003357}
3358
Mike Stump876387b2009-10-27 22:09:17 +00003359namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003360enum EvalStmtResult {
3361 /// Evaluation failed.
3362 ESR_Failed,
3363 /// Hit a 'return' statement.
3364 ESR_Returned,
3365 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003366 ESR_Succeeded,
3367 /// Hit a 'continue' statement.
3368 ESR_Continue,
3369 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003370 ESR_Break,
3371 /// Still scanning for 'case' or 'default' statement.
3372 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003373};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003374}
Richard Smith254a73d2011-10-28 22:34:42 +00003375
Richard Smithd9f663b2013-04-22 15:31:51 +00003376static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3377 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3378 // We don't need to evaluate the initializer for a static local.
3379 if (!VD->hasLocalStorage())
3380 return true;
3381
3382 LValue Result;
3383 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003384 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003385
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003386 const Expr *InitE = VD->getInit();
3387 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003388 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3389 << false << VD->getType();
3390 Val = APValue();
3391 return false;
3392 }
3393
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003394 if (InitE->isValueDependent())
3395 return false;
3396
3397 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003398 // Wipe out any partially-computed value, to allow tracking that this
3399 // evaluation failed.
3400 Val = APValue();
3401 return false;
3402 }
3403 }
3404
3405 return true;
3406}
3407
Richard Smith4e18ca52013-05-06 05:56:11 +00003408/// Evaluate a condition (either a variable declaration or an expression).
3409static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3410 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003411 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003412 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3413 return false;
3414 return EvaluateAsBooleanCondition(Cond, Result, Info);
3415}
3416
Richard Smith89210072016-04-04 23:29:43 +00003417namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003418/// \brief A location where the result (returned value) of evaluating a
3419/// statement should be stored.
3420struct StmtResult {
3421 /// The APValue that should be filled in with the returned value.
3422 APValue &Value;
3423 /// The location containing the result, if any (used to support RVO).
3424 const LValue *Slot;
3425};
Richard Smith89210072016-04-04 23:29:43 +00003426}
Richard Smith52a980a2015-08-28 02:43:42 +00003427
3428static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003429 const Stmt *S,
3430 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003431
3432/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003433static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003434 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003435 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003436 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003437 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003438 case ESR_Break:
3439 return ESR_Succeeded;
3440 case ESR_Succeeded:
3441 case ESR_Continue:
3442 return ESR_Continue;
3443 case ESR_Failed:
3444 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003445 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003446 return ESR;
3447 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003448 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003449}
3450
Richard Smith496ddcf2013-05-12 17:32:42 +00003451/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003452static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003453 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003454 BlockScopeRAII Scope(Info);
3455
Richard Smith496ddcf2013-05-12 17:32:42 +00003456 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003457 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003458 {
3459 FullExpressionRAII Scope(Info);
3460 if (SS->getConditionVariable() &&
3461 !EvaluateDecl(Info, SS->getConditionVariable()))
3462 return ESR_Failed;
3463 if (!EvaluateInteger(SS->getCond(), Value, Info))
3464 return ESR_Failed;
3465 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003466
3467 // Find the switch case corresponding to the value of the condition.
3468 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003469 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003470 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3471 SC = SC->getNextSwitchCase()) {
3472 if (isa<DefaultStmt>(SC)) {
3473 Found = SC;
3474 continue;
3475 }
3476
3477 const CaseStmt *CS = cast<CaseStmt>(SC);
3478 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3479 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3480 : LHS;
3481 if (LHS <= Value && Value <= RHS) {
3482 Found = SC;
3483 break;
3484 }
3485 }
3486
3487 if (!Found)
3488 return ESR_Succeeded;
3489
3490 // Search the switch body for the switch case and evaluate it from there.
3491 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3492 case ESR_Break:
3493 return ESR_Succeeded;
3494 case ESR_Succeeded:
3495 case ESR_Continue:
3496 case ESR_Failed:
3497 case ESR_Returned:
3498 return ESR;
3499 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003500 // This can only happen if the switch case is nested within a statement
3501 // expression. We have no intention of supporting that.
3502 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3503 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003504 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003505 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003506}
3507
Richard Smith254a73d2011-10-28 22:34:42 +00003508// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003509static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003510 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003511 if (!Info.nextStep(S))
3512 return ESR_Failed;
3513
Richard Smith496ddcf2013-05-12 17:32:42 +00003514 // If we're hunting down a 'case' or 'default' label, recurse through
3515 // substatements until we hit the label.
3516 if (Case) {
3517 // FIXME: We don't start the lifetime of objects whose initialization we
3518 // jump over. However, such objects must be of class type with a trivial
3519 // default constructor that initialize all subobjects, so must be empty,
3520 // so this almost never matters.
3521 switch (S->getStmtClass()) {
3522 case Stmt::CompoundStmtClass:
3523 // FIXME: Precompute which substatement of a compound statement we
3524 // would jump to, and go straight there rather than performing a
3525 // linear scan each time.
3526 case Stmt::LabelStmtClass:
3527 case Stmt::AttributedStmtClass:
3528 case Stmt::DoStmtClass:
3529 break;
3530
3531 case Stmt::CaseStmtClass:
3532 case Stmt::DefaultStmtClass:
3533 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003534 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003535 break;
3536
3537 case Stmt::IfStmtClass: {
3538 // FIXME: Precompute which side of an 'if' we would jump to, and go
3539 // straight there rather than scanning both sides.
3540 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003541
3542 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3543 // preceded by our switch label.
3544 BlockScopeRAII Scope(Info);
3545
Richard Smith496ddcf2013-05-12 17:32:42 +00003546 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3547 if (ESR != ESR_CaseNotFound || !IS->getElse())
3548 return ESR;
3549 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3550 }
3551
3552 case Stmt::WhileStmtClass: {
3553 EvalStmtResult ESR =
3554 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3555 if (ESR != ESR_Continue)
3556 return ESR;
3557 break;
3558 }
3559
3560 case Stmt::ForStmtClass: {
3561 const ForStmt *FS = cast<ForStmt>(S);
3562 EvalStmtResult ESR =
3563 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3564 if (ESR != ESR_Continue)
3565 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003566 if (FS->getInc()) {
3567 FullExpressionRAII IncScope(Info);
3568 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3569 return ESR_Failed;
3570 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003571 break;
3572 }
3573
3574 case Stmt::DeclStmtClass:
3575 // FIXME: If the variable has initialization that can't be jumped over,
3576 // bail out of any immediately-surrounding compound-statement too.
3577 default:
3578 return ESR_CaseNotFound;
3579 }
3580 }
3581
Richard Smith254a73d2011-10-28 22:34:42 +00003582 switch (S->getStmtClass()) {
3583 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003584 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003585 // Don't bother evaluating beyond an expression-statement which couldn't
3586 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003587 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003588 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003589 return ESR_Failed;
3590 return ESR_Succeeded;
3591 }
3592
3593 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003594 return ESR_Failed;
3595
3596 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003597 return ESR_Succeeded;
3598
Richard Smithd9f663b2013-04-22 15:31:51 +00003599 case Stmt::DeclStmtClass: {
3600 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003601 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003602 // Each declaration initialization is its own full-expression.
3603 // FIXME: This isn't quite right; if we're performing aggregate
3604 // initialization, each braced subexpression is its own full-expression.
3605 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003606 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003607 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003608 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003609 return ESR_Succeeded;
3610 }
3611
Richard Smith357362d2011-12-13 06:39:58 +00003612 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003613 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003614 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003615 if (RetExpr &&
3616 !(Result.Slot
3617 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3618 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003619 return ESR_Failed;
3620 return ESR_Returned;
3621 }
Richard Smith254a73d2011-10-28 22:34:42 +00003622
3623 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003624 BlockScopeRAII Scope(Info);
3625
Richard Smith254a73d2011-10-28 22:34:42 +00003626 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003627 for (const auto *BI : CS->body()) {
3628 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003629 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003630 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003631 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003632 return ESR;
3633 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003634 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003635 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003636
3637 case Stmt::IfStmtClass: {
3638 const IfStmt *IS = cast<IfStmt>(S);
3639
3640 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003641 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003642 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003643 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003644 return ESR_Failed;
3645
3646 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3647 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3648 if (ESR != ESR_Succeeded)
3649 return ESR;
3650 }
3651 return ESR_Succeeded;
3652 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003653
3654 case Stmt::WhileStmtClass: {
3655 const WhileStmt *WS = cast<WhileStmt>(S);
3656 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003657 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003658 bool Continue;
3659 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3660 Continue))
3661 return ESR_Failed;
3662 if (!Continue)
3663 break;
3664
3665 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3666 if (ESR != ESR_Continue)
3667 return ESR;
3668 }
3669 return ESR_Succeeded;
3670 }
3671
3672 case Stmt::DoStmtClass: {
3673 const DoStmt *DS = cast<DoStmt>(S);
3674 bool Continue;
3675 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003676 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003677 if (ESR != ESR_Continue)
3678 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003679 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003680
Richard Smith08d6a2c2013-07-24 07:11:57 +00003681 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003682 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3683 return ESR_Failed;
3684 } while (Continue);
3685 return ESR_Succeeded;
3686 }
3687
3688 case Stmt::ForStmtClass: {
3689 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003690 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003691 if (FS->getInit()) {
3692 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3693 if (ESR != ESR_Succeeded)
3694 return ESR;
3695 }
3696 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003697 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003698 bool Continue = true;
3699 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3700 FS->getCond(), Continue))
3701 return ESR_Failed;
3702 if (!Continue)
3703 break;
3704
3705 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3706 if (ESR != ESR_Continue)
3707 return ESR;
3708
Richard Smith08d6a2c2013-07-24 07:11:57 +00003709 if (FS->getInc()) {
3710 FullExpressionRAII IncScope(Info);
3711 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3712 return ESR_Failed;
3713 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003714 }
3715 return ESR_Succeeded;
3716 }
3717
Richard Smith896e0d72013-05-06 06:51:17 +00003718 case Stmt::CXXForRangeStmtClass: {
3719 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003720 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003721
3722 // Initialize the __range variable.
3723 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3724 if (ESR != ESR_Succeeded)
3725 return ESR;
3726
3727 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003728 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3729 if (ESR != ESR_Succeeded)
3730 return ESR;
3731 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003732 if (ESR != ESR_Succeeded)
3733 return ESR;
3734
3735 while (true) {
3736 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003737 {
3738 bool Continue = true;
3739 FullExpressionRAII CondExpr(Info);
3740 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3741 return ESR_Failed;
3742 if (!Continue)
3743 break;
3744 }
Richard Smith896e0d72013-05-06 06:51:17 +00003745
3746 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003747 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003748 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3749 if (ESR != ESR_Succeeded)
3750 return ESR;
3751
3752 // Loop body.
3753 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3754 if (ESR != ESR_Continue)
3755 return ESR;
3756
3757 // Increment: ++__begin
3758 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3759 return ESR_Failed;
3760 }
3761
3762 return ESR_Succeeded;
3763 }
3764
Richard Smith496ddcf2013-05-12 17:32:42 +00003765 case Stmt::SwitchStmtClass:
3766 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3767
Richard Smith4e18ca52013-05-06 05:56:11 +00003768 case Stmt::ContinueStmtClass:
3769 return ESR_Continue;
3770
3771 case Stmt::BreakStmtClass:
3772 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003773
3774 case Stmt::LabelStmtClass:
3775 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3776
3777 case Stmt::AttributedStmtClass:
3778 // As a general principle, C++11 attributes can be ignored without
3779 // any semantic impact.
3780 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3781 Case);
3782
3783 case Stmt::CaseStmtClass:
3784 case Stmt::DefaultStmtClass:
3785 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003786 }
3787}
3788
Richard Smithcc36f692011-12-22 02:22:31 +00003789/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3790/// default constructor. If so, we'll fold it whether or not it's marked as
3791/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3792/// so we need special handling.
3793static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003794 const CXXConstructorDecl *CD,
3795 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003796 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3797 return false;
3798
Richard Smith66e05fe2012-01-18 05:21:49 +00003799 // Value-initialization does not call a trivial default constructor, so such a
3800 // call is a core constant expression whether or not the constructor is
3801 // constexpr.
3802 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003803 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003804 // FIXME: If DiagDecl is an implicitly-declared special member function,
3805 // we should be much more explicit about why it's not constexpr.
3806 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3807 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3808 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003809 } else {
3810 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3811 }
3812 }
3813 return true;
3814}
3815
Richard Smith357362d2011-12-13 06:39:58 +00003816/// CheckConstexprFunction - Check that a function can be called in a constant
3817/// expression.
3818static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3819 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003820 const FunctionDecl *Definition,
3821 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003822 // Potential constant expressions can contain calls to declared, but not yet
3823 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003824 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003825 Declaration->isConstexpr())
3826 return false;
3827
Richard Smith0838f3a2013-05-14 05:18:44 +00003828 // Bail out with no diagnostic if the function declaration itself is invalid.
3829 // We will have produced a relevant diagnostic while parsing it.
3830 if (Declaration->isInvalidDecl())
3831 return false;
3832
Richard Smith357362d2011-12-13 06:39:58 +00003833 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003834 if (Definition && Definition->isConstexpr() &&
3835 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003836 return true;
3837
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003838 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003839 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003840 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3841 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003842 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3843 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3844 << DiagDecl;
3845 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3846 } else {
3847 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3848 }
3849 return false;
3850}
3851
Richard Smithbe6dd812014-11-19 21:27:17 +00003852/// Determine if a class has any fields that might need to be copied by a
3853/// trivial copy or move operation.
3854static bool hasFields(const CXXRecordDecl *RD) {
3855 if (!RD || RD->isEmpty())
3856 return false;
3857 for (auto *FD : RD->fields()) {
3858 if (FD->isUnnamedBitfield())
3859 continue;
3860 return true;
3861 }
3862 for (auto &Base : RD->bases())
3863 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3864 return true;
3865 return false;
3866}
3867
Richard Smithd62306a2011-11-10 06:34:14 +00003868namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003869typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003870}
3871
3872/// EvaluateArgs - Evaluate the arguments to a function call.
3873static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3874 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003875 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003876 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003877 I != E; ++I) {
3878 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3879 // If we're checking for a potential constant expression, evaluate all
3880 // initializers even if some of them fail.
3881 if (!Info.keepEvaluatingAfterFailure())
3882 return false;
3883 Success = false;
3884 }
3885 }
3886 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003887}
3888
Richard Smith254a73d2011-10-28 22:34:42 +00003889/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003890static bool HandleFunctionCall(SourceLocation CallLoc,
3891 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003892 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003893 EvalInfo &Info, APValue &Result,
3894 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003895 ArgVector ArgValues(Args.size());
3896 if (!EvaluateArgs(Args, ArgValues, Info))
3897 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003898
Richard Smith253c2a32012-01-27 01:14:48 +00003899 if (!Info.CheckCallLimit(CallLoc))
3900 return false;
3901
3902 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003903
3904 // For a trivial copy or move assignment, perform an APValue copy. This is
3905 // essential for unions, where the operations performed by the assignment
3906 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003907 //
3908 // Skip this for non-union classes with no fields; in that case, the defaulted
3909 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003910 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003911 if (MD && MD->isDefaulted() &&
3912 (MD->getParent()->isUnion() ||
3913 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003914 assert(This &&
3915 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3916 LValue RHS;
3917 RHS.setFrom(Info.Ctx, ArgValues[0]);
3918 APValue RHSValue;
3919 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3920 RHS, RHSValue))
3921 return false;
3922 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3923 RHSValue))
3924 return false;
3925 This->moveInto(Result);
3926 return true;
3927 }
3928
Richard Smith52a980a2015-08-28 02:43:42 +00003929 StmtResult Ret = {Result, ResultSlot};
3930 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003931 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003932 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003933 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003934 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003935 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003936 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003937}
3938
Richard Smithd62306a2011-11-10 06:34:14 +00003939/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003940static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003941 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003942 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003943 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003944 ArgVector ArgValues(Args.size());
3945 if (!EvaluateArgs(Args, ArgValues, Info))
3946 return false;
3947
Richard Smith253c2a32012-01-27 01:14:48 +00003948 if (!Info.CheckCallLimit(CallLoc))
3949 return false;
3950
Richard Smith3607ffe2012-02-13 03:54:03 +00003951 const CXXRecordDecl *RD = Definition->getParent();
3952 if (RD->getNumVBases()) {
3953 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3954 return false;
3955 }
3956
Richard Smith253c2a32012-01-27 01:14:48 +00003957 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003958
Richard Smith52a980a2015-08-28 02:43:42 +00003959 // FIXME: Creating an APValue just to hold a nonexistent return value is
3960 // wasteful.
3961 APValue RetVal;
3962 StmtResult Ret = {RetVal, nullptr};
3963
Richard Smithd62306a2011-11-10 06:34:14 +00003964 // If it's a delegating constructor, just delegate.
3965 if (Definition->isDelegatingConstructor()) {
3966 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003967 {
3968 FullExpressionRAII InitScope(Info);
3969 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3970 return false;
3971 }
Richard Smith52a980a2015-08-28 02:43:42 +00003972 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003973 }
3974
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003975 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003976 // essential for unions (or classes with anonymous union members), where the
3977 // operations performed by the constructor cannot be represented by
3978 // ctor-initializers.
3979 //
3980 // Skip this for empty non-union classes; we should not perform an
3981 // lvalue-to-rvalue conversion on them because their copy constructor does not
3982 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003983 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003984 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003985 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003986 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003987 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003988 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003989 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003990 }
3991
3992 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003993 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003994 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003995 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003996
John McCalld7bca762012-05-01 00:38:49 +00003997 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003998 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3999
Richard Smith08d6a2c2013-07-24 07:11:57 +00004000 // A scope for temporaries lifetime-extended by reference members.
4001 BlockScopeRAII LifetimeExtendedScope(Info);
4002
Richard Smith253c2a32012-01-27 01:14:48 +00004003 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004004 unsigned BasesSeen = 0;
4005#ifndef NDEBUG
4006 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4007#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004008 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004009 LValue Subobject = This;
4010 APValue *Value = &Result;
4011
4012 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004013 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004014 if (I->isBaseInitializer()) {
4015 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004016#ifndef NDEBUG
4017 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004018 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004019 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4020 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4021 "base class initializers not in expected order");
4022 ++BaseIt;
4023#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004024 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004025 BaseType->getAsCXXRecordDecl(), &Layout))
4026 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004027 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004028 } else if ((FD = I->getMember())) {
4029 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004030 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004031 if (RD->isUnion()) {
4032 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004033 Value = &Result.getUnionValue();
4034 } else {
4035 Value = &Result.getStructField(FD->getFieldIndex());
4036 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004037 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004038 // Walk the indirect field decl's chain to find the object to initialize,
4039 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004040 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004041 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004042 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4043 // Switch the union field if it differs. This happens if we had
4044 // preceding zero-initialization, and we're now initializing a union
4045 // subobject other than the first.
4046 // FIXME: In this case, the values of the other subobjects are
4047 // specified, since zero-initialization sets all padding bits to zero.
4048 if (Value->isUninit() ||
4049 (Value->isUnion() && Value->getUnionField() != FD)) {
4050 if (CD->isUnion())
4051 *Value = APValue(FD);
4052 else
4053 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004054 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004055 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004056 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004057 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004058 if (CD->isUnion())
4059 Value = &Value->getUnionValue();
4060 else
4061 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004062 }
Richard Smithd62306a2011-11-10 06:34:14 +00004063 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004064 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004065 }
Richard Smith253c2a32012-01-27 01:14:48 +00004066
Richard Smith08d6a2c2013-07-24 07:11:57 +00004067 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004068 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4069 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004070 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004071 // If we're checking for a potential constant expression, evaluate all
4072 // initializers even if some of them fail.
4073 if (!Info.keepEvaluatingAfterFailure())
4074 return false;
4075 Success = false;
4076 }
Richard Smithd62306a2011-11-10 06:34:14 +00004077 }
4078
Richard Smithd9f663b2013-04-22 15:31:51 +00004079 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004080 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004081}
4082
Eli Friedman9a156e52008-11-12 09:44:48 +00004083//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004084// Generic Evaluation
4085//===----------------------------------------------------------------------===//
4086namespace {
4087
Aaron Ballman68af21c2014-01-03 19:26:43 +00004088template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004089class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004090 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004091private:
Richard Smith52a980a2015-08-28 02:43:42 +00004092 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004093 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004094 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004095 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004096 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004097 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004098 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004099
Richard Smith17100ba2012-02-16 02:46:34 +00004100 // Check whether a conditional operator with a non-constant condition is a
4101 // potential constant expression. If neither arm is a potential constant
4102 // expression, then the conditional operator is not either.
4103 template<typename ConditionalOperator>
4104 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004105 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004106
4107 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004108 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004109 {
Richard Smith17100ba2012-02-16 02:46:34 +00004110 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004111 StmtVisitorTy::Visit(E->getFalseExpr());
4112 if (Diag.empty())
4113 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004114 }
Richard Smith17100ba2012-02-16 02:46:34 +00004115
George Burgess IV8c892b52016-05-25 22:31:54 +00004116 {
4117 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004118 Diag.clear();
4119 StmtVisitorTy::Visit(E->getTrueExpr());
4120 if (Diag.empty())
4121 return;
4122 }
4123
4124 Error(E, diag::note_constexpr_conditional_never_const);
4125 }
4126
4127
4128 template<typename ConditionalOperator>
4129 bool HandleConditionalOperator(const ConditionalOperator *E) {
4130 bool BoolResult;
4131 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004132 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004133 CheckPotentialConstantConditional(E);
4134 return false;
4135 }
4136
4137 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4138 return StmtVisitorTy::Visit(EvalExpr);
4139 }
4140
Peter Collingbournee9200682011-05-13 03:29:01 +00004141protected:
4142 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004143 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004144 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4145
Richard Smith92b1ce02011-12-12 09:28:41 +00004146 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004147 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004148 }
4149
Aaron Ballman68af21c2014-01-03 19:26:43 +00004150 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004151
4152public:
4153 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4154
4155 EvalInfo &getEvalInfo() { return Info; }
4156
Richard Smithf57d8cb2011-12-09 22:58:01 +00004157 /// Report an evaluation error. This should only be called when an error is
4158 /// first discovered. When propagating an error, just return false.
4159 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004160 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004161 return false;
4162 }
4163 bool Error(const Expr *E) {
4164 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4165 }
4166
Aaron Ballman68af21c2014-01-03 19:26:43 +00004167 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004168 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004169 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004170 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004171 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004172 }
4173
Aaron Ballman68af21c2014-01-03 19:26:43 +00004174 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004175 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004176 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004177 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004178 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004179 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004180 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004181 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004182 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004183 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004184 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004185 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004186 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004187 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004188 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004189 // The initializer may not have been parsed yet, or might be erroneous.
4190 if (!E->getExpr())
4191 return Error(E);
4192 return StmtVisitorTy::Visit(E->getExpr());
4193 }
Richard Smith5894a912011-12-19 22:12:41 +00004194 // We cannot create any objects for which cleanups are required, so there is
4195 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004196 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004197 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004198
Aaron Ballman68af21c2014-01-03 19:26:43 +00004199 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004200 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4201 return static_cast<Derived*>(this)->VisitCastExpr(E);
4202 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004203 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004204 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4205 return static_cast<Derived*>(this)->VisitCastExpr(E);
4206 }
4207
Aaron Ballman68af21c2014-01-03 19:26:43 +00004208 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004209 switch (E->getOpcode()) {
4210 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004211 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004212
4213 case BO_Comma:
4214 VisitIgnoredValue(E->getLHS());
4215 return StmtVisitorTy::Visit(E->getRHS());
4216
4217 case BO_PtrMemD:
4218 case BO_PtrMemI: {
4219 LValue Obj;
4220 if (!HandleMemberPointerAccess(Info, E, Obj))
4221 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004222 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004223 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004224 return false;
4225 return DerivedSuccess(Result, E);
4226 }
4227 }
4228 }
4229
Aaron Ballman68af21c2014-01-03 19:26:43 +00004230 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004231 // Evaluate and cache the common expression. We treat it as a temporary,
4232 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004233 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004234 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004235 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004236
Richard Smith17100ba2012-02-16 02:46:34 +00004237 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004238 }
4239
Aaron Ballman68af21c2014-01-03 19:26:43 +00004240 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004241 bool IsBcpCall = false;
4242 // If the condition (ignoring parens) is a __builtin_constant_p call,
4243 // the result is a constant expression if it can be folded without
4244 // side-effects. This is an important GNU extension. See GCC PR38377
4245 // for discussion.
4246 if (const CallExpr *CallCE =
4247 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004248 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004249 IsBcpCall = true;
4250
4251 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4252 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004253 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004254 return false;
4255
Richard Smith6d4c6582013-11-05 22:18:15 +00004256 FoldConstant Fold(Info, IsBcpCall);
4257 if (!HandleConditionalOperator(E)) {
4258 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004259 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004260 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004261
4262 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004263 }
4264
Aaron Ballman68af21c2014-01-03 19:26:43 +00004265 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004266 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4267 return DerivedSuccess(*Value, E);
4268
4269 const Expr *Source = E->getSourceExpr();
4270 if (!Source)
4271 return Error(E);
4272 if (Source == E) { // sanity checking.
4273 assert(0 && "OpaqueValueExpr recursively refers to itself");
4274 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004275 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004276 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004277 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004278
Aaron Ballman68af21c2014-01-03 19:26:43 +00004279 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004280 APValue Result;
4281 if (!handleCallExpr(E, Result, nullptr))
4282 return false;
4283 return DerivedSuccess(Result, E);
4284 }
4285
4286 bool handleCallExpr(const CallExpr *E, APValue &Result,
4287 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004288 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004289 QualType CalleeType = Callee->getType();
4290
Craig Topper36250ad2014-05-12 05:36:57 +00004291 const FunctionDecl *FD = nullptr;
4292 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004293 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004294 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004295
Richard Smithe97cbd72011-11-11 04:05:33 +00004296 // Extract function decl and 'this' pointer from the callee.
4297 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004298 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004299 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4300 // Explicit bound member calls, such as x.f() or p->g();
4301 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004302 return false;
4303 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004304 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004305 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004306 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4307 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004308 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4309 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004310 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004311 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004312 return Error(Callee);
4313
4314 FD = dyn_cast<FunctionDecl>(Member);
4315 if (!FD)
4316 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004317 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004318 LValue Call;
4319 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004320 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004321
Richard Smitha8105bc2012-01-06 16:39:00 +00004322 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004323 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004324 FD = dyn_cast_or_null<FunctionDecl>(
4325 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004326 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004327 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004328
4329 // Overloaded operator calls to member functions are represented as normal
4330 // calls with '*this' as the first argument.
4331 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4332 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004333 // FIXME: When selecting an implicit conversion for an overloaded
4334 // operator delete, we sometimes try to evaluate calls to conversion
4335 // operators without a 'this' parameter!
4336 if (Args.empty())
4337 return Error(E);
4338
Richard Smithe97cbd72011-11-11 04:05:33 +00004339 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4340 return false;
4341 This = &ThisVal;
4342 Args = Args.slice(1);
4343 }
4344
4345 // Don't call function pointers which have been cast to some other type.
4346 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004347 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004348 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004349 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004350
Richard Smith47b34932012-02-01 02:39:43 +00004351 if (This && !This->checkSubobject(Info, E, CSK_This))
4352 return false;
4353
Richard Smith3607ffe2012-02-13 03:54:03 +00004354 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4355 // calls to such functions in constant expressions.
4356 if (This && !HasQualifier &&
4357 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4358 return Error(E, diag::note_constexpr_virtual_call);
4359
Craig Topper36250ad2014-05-12 05:36:57 +00004360 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004361 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004362
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004363 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004364 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4365 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004366 return false;
4367
Richard Smith52a980a2015-08-28 02:43:42 +00004368 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004369 }
4370
Aaron Ballman68af21c2014-01-03 19:26:43 +00004371 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004372 return StmtVisitorTy::Visit(E->getInitializer());
4373 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004374 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004375 if (E->getNumInits() == 0)
4376 return DerivedZeroInitialization(E);
4377 if (E->getNumInits() == 1)
4378 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004379 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004380 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004381 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004382 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004383 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004384 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004385 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004386 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004387 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004388 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004389 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004390
Richard Smithd62306a2011-11-10 06:34:14 +00004391 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004392 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004393 assert(!E->isArrow() && "missing call to bound member function?");
4394
Richard Smith2e312c82012-03-03 22:46:17 +00004395 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004396 if (!Evaluate(Val, Info, E->getBase()))
4397 return false;
4398
4399 QualType BaseTy = E->getBase()->getType();
4400
4401 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004402 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004403 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004404 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004405 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4406
Richard Smith3229b742013-05-05 21:17:10 +00004407 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004408 SubobjectDesignator Designator(BaseTy);
4409 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004410
Richard Smith3229b742013-05-05 21:17:10 +00004411 APValue Result;
4412 return extractSubobject(Info, E, Obj, Designator, Result) &&
4413 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004414 }
4415
Aaron Ballman68af21c2014-01-03 19:26:43 +00004416 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004417 switch (E->getCastKind()) {
4418 default:
4419 break;
4420
Richard Smitha23ab512013-05-23 00:30:41 +00004421 case CK_AtomicToNonAtomic: {
4422 APValue AtomicVal;
4423 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4424 return false;
4425 return DerivedSuccess(AtomicVal, E);
4426 }
4427
Richard Smith11562c52011-10-28 17:51:58 +00004428 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004429 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004430 return StmtVisitorTy::Visit(E->getSubExpr());
4431
4432 case CK_LValueToRValue: {
4433 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004434 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4435 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004436 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004437 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004438 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004439 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004440 return false;
4441 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004442 }
4443 }
4444
Richard Smithf57d8cb2011-12-09 22:58:01 +00004445 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004446 }
4447
Aaron Ballman68af21c2014-01-03 19:26:43 +00004448 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004449 return VisitUnaryPostIncDec(UO);
4450 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004451 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004452 return VisitUnaryPostIncDec(UO);
4453 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004455 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004456 return Error(UO);
4457
4458 LValue LVal;
4459 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4460 return false;
4461 APValue RVal;
4462 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4463 UO->isIncrementOp(), &RVal))
4464 return false;
4465 return DerivedSuccess(RVal, UO);
4466 }
4467
Aaron Ballman68af21c2014-01-03 19:26:43 +00004468 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004469 // We will have checked the full-expressions inside the statement expression
4470 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004471 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004472 return Error(E);
4473
Richard Smith08d6a2c2013-07-24 07:11:57 +00004474 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004475 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004476 if (CS->body_empty())
4477 return true;
4478
Richard Smith51f03172013-06-20 03:00:05 +00004479 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4480 BE = CS->body_end();
4481 /**/; ++BI) {
4482 if (BI + 1 == BE) {
4483 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4484 if (!FinalExpr) {
4485 Info.Diag((*BI)->getLocStart(),
4486 diag::note_constexpr_stmt_expr_unsupported);
4487 return false;
4488 }
4489 return this->Visit(FinalExpr);
4490 }
4491
4492 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004493 StmtResult Result = { ReturnValue, nullptr };
4494 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004495 if (ESR != ESR_Succeeded) {
4496 // FIXME: If the statement-expression terminated due to 'return',
4497 // 'break', or 'continue', it would be nice to propagate that to
4498 // the outer statement evaluation rather than bailing out.
4499 if (ESR != ESR_Failed)
4500 Info.Diag((*BI)->getLocStart(),
4501 diag::note_constexpr_stmt_expr_unsupported);
4502 return false;
4503 }
4504 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004505
4506 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004507 }
4508
Richard Smith4a678122011-10-24 18:44:57 +00004509 /// Visit a value which is evaluated, but whose value is ignored.
4510 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004511 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004512 }
David Majnemere9807b22016-02-26 04:23:19 +00004513
4514 /// Potentially visit a MemberExpr's base expression.
4515 void VisitIgnoredBaseExpression(const Expr *E) {
4516 // While MSVC doesn't evaluate the base expression, it does diagnose the
4517 // presence of side-effecting behavior.
4518 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4519 return;
4520 VisitIgnoredValue(E);
4521 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004522};
4523
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004524}
Peter Collingbournee9200682011-05-13 03:29:01 +00004525
4526//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004527// Common base class for lvalue and temporary evaluation.
4528//===----------------------------------------------------------------------===//
4529namespace {
4530template<class Derived>
4531class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004532 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004533protected:
4534 LValue &Result;
4535 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004536 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004537
4538 bool Success(APValue::LValueBase B) {
4539 Result.set(B);
4540 return true;
4541 }
4542
4543public:
4544 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4545 ExprEvaluatorBaseTy(Info), Result(Result) {}
4546
Richard Smith2e312c82012-03-03 22:46:17 +00004547 bool Success(const APValue &V, const Expr *E) {
4548 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004549 return true;
4550 }
Richard Smith027bf112011-11-17 22:56:20 +00004551
Richard Smith027bf112011-11-17 22:56:20 +00004552 bool VisitMemberExpr(const MemberExpr *E) {
4553 // Handle non-static data members.
4554 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004555 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004556 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004557 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004558 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004559 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004560 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004561 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004562 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004563 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004564 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004565 BaseTy = E->getBase()->getType();
4566 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004567 if (!EvalOK) {
4568 if (!this->Info.allowInvalidBaseExpr())
4569 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004570 Result.setInvalid(E);
4571 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004572 }
Richard Smith027bf112011-11-17 22:56:20 +00004573
Richard Smith1b78b3d2012-01-25 22:15:11 +00004574 const ValueDecl *MD = E->getMemberDecl();
4575 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4576 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4577 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4578 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004579 if (!HandleLValueMember(this->Info, E, Result, FD))
4580 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004581 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004582 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4583 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004584 } else
4585 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004586
Richard Smith1b78b3d2012-01-25 22:15:11 +00004587 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004588 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004589 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004590 RefValue))
4591 return false;
4592 return Success(RefValue, E);
4593 }
4594 return true;
4595 }
4596
4597 bool VisitBinaryOperator(const BinaryOperator *E) {
4598 switch (E->getOpcode()) {
4599 default:
4600 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4601
4602 case BO_PtrMemD:
4603 case BO_PtrMemI:
4604 return HandleMemberPointerAccess(this->Info, E, Result);
4605 }
4606 }
4607
4608 bool VisitCastExpr(const CastExpr *E) {
4609 switch (E->getCastKind()) {
4610 default:
4611 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4612
4613 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004614 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004615 if (!this->Visit(E->getSubExpr()))
4616 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004617
4618 // Now figure out the necessary offset to add to the base LV to get from
4619 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004620 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4621 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004622 }
4623 }
4624};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004625}
Richard Smith027bf112011-11-17 22:56:20 +00004626
4627//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004628// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004629//
4630// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4631// function designators (in C), decl references to void objects (in C), and
4632// temporaries (if building with -Wno-address-of-temporary).
4633//
4634// LValue evaluation produces values comprising a base expression of one of the
4635// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004636// - Declarations
4637// * VarDecl
4638// * FunctionDecl
4639// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004640// * CompoundLiteralExpr in C
4641// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004642// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004643// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004644// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004645// * ObjCEncodeExpr
4646// * AddrLabelExpr
4647// * BlockExpr
4648// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004649// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004650// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004651// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004652// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4653// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004654// * A MaterializeTemporaryExpr that has static storage duration, with no
4655// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004656// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004657//===----------------------------------------------------------------------===//
4658namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004659class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004660 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004661public:
Richard Smith027bf112011-11-17 22:56:20 +00004662 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4663 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004664
Richard Smith11562c52011-10-28 17:51:58 +00004665 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004666 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004667
Peter Collingbournee9200682011-05-13 03:29:01 +00004668 bool VisitDeclRefExpr(const DeclRefExpr *E);
4669 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004670 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004671 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4672 bool VisitMemberExpr(const MemberExpr *E);
4673 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4674 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004675 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004676 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004677 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4678 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004679 bool VisitUnaryReal(const UnaryOperator *E);
4680 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004681 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4682 return VisitUnaryPreIncDec(UO);
4683 }
4684 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4685 return VisitUnaryPreIncDec(UO);
4686 }
Richard Smith3229b742013-05-05 21:17:10 +00004687 bool VisitBinAssign(const BinaryOperator *BO);
4688 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004689
Peter Collingbournee9200682011-05-13 03:29:01 +00004690 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004691 switch (E->getCastKind()) {
4692 default:
Richard Smith027bf112011-11-17 22:56:20 +00004693 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004694
Eli Friedmance3e02a2011-10-11 00:13:24 +00004695 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004696 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004697 if (!Visit(E->getSubExpr()))
4698 return false;
4699 Result.Designator.setInvalid();
4700 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004701
Richard Smith027bf112011-11-17 22:56:20 +00004702 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004703 if (!Visit(E->getSubExpr()))
4704 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004705 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004706 }
4707 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004708};
4709} // end anonymous namespace
4710
Richard Smith11562c52011-10-28 17:51:58 +00004711/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004712/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004713/// * function designators in C, and
4714/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004715/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004716static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4717 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004718 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004719 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004720}
4721
Peter Collingbournee9200682011-05-13 03:29:01 +00004722bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004723 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004724 return Success(FD);
4725 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004726 return VisitVarDecl(E, VD);
4727 return Error(E);
4728}
Richard Smith733237d2011-10-24 23:14:33 +00004729
Richard Smith11562c52011-10-28 17:51:58 +00004730bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004731 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004732 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4733 Frame = Info.CurrentCall;
4734
Richard Smithfec09922011-11-01 16:57:24 +00004735 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004736 if (Frame) {
4737 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004738 return true;
4739 }
Richard Smithce40ad62011-11-12 22:28:03 +00004740 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004741 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004742
Richard Smith3229b742013-05-05 21:17:10 +00004743 APValue *V;
4744 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004746 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004747 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004748 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4749 return false;
4750 }
Richard Smith3229b742013-05-05 21:17:10 +00004751 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004752}
4753
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004754bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4755 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004756 // Walk through the expression to find the materialized temporary itself.
4757 SmallVector<const Expr *, 2> CommaLHSs;
4758 SmallVector<SubobjectAdjustment, 2> Adjustments;
4759 const Expr *Inner = E->GetTemporaryExpr()->
4760 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004761
Richard Smith84401042013-06-03 05:03:02 +00004762 // If we passed any comma operators, evaluate their LHSs.
4763 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4764 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4765 return false;
4766
Richard Smithe6c01442013-06-05 00:46:14 +00004767 // A materialized temporary with static storage duration can appear within the
4768 // result of a constant expression evaluation, so we need to preserve its
4769 // value for use outside this evaluation.
4770 APValue *Value;
4771 if (E->getStorageDuration() == SD_Static) {
4772 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004773 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004774 Result.set(E);
4775 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004776 Value = &Info.CurrentCall->
4777 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004778 Result.set(E, Info.CurrentCall->Index);
4779 }
4780
Richard Smithea4ad5d2013-06-06 08:19:16 +00004781 QualType Type = Inner->getType();
4782
Richard Smith84401042013-06-03 05:03:02 +00004783 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004784 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4785 (E->getStorageDuration() == SD_Static &&
4786 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4787 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004788 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004789 }
Richard Smith84401042013-06-03 05:03:02 +00004790
4791 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004792 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4793 --I;
4794 switch (Adjustments[I].Kind) {
4795 case SubobjectAdjustment::DerivedToBaseAdjustment:
4796 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4797 Type, Result))
4798 return false;
4799 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4800 break;
4801
4802 case SubobjectAdjustment::FieldAdjustment:
4803 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4804 return false;
4805 Type = Adjustments[I].Field->getType();
4806 break;
4807
4808 case SubobjectAdjustment::MemberPointerAdjustment:
4809 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4810 Adjustments[I].Ptr.RHS))
4811 return false;
4812 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4813 break;
4814 }
4815 }
4816
4817 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004818}
4819
Peter Collingbournee9200682011-05-13 03:29:01 +00004820bool
4821LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004822 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4823 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4824 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004825 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004826}
4827
Richard Smith6e525142011-12-27 12:18:28 +00004828bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004829 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004830 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004831
4832 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4833 << E->getExprOperand()->getType()
4834 << E->getExprOperand()->getSourceRange();
4835 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004836}
4837
Francois Pichet0066db92012-04-16 04:08:35 +00004838bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4839 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004840}
Francois Pichet0066db92012-04-16 04:08:35 +00004841
Peter Collingbournee9200682011-05-13 03:29:01 +00004842bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004843 // Handle static data members.
4844 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004845 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004846 return VisitVarDecl(E, VD);
4847 }
4848
Richard Smith254a73d2011-10-28 22:34:42 +00004849 // Handle static member functions.
4850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4851 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004852 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004853 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004854 }
4855 }
4856
Richard Smithd62306a2011-11-10 06:34:14 +00004857 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004858 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004859}
4860
Peter Collingbournee9200682011-05-13 03:29:01 +00004861bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004862 // FIXME: Deal with vectors as array subscript bases.
4863 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004864 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004865
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004866 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004867 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004868
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004869 APSInt Index;
4870 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004871 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004872
Richard Smith861b5b52013-05-07 23:34:45 +00004873 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4874 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004875}
Eli Friedman9a156e52008-11-12 09:44:48 +00004876
Peter Collingbournee9200682011-05-13 03:29:01 +00004877bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004878 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004879}
4880
Richard Smith66c96992012-02-18 22:04:06 +00004881bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4882 if (!Visit(E->getSubExpr()))
4883 return false;
4884 // __real is a no-op on scalar lvalues.
4885 if (E->getSubExpr()->getType()->isAnyComplexType())
4886 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4887 return true;
4888}
4889
4890bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4891 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4892 "lvalue __imag__ on scalar?");
4893 if (!Visit(E->getSubExpr()))
4894 return false;
4895 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4896 return true;
4897}
4898
Richard Smith243ef902013-05-05 23:31:59 +00004899bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004900 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004901 return Error(UO);
4902
4903 if (!this->Visit(UO->getSubExpr()))
4904 return false;
4905
Richard Smith243ef902013-05-05 23:31:59 +00004906 return handleIncDec(
4907 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004908 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004909}
4910
4911bool LValueExprEvaluator::VisitCompoundAssignOperator(
4912 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004913 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004914 return Error(CAO);
4915
Richard Smith3229b742013-05-05 21:17:10 +00004916 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004917
4918 // The overall lvalue result is the result of evaluating the LHS.
4919 if (!this->Visit(CAO->getLHS())) {
4920 if (Info.keepEvaluatingAfterFailure())
4921 Evaluate(RHS, this->Info, CAO->getRHS());
4922 return false;
4923 }
4924
Richard Smith3229b742013-05-05 21:17:10 +00004925 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4926 return false;
4927
Richard Smith43e77732013-05-07 04:50:00 +00004928 return handleCompoundAssignment(
4929 this->Info, CAO,
4930 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4931 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004932}
4933
4934bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004935 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004936 return Error(E);
4937
Richard Smith3229b742013-05-05 21:17:10 +00004938 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004939
4940 if (!this->Visit(E->getLHS())) {
4941 if (Info.keepEvaluatingAfterFailure())
4942 Evaluate(NewVal, this->Info, E->getRHS());
4943 return false;
4944 }
4945
Richard Smith3229b742013-05-05 21:17:10 +00004946 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4947 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004948
4949 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004950 NewVal);
4951}
4952
Eli Friedman9a156e52008-11-12 09:44:48 +00004953//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004954// Pointer Evaluation
4955//===----------------------------------------------------------------------===//
4956
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004957namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004958class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004959 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004960 LValue &Result;
4961
Peter Collingbournee9200682011-05-13 03:29:01 +00004962 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004963 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004964 return true;
4965 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004966public:
Mike Stump11289f42009-09-09 15:08:12 +00004967
John McCall45d55e42010-05-07 21:00:08 +00004968 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004969 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004970
Richard Smith2e312c82012-03-03 22:46:17 +00004971 bool Success(const APValue &V, const Expr *E) {
4972 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004973 return true;
4974 }
Richard Smithfddd3842011-12-30 21:15:51 +00004975 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004976 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004977 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004978
John McCall45d55e42010-05-07 21:00:08 +00004979 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004980 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004981 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004982 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004983 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004984 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004985 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004986 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004987 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004988 bool VisitCallExpr(const CallExpr *E);
4989 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004990 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004991 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004993 }
Richard Smithd62306a2011-11-10 06:34:14 +00004994 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004995 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004996 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004997 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004998 if (!Info.CurrentCall->This) {
4999 if (Info.getLangOpts().CPlusPlus11)
5000 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
5001 else
5002 Info.Diag(E);
5003 return false;
5004 }
Richard Smithd62306a2011-11-10 06:34:14 +00005005 Result = *Info.CurrentCall->This;
5006 return true;
5007 }
John McCallc07a0c72011-02-17 10:25:35 +00005008
Eli Friedman449fe542009-03-23 04:56:01 +00005009 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005010};
Chris Lattner05706e882008-07-11 18:11:29 +00005011} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005012
John McCall45d55e42010-05-07 21:00:08 +00005013static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005014 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005015 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005016}
5017
John McCall45d55e42010-05-07 21:00:08 +00005018bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005019 if (E->getOpcode() != BO_Add &&
5020 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005022
Chris Lattner05706e882008-07-11 18:11:29 +00005023 const Expr *PExp = E->getLHS();
5024 const Expr *IExp = E->getRHS();
5025 if (IExp->getType()->isPointerType())
5026 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Richard Smith253c2a32012-01-27 01:14:48 +00005028 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
5029 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00005030 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005031
John McCall45d55e42010-05-07 21:00:08 +00005032 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005033 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005034 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005035
5036 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005037 if (E->getOpcode() == BO_Sub)
5038 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005039
Ted Kremenek28831752012-08-23 20:46:57 +00005040 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005041 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5042 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005043}
Eli Friedman9a156e52008-11-12 09:44:48 +00005044
John McCall45d55e42010-05-07 21:00:08 +00005045bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5046 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005047}
Mike Stump11289f42009-09-09 15:08:12 +00005048
Peter Collingbournee9200682011-05-13 03:29:01 +00005049bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5050 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005051
Eli Friedman847a2bc2009-12-27 05:43:15 +00005052 switch (E->getCastKind()) {
5053 default:
5054 break;
5055
John McCalle3027922010-08-25 11:45:40 +00005056 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005057 case CK_CPointerToObjCPointerCast:
5058 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005059 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005060 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005061 if (!Visit(SubExpr))
5062 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005063 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5064 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5065 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005066 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005067 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005068 if (SubExpr->getType()->isVoidPointerType())
5069 CCEDiag(E, diag::note_constexpr_invalid_cast)
5070 << 3 << SubExpr->getType();
5071 else
5072 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5073 }
Richard Smith96e0c102011-11-04 02:25:55 +00005074 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005075
Anders Carlsson18275092010-10-31 20:41:46 +00005076 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005077 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005078 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005079 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005080 if (!Result.Base && Result.Offset.isZero())
5081 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005082
Richard Smithd62306a2011-11-10 06:34:14 +00005083 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005084 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005085 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5086 castAs<PointerType>()->getPointeeType(),
5087 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005088
Richard Smith027bf112011-11-17 22:56:20 +00005089 case CK_BaseToDerived:
5090 if (!Visit(E->getSubExpr()))
5091 return false;
5092 if (!Result.Base && Result.Offset.isZero())
5093 return true;
5094 return HandleBaseToDerivedCast(Info, E, Result);
5095
Richard Smith0b0a0b62011-10-29 20:57:55 +00005096 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005097 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005098 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005099
John McCalle3027922010-08-25 11:45:40 +00005100 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005101 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5102
Richard Smith2e312c82012-03-03 22:46:17 +00005103 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005104 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005105 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005106
John McCall45d55e42010-05-07 21:00:08 +00005107 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005108 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5109 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005110 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005111 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005112 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005113 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005114 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005115 return true;
5116 } else {
5117 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005118 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005119 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005120 }
5121 }
John McCalle3027922010-08-25 11:45:40 +00005122 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005123 if (SubExpr->isGLValue()) {
5124 if (!EvaluateLValue(SubExpr, Result, Info))
5125 return false;
5126 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005127 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005128 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005129 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005130 return false;
5131 }
Richard Smith96e0c102011-11-04 02:25:55 +00005132 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005133 if (const ConstantArrayType *CAT
5134 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5135 Result.addArray(Info, E, CAT);
5136 else
5137 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005138 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005139
John McCalle3027922010-08-25 11:45:40 +00005140 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005141 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005142 }
5143
Richard Smith11562c52011-10-28 17:51:58 +00005144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005145}
Chris Lattner05706e882008-07-11 18:11:29 +00005146
Hal Finkel0dd05d42014-10-03 17:18:37 +00005147static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5148 // C++ [expr.alignof]p3:
5149 // When alignof is applied to a reference type, the result is the
5150 // alignment of the referenced type.
5151 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5152 T = Ref->getPointeeType();
5153
5154 // __alignof is defined to return the preferred alignment.
5155 return Info.Ctx.toCharUnitsFromBits(
5156 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5157}
5158
5159static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5160 E = E->IgnoreParens();
5161
5162 // The kinds of expressions that we have special-case logic here for
5163 // should be kept up to date with the special checks for those
5164 // expressions in Sema.
5165
5166 // alignof decl is always accepted, even if it doesn't make sense: we default
5167 // to 1 in those cases.
5168 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5169 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5170 /*RefAsPointee*/true);
5171
5172 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5173 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5174 /*RefAsPointee*/true);
5175
5176 return GetAlignOfType(Info, E->getType());
5177}
5178
Peter Collingbournee9200682011-05-13 03:29:01 +00005179bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005180 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005181 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005182
Alp Tokera724cff2013-12-28 21:59:02 +00005183 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005184 case Builtin::BI__builtin_addressof:
5185 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005186 case Builtin::BI__builtin_assume_aligned: {
5187 // We need to be very careful here because: if the pointer does not have the
5188 // asserted alignment, then the behavior is undefined, and undefined
5189 // behavior is non-constant.
5190 if (!EvaluatePointer(E->getArg(0), Result, Info))
5191 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005192
Hal Finkel0dd05d42014-10-03 17:18:37 +00005193 LValue OffsetResult(Result);
5194 APSInt Alignment;
5195 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5196 return false;
5197 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5198
5199 if (E->getNumArgs() > 2) {
5200 APSInt Offset;
5201 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5202 return false;
5203
5204 int64_t AdditionalOffset = -getExtValue(Offset);
5205 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5206 }
5207
5208 // If there is a base object, then it must have the correct alignment.
5209 if (OffsetResult.Base) {
5210 CharUnits BaseAlignment;
5211 if (const ValueDecl *VD =
5212 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5213 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5214 } else {
5215 BaseAlignment =
5216 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5217 }
5218
5219 if (BaseAlignment < Align) {
5220 Result.Designator.setInvalid();
5221 // FIXME: Quantities here cast to integers because the plural modifier
5222 // does not work on APSInts yet.
5223 CCEDiag(E->getArg(0),
5224 diag::note_constexpr_baa_insufficient_alignment) << 0
5225 << (int) BaseAlignment.getQuantity()
5226 << (unsigned) getExtValue(Alignment);
5227 return false;
5228 }
5229 }
5230
5231 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005232 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005233 Result.Designator.setInvalid();
5234 APSInt Offset(64, false);
5235 Offset = OffsetResult.Offset.getQuantity();
5236
5237 if (OffsetResult.Base)
5238 CCEDiag(E->getArg(0),
5239 diag::note_constexpr_baa_insufficient_alignment) << 1
5240 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5241 else
5242 CCEDiag(E->getArg(0),
5243 diag::note_constexpr_baa_value_insufficient_alignment)
5244 << Offset << (unsigned) getExtValue(Alignment);
5245
5246 return false;
5247 }
5248
5249 return true;
5250 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005251 default:
5252 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5253 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005254}
Chris Lattner05706e882008-07-11 18:11:29 +00005255
5256//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005257// Member Pointer Evaluation
5258//===----------------------------------------------------------------------===//
5259
5260namespace {
5261class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005262 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005263 MemberPtr &Result;
5264
5265 bool Success(const ValueDecl *D) {
5266 Result = MemberPtr(D);
5267 return true;
5268 }
5269public:
5270
5271 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5272 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5273
Richard Smith2e312c82012-03-03 22:46:17 +00005274 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005275 Result.setFrom(V);
5276 return true;
5277 }
Richard Smithfddd3842011-12-30 21:15:51 +00005278 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005279 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005280 }
5281
5282 bool VisitCastExpr(const CastExpr *E);
5283 bool VisitUnaryAddrOf(const UnaryOperator *E);
5284};
5285} // end anonymous namespace
5286
5287static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5288 EvalInfo &Info) {
5289 assert(E->isRValue() && E->getType()->isMemberPointerType());
5290 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5291}
5292
5293bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5294 switch (E->getCastKind()) {
5295 default:
5296 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5297
5298 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005299 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005300 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005301
5302 case CK_BaseToDerivedMemberPointer: {
5303 if (!Visit(E->getSubExpr()))
5304 return false;
5305 if (E->path_empty())
5306 return true;
5307 // Base-to-derived member pointer casts store the path in derived-to-base
5308 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5309 // the wrong end of the derived->base arc, so stagger the path by one class.
5310 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5311 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5312 PathI != PathE; ++PathI) {
5313 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5314 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5315 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005316 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005317 }
5318 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5319 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005320 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005321 return true;
5322 }
5323
5324 case CK_DerivedToBaseMemberPointer:
5325 if (!Visit(E->getSubExpr()))
5326 return false;
5327 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5328 PathE = E->path_end(); PathI != PathE; ++PathI) {
5329 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5330 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5331 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005333 }
5334 return true;
5335 }
5336}
5337
5338bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5339 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5340 // member can be formed.
5341 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5342}
5343
5344//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005345// Record Evaluation
5346//===----------------------------------------------------------------------===//
5347
5348namespace {
5349 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005350 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005351 const LValue &This;
5352 APValue &Result;
5353 public:
5354
5355 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5356 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5357
Richard Smith2e312c82012-03-03 22:46:17 +00005358 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005359 Result = V;
5360 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005361 }
Richard Smithb8348f52016-05-12 22:16:28 +00005362 bool ZeroInitialization(const Expr *E) {
5363 return ZeroInitialization(E, E->getType());
5364 }
5365 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005366
Richard Smith52a980a2015-08-28 02:43:42 +00005367 bool VisitCallExpr(const CallExpr *E) {
5368 return handleCallExpr(E, Result, &This);
5369 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005370 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005371 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005372 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5373 return VisitCXXConstructExpr(E, E->getType());
5374 }
5375 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005376 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005377 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005378}
Richard Smithd62306a2011-11-10 06:34:14 +00005379
Richard Smithfddd3842011-12-30 21:15:51 +00005380/// Perform zero-initialization on an object of non-union class type.
5381/// C++11 [dcl.init]p5:
5382/// To zero-initialize an object or reference of type T means:
5383/// [...]
5384/// -- if T is a (possibly cv-qualified) non-union class type,
5385/// each non-static data member and each base-class subobject is
5386/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005387static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5388 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005389 const LValue &This, APValue &Result) {
5390 assert(!RD->isUnion() && "Expected non-union class type");
5391 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5392 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005393 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005394
John McCalld7bca762012-05-01 00:38:49 +00005395 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005396 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5397
5398 if (CD) {
5399 unsigned Index = 0;
5400 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005401 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005402 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5403 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005404 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5405 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005406 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005407 Result.getStructBase(Index)))
5408 return false;
5409 }
5410 }
5411
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005412 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005413 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005414 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005415 continue;
5416
5417 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005418 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005419 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005420
David Blaikie2d7c57e2012-04-30 02:36:29 +00005421 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005422 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005423 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005424 return false;
5425 }
5426
5427 return true;
5428}
5429
Richard Smithb8348f52016-05-12 22:16:28 +00005430bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5431 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005432 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005433 if (RD->isUnion()) {
5434 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5435 // object's first non-static named data member is zero-initialized
5436 RecordDecl::field_iterator I = RD->field_begin();
5437 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005438 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005439 return true;
5440 }
5441
5442 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005443 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005444 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005445 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005446 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005447 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005448 }
5449
Richard Smith5d108602012-02-17 00:44:16 +00005450 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005451 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005452 return false;
5453 }
5454
Richard Smitha8105bc2012-01-06 16:39:00 +00005455 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005456}
5457
Richard Smithe97cbd72011-11-11 04:05:33 +00005458bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5459 switch (E->getCastKind()) {
5460 default:
5461 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5462
5463 case CK_ConstructorConversion:
5464 return Visit(E->getSubExpr());
5465
5466 case CK_DerivedToBase:
5467 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005468 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005469 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005470 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005471 if (!DerivedObject.isStruct())
5472 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005473
5474 // Derived-to-base rvalue conversion: just slice off the derived part.
5475 APValue *Value = &DerivedObject;
5476 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5477 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5478 PathE = E->path_end(); PathI != PathE; ++PathI) {
5479 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5480 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5481 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5482 RD = Base;
5483 }
5484 Result = *Value;
5485 return true;
5486 }
5487 }
5488}
5489
Richard Smithd62306a2011-11-10 06:34:14 +00005490bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5491 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005492 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5494
5495 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005496 const FieldDecl *Field = E->getInitializedFieldInUnion();
5497 Result = APValue(Field);
5498 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005499 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005500
5501 // If the initializer list for a union does not contain any elements, the
5502 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005503 // FIXME: The element should be initialized from an initializer list.
5504 // Is this difference ever observable for initializer lists which
5505 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005506 ImplicitValueInitExpr VIE(Field->getType());
5507 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5508
Richard Smithd62306a2011-11-10 06:34:14 +00005509 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005510 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5511 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005512
5513 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5514 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5515 isa<CXXDefaultInitExpr>(InitExpr));
5516
Richard Smithb228a862012-02-15 02:18:13 +00005517 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005518 }
5519
Richard Smith872307e2016-03-08 22:17:41 +00005520 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005521 if (Result.isUninit())
5522 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5523 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005524 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005525 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005526
5527 // Initialize base classes.
5528 if (CXXRD) {
5529 for (const auto &Base : CXXRD->bases()) {
5530 assert(ElementNo < E->getNumInits() && "missing init for base class");
5531 const Expr *Init = E->getInit(ElementNo);
5532
5533 LValue Subobject = This;
5534 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5535 return false;
5536
5537 APValue &FieldVal = Result.getStructBase(ElementNo);
5538 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
5539 if (!Info.keepEvaluatingAfterFailure())
5540 return false;
5541 Success = false;
5542 }
5543 ++ElementNo;
5544 }
5545 }
5546
5547 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005548 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005549 // Anonymous bit-fields are not considered members of the class for
5550 // purposes of aggregate initialization.
5551 if (Field->isUnnamedBitfield())
5552 continue;
5553
5554 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005555
Richard Smith253c2a32012-01-27 01:14:48 +00005556 bool HaveInit = ElementNo < E->getNumInits();
5557
5558 // FIXME: Diagnostics here should point to the end of the initializer
5559 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005560 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005561 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005562 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005563
5564 // Perform an implicit value-initialization for members beyond the end of
5565 // the initializer list.
5566 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005567 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005568
Richard Smith852c9db2013-04-20 22:23:05 +00005569 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5570 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5571 isa<CXXDefaultInitExpr>(Init));
5572
Richard Smith49ca8aa2013-08-06 07:09:20 +00005573 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5574 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5575 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005576 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005577 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005578 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005579 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005580 }
5581 }
5582
Richard Smith253c2a32012-01-27 01:14:48 +00005583 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005584}
5585
Richard Smithb8348f52016-05-12 22:16:28 +00005586bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5587 QualType T) {
5588 // Note that E's type is not necessarily the type of our class here; we might
5589 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005590 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005591 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5592
Richard Smithfddd3842011-12-30 21:15:51 +00005593 bool ZeroInit = E->requiresZeroInitialization();
5594 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005595 // If we've already performed zero-initialization, we're already done.
5596 if (!Result.isUninit())
5597 return true;
5598
Richard Smithda3f4fd2014-03-05 23:32:50 +00005599 // We can get here in two different ways:
5600 // 1) We're performing value-initialization, and should zero-initialize
5601 // the object, or
5602 // 2) We're performing default-initialization of an object with a trivial
5603 // constexpr default constructor, in which case we should start the
5604 // lifetimes of all the base subobjects (there can be no data member
5605 // subobjects in this case) per [basic.life]p1.
5606 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005607 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005608 }
5609
Craig Topper36250ad2014-05-12 05:36:57 +00005610 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005611 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005612
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005613 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005614 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005615
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005616 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005617 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005618 if (const MaterializeTemporaryExpr *ME
5619 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5620 return Visit(ME->GetTemporaryExpr());
5621
Richard Smithb8348f52016-05-12 22:16:28 +00005622 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005623 return false;
5624
Craig Topper5fc8fc22014-08-27 06:28:36 +00005625 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005626 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005627 cast<CXXConstructorDecl>(Definition), Info,
5628 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005629}
5630
Richard Smithcc1b96d2013-06-12 22:31:48 +00005631bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5632 const CXXStdInitializerListExpr *E) {
5633 const ConstantArrayType *ArrayType =
5634 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5635
5636 LValue Array;
5637 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5638 return false;
5639
5640 // Get a pointer to the first element of the array.
5641 Array.addArray(Info, E, ArrayType);
5642
5643 // FIXME: Perform the checks on the field types in SemaInit.
5644 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5645 RecordDecl::field_iterator Field = Record->field_begin();
5646 if (Field == Record->field_end())
5647 return Error(E);
5648
5649 // Start pointer.
5650 if (!Field->getType()->isPointerType() ||
5651 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5652 ArrayType->getElementType()))
5653 return Error(E);
5654
5655 // FIXME: What if the initializer_list type has base classes, etc?
5656 Result = APValue(APValue::UninitStruct(), 0, 2);
5657 Array.moveInto(Result.getStructField(0));
5658
5659 if (++Field == Record->field_end())
5660 return Error(E);
5661
5662 if (Field->getType()->isPointerType() &&
5663 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5664 ArrayType->getElementType())) {
5665 // End pointer.
5666 if (!HandleLValueArrayAdjustment(Info, E, Array,
5667 ArrayType->getElementType(),
5668 ArrayType->getSize().getZExtValue()))
5669 return false;
5670 Array.moveInto(Result.getStructField(1));
5671 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5672 // Length.
5673 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5674 else
5675 return Error(E);
5676
5677 if (++Field != Record->field_end())
5678 return Error(E);
5679
5680 return true;
5681}
5682
Richard Smithd62306a2011-11-10 06:34:14 +00005683static bool EvaluateRecord(const Expr *E, const LValue &This,
5684 APValue &Result, EvalInfo &Info) {
5685 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005686 "can't evaluate expression as a record rvalue");
5687 return RecordExprEvaluator(Info, This, Result).Visit(E);
5688}
5689
5690//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005691// Temporary Evaluation
5692//
5693// Temporaries are represented in the AST as rvalues, but generally behave like
5694// lvalues. The full-object of which the temporary is a subobject is implicitly
5695// materialized so that a reference can bind to it.
5696//===----------------------------------------------------------------------===//
5697namespace {
5698class TemporaryExprEvaluator
5699 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5700public:
5701 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5702 LValueExprEvaluatorBaseTy(Info, Result) {}
5703
5704 /// Visit an expression which constructs the value of this temporary.
5705 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005706 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005707 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5708 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005709 }
5710
5711 bool VisitCastExpr(const CastExpr *E) {
5712 switch (E->getCastKind()) {
5713 default:
5714 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5715
5716 case CK_ConstructorConversion:
5717 return VisitConstructExpr(E->getSubExpr());
5718 }
5719 }
5720 bool VisitInitListExpr(const InitListExpr *E) {
5721 return VisitConstructExpr(E);
5722 }
5723 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5724 return VisitConstructExpr(E);
5725 }
5726 bool VisitCallExpr(const CallExpr *E) {
5727 return VisitConstructExpr(E);
5728 }
Richard Smith513955c2014-12-17 19:24:30 +00005729 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5730 return VisitConstructExpr(E);
5731 }
Richard Smith027bf112011-11-17 22:56:20 +00005732};
5733} // end anonymous namespace
5734
5735/// Evaluate an expression of record type as a temporary.
5736static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005737 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005738 return TemporaryExprEvaluator(Info, Result).Visit(E);
5739}
5740
5741//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005742// Vector Evaluation
5743//===----------------------------------------------------------------------===//
5744
5745namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005746 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005747 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005748 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005749 public:
Mike Stump11289f42009-09-09 15:08:12 +00005750
Richard Smith2d406342011-10-22 21:10:00 +00005751 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5752 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005753
Craig Topper9798b932015-09-29 04:30:05 +00005754 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005755 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5756 // FIXME: remove this APValue copy.
5757 Result = APValue(V.data(), V.size());
5758 return true;
5759 }
Richard Smith2e312c82012-03-03 22:46:17 +00005760 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005761 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005762 Result = V;
5763 return true;
5764 }
Richard Smithfddd3842011-12-30 21:15:51 +00005765 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005766
Richard Smith2d406342011-10-22 21:10:00 +00005767 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005768 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005769 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005770 bool VisitInitListExpr(const InitListExpr *E);
5771 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005772 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005773 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005774 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005775 };
5776} // end anonymous namespace
5777
5778static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005779 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005780 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005781}
5782
George Burgess IV533ff002015-12-11 00:23:35 +00005783bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005784 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005785 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005786
Richard Smith161f09a2011-12-06 22:44:34 +00005787 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005788 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005789
Eli Friedmanc757de22011-03-25 00:43:55 +00005790 switch (E->getCastKind()) {
5791 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005792 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005793 if (SETy->isIntegerType()) {
5794 APSInt IntResult;
5795 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005796 return false;
5797 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005798 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005799 APFloat FloatResult(0.0);
5800 if (!EvaluateFloat(SE, FloatResult, Info))
5801 return false;
5802 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005803 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005804 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005805 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005806
5807 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005808 SmallVector<APValue, 4> Elts(NElts, Val);
5809 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005810 }
Eli Friedman803acb32011-12-22 03:51:45 +00005811 case CK_BitCast: {
5812 // Evaluate the operand into an APInt we can extract from.
5813 llvm::APInt SValInt;
5814 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5815 return false;
5816 // Extract the elements
5817 QualType EltTy = VTy->getElementType();
5818 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5819 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5820 SmallVector<APValue, 4> Elts;
5821 if (EltTy->isRealFloatingType()) {
5822 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005823 unsigned FloatEltSize = EltSize;
5824 if (&Sem == &APFloat::x87DoubleExtended)
5825 FloatEltSize = 80;
5826 for (unsigned i = 0; i < NElts; i++) {
5827 llvm::APInt Elt;
5828 if (BigEndian)
5829 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5830 else
5831 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005832 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005833 }
5834 } else if (EltTy->isIntegerType()) {
5835 for (unsigned i = 0; i < NElts; i++) {
5836 llvm::APInt Elt;
5837 if (BigEndian)
5838 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5839 else
5840 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5841 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5842 }
5843 } else {
5844 return Error(E);
5845 }
5846 return Success(Elts, E);
5847 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005848 default:
Richard Smith11562c52011-10-28 17:51:58 +00005849 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005850 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005851}
5852
Richard Smith2d406342011-10-22 21:10:00 +00005853bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005854VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005855 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005856 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005857 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005858
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005859 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005860 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005861
Eli Friedmanb9c71292012-01-03 23:24:20 +00005862 // The number of initializers can be less than the number of
5863 // vector elements. For OpenCL, this can be due to nested vector
5864 // initialization. For GCC compatibility, missing trailing elements
5865 // should be initialized with zeroes.
5866 unsigned CountInits = 0, CountElts = 0;
5867 while (CountElts < NumElements) {
5868 // Handle nested vector initialization.
5869 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005870 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005871 APValue v;
5872 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5873 return Error(E);
5874 unsigned vlen = v.getVectorLength();
5875 for (unsigned j = 0; j < vlen; j++)
5876 Elements.push_back(v.getVectorElt(j));
5877 CountElts += vlen;
5878 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005879 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005880 if (CountInits < NumInits) {
5881 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005882 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005883 } else // trailing integer zero.
5884 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5885 Elements.push_back(APValue(sInt));
5886 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005887 } else {
5888 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005889 if (CountInits < NumInits) {
5890 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005891 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005892 } else // trailing float zero.
5893 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5894 Elements.push_back(APValue(f));
5895 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005896 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005897 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005898 }
Richard Smith2d406342011-10-22 21:10:00 +00005899 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005900}
5901
Richard Smith2d406342011-10-22 21:10:00 +00005902bool
Richard Smithfddd3842011-12-30 21:15:51 +00005903VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005904 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005905 QualType EltTy = VT->getElementType();
5906 APValue ZeroElement;
5907 if (EltTy->isIntegerType())
5908 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5909 else
5910 ZeroElement =
5911 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5912
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005913 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005914 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005915}
5916
Richard Smith2d406342011-10-22 21:10:00 +00005917bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005918 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005919 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005920}
5921
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005922//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005923// Array Evaluation
5924//===----------------------------------------------------------------------===//
5925
5926namespace {
5927 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005928 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005929 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005930 APValue &Result;
5931 public:
5932
Richard Smithd62306a2011-11-10 06:34:14 +00005933 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5934 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005935
5936 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005937 assert((V.isArray() || V.isLValue()) &&
5938 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005939 Result = V;
5940 return true;
5941 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005942
Richard Smithfddd3842011-12-30 21:15:51 +00005943 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005944 const ConstantArrayType *CAT =
5945 Info.Ctx.getAsConstantArrayType(E->getType());
5946 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005947 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005948
5949 Result = APValue(APValue::UninitArray(), 0,
5950 CAT->getSize().getZExtValue());
5951 if (!Result.hasArrayFiller()) return true;
5952
Richard Smithfddd3842011-12-30 21:15:51 +00005953 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005954 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005955 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005956 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005957 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005958 }
5959
Richard Smith52a980a2015-08-28 02:43:42 +00005960 bool VisitCallExpr(const CallExpr *E) {
5961 return handleCallExpr(E, Result, &This);
5962 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005963 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005964 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005965 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5966 const LValue &Subobject,
5967 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005968 };
5969} // end anonymous namespace
5970
Richard Smithd62306a2011-11-10 06:34:14 +00005971static bool EvaluateArray(const Expr *E, const LValue &This,
5972 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005973 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005974 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005975}
5976
5977bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5978 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5979 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005980 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005981
Richard Smithca2cfbf2011-12-22 01:07:19 +00005982 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5983 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005984 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005985 LValue LV;
5986 if (!EvaluateLValue(E->getInit(0), LV, Info))
5987 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005988 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005989 LV.moveInto(Val);
5990 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005991 }
5992
Richard Smith253c2a32012-01-27 01:14:48 +00005993 bool Success = true;
5994
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005995 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5996 "zero-initialized array shouldn't have any initialized elts");
5997 APValue Filler;
5998 if (Result.isArray() && Result.hasArrayFiller())
5999 Filler = Result.getArrayFiller();
6000
Richard Smith9543c5e2013-04-22 14:44:29 +00006001 unsigned NumEltsToInit = E->getNumInits();
6002 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006003 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006004
6005 // If the initializer might depend on the array index, run it for each
6006 // array element. For now, just whitelist non-class value-initialization.
6007 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6008 NumEltsToInit = NumElts;
6009
6010 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006011
6012 // If the array was previously zero-initialized, preserve the
6013 // zero-initialized values.
6014 if (!Filler.isUninit()) {
6015 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6016 Result.getArrayInitializedElt(I) = Filler;
6017 if (Result.hasArrayFiller())
6018 Result.getArrayFiller() = Filler;
6019 }
6020
Richard Smithd62306a2011-11-10 06:34:14 +00006021 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006022 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006023 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6024 const Expr *Init =
6025 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006026 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006027 Info, Subobject, Init) ||
6028 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006029 CAT->getElementType(), 1)) {
6030 if (!Info.keepEvaluatingAfterFailure())
6031 return false;
6032 Success = false;
6033 }
Richard Smithd62306a2011-11-10 06:34:14 +00006034 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006035
Richard Smith9543c5e2013-04-22 14:44:29 +00006036 if (!Result.hasArrayFiller())
6037 return Success;
6038
6039 // If we get here, we have a trivial filler, which we can just evaluate
6040 // once and splat over the rest of the array elements.
6041 assert(FillerExpr && "no array filler for incomplete init list");
6042 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6043 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006044}
6045
Richard Smith027bf112011-11-17 22:56:20 +00006046bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006047 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6048}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006049
Richard Smith9543c5e2013-04-22 14:44:29 +00006050bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6051 const LValue &Subobject,
6052 APValue *Value,
6053 QualType Type) {
6054 bool HadZeroInit = !Value->isUninit();
6055
6056 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6057 unsigned N = CAT->getSize().getZExtValue();
6058
6059 // Preserve the array filler if we had prior zero-initialization.
6060 APValue Filler =
6061 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6062 : APValue();
6063
6064 *Value = APValue(APValue::UninitArray(), N, N);
6065
6066 if (HadZeroInit)
6067 for (unsigned I = 0; I != N; ++I)
6068 Value->getArrayInitializedElt(I) = Filler;
6069
6070 // Initialize the elements.
6071 LValue ArrayElt = Subobject;
6072 ArrayElt.addArray(Info, E, CAT);
6073 for (unsigned I = 0; I != N; ++I)
6074 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6075 CAT->getElementType()) ||
6076 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6077 CAT->getElementType(), 1))
6078 return false;
6079
6080 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006081 }
Richard Smith027bf112011-11-17 22:56:20 +00006082
Richard Smith9543c5e2013-04-22 14:44:29 +00006083 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006084 return Error(E);
6085
Richard Smithb8348f52016-05-12 22:16:28 +00006086 return RecordExprEvaluator(Info, Subobject, *Value)
6087 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006088}
6089
Richard Smithf3e9e432011-11-07 09:22:26 +00006090//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006091// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006092//
6093// As a GNU extension, we support casting pointers to sufficiently-wide integer
6094// types and back in constant folding. Integer values are thus represented
6095// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006096//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006097
6098namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006099class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006100 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006101 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006102public:
Richard Smith2e312c82012-03-03 22:46:17 +00006103 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006104 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006106 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006107 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006108 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006109 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006110 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006111 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006112 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006113 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006114 return true;
6115 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006116 bool Success(const llvm::APSInt &SI, const Expr *E) {
6117 return Success(SI, E, Result);
6118 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006119
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006120 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006121 assert(E->getType()->isIntegralOrEnumerationType() &&
6122 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006123 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006124 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006125 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006126 Result.getInt().setIsUnsigned(
6127 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006128 return true;
6129 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006130 bool Success(const llvm::APInt &I, const Expr *E) {
6131 return Success(I, E, Result);
6132 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006134 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006135 assert(E->getType()->isIntegralOrEnumerationType() &&
6136 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006137 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006138 return true;
6139 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006140 bool Success(uint64_t Value, const Expr *E) {
6141 return Success(Value, E, Result);
6142 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006143
Ken Dyckdbc01912011-03-11 02:13:43 +00006144 bool Success(CharUnits Size, const Expr *E) {
6145 return Success(Size.getQuantity(), E);
6146 }
6147
Richard Smith2e312c82012-03-03 22:46:17 +00006148 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006149 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006150 Result = V;
6151 return true;
6152 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006153 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006154 }
Mike Stump11289f42009-09-09 15:08:12 +00006155
Richard Smithfddd3842011-12-30 21:15:51 +00006156 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006157
Peter Collingbournee9200682011-05-13 03:29:01 +00006158 //===--------------------------------------------------------------------===//
6159 // Visitor Methods
6160 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006161
Chris Lattner7174bf32008-07-12 00:38:25 +00006162 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006163 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006164 }
6165 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006166 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006167 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006168
6169 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6170 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006171 if (CheckReferencedDecl(E, E->getDecl()))
6172 return true;
6173
6174 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006175 }
6176 bool VisitMemberExpr(const MemberExpr *E) {
6177 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006178 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006179 return true;
6180 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006181
6182 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006183 }
6184
Peter Collingbournee9200682011-05-13 03:29:01 +00006185 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006186 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006187 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006188 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006189
Peter Collingbournee9200682011-05-13 03:29:01 +00006190 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006191 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006192
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006193 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006194 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
Ted Kremeneke65b0862012-03-06 20:05:56 +00006197 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6198 return Success(E->getValue(), E);
6199 }
6200
Richard Smith4ce706a2011-10-11 21:43:33 +00006201 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006202 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006203 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006204 }
6205
Douglas Gregor29c42f22012-02-24 07:38:34 +00006206 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6207 return Success(E->getValue(), E);
6208 }
6209
John Wiegley6242b6a2011-04-28 00:16:57 +00006210 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6211 return Success(E->getValue(), E);
6212 }
6213
John Wiegleyf9f65842011-04-25 06:54:41 +00006214 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6215 return Success(E->getValue(), E);
6216 }
6217
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006218 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006219 bool VisitUnaryImag(const UnaryOperator *E);
6220
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006221 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006222 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006223
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006224private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006225 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006226 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006227};
Chris Lattner05706e882008-07-11 18:11:29 +00006228} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006229
Richard Smith11562c52011-10-28 17:51:58 +00006230/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6231/// produce either the integer value or a pointer.
6232///
6233/// GCC has a heinous extension which folds casts between pointer types and
6234/// pointer-sized integral types. We support this by allowing the evaluation of
6235/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6236/// Some simple arithmetic on such values is supported (they are treated much
6237/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006238static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006239 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006240 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006241 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006242}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006243
Richard Smithf57d8cb2011-12-09 22:58:01 +00006244static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006245 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006246 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006247 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006248 if (!Val.isInt()) {
6249 // FIXME: It would be better to produce the diagnostic for casting
6250 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006251 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006252 return false;
6253 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006254 Result = Val.getInt();
6255 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006256}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006257
Richard Smithf57d8cb2011-12-09 22:58:01 +00006258/// Check whether the given declaration can be directly converted to an integral
6259/// rvalue. If not, no diagnostic is produced; there are other things we can
6260/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006261bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006262 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006263 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006264 // Check for signedness/width mismatches between E type and ECD value.
6265 bool SameSign = (ECD->getInitVal().isSigned()
6266 == E->getType()->isSignedIntegerOrEnumerationType());
6267 bool SameWidth = (ECD->getInitVal().getBitWidth()
6268 == Info.Ctx.getIntWidth(E->getType()));
6269 if (SameSign && SameWidth)
6270 return Success(ECD->getInitVal(), E);
6271 else {
6272 // Get rid of mismatch (otherwise Success assertions will fail)
6273 // by computing a new value matching the type of E.
6274 llvm::APSInt Val = ECD->getInitVal();
6275 if (!SameSign)
6276 Val.setIsSigned(!ECD->getInitVal().isSigned());
6277 if (!SameWidth)
6278 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6279 return Success(Val, E);
6280 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006281 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006282 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006283}
6284
Chris Lattner86ee2862008-10-06 06:40:35 +00006285/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6286/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006287static int EvaluateBuiltinClassifyType(const CallExpr *E,
6288 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006289 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006290 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006291 enum gcc_type_class {
6292 no_type_class = -1,
6293 void_type_class, integer_type_class, char_type_class,
6294 enumeral_type_class, boolean_type_class,
6295 pointer_type_class, reference_type_class, offset_type_class,
6296 real_type_class, complex_type_class,
6297 function_type_class, method_type_class,
6298 record_type_class, union_type_class,
6299 array_type_class, string_type_class,
6300 lang_type_class
6301 };
Mike Stump11289f42009-09-09 15:08:12 +00006302
6303 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006304 // ideal, however it is what gcc does.
6305 if (E->getNumArgs() == 0)
6306 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006307
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006308 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6309 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6310
6311 switch (CanTy->getTypeClass()) {
6312#define TYPE(ID, BASE)
6313#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6314#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6315#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6316#include "clang/AST/TypeNodes.def"
6317 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6318
6319 case Type::Builtin:
6320 switch (BT->getKind()) {
6321#define BUILTIN_TYPE(ID, SINGLETON_ID)
6322#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6323#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6324#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6325#include "clang/AST/BuiltinTypes.def"
6326 case BuiltinType::Void:
6327 return void_type_class;
6328
6329 case BuiltinType::Bool:
6330 return boolean_type_class;
6331
6332 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6333 case BuiltinType::UChar:
6334 case BuiltinType::UShort:
6335 case BuiltinType::UInt:
6336 case BuiltinType::ULong:
6337 case BuiltinType::ULongLong:
6338 case BuiltinType::UInt128:
6339 return integer_type_class;
6340
6341 case BuiltinType::NullPtr:
6342 return pointer_type_class;
6343
6344 case BuiltinType::WChar_U:
6345 case BuiltinType::Char16:
6346 case BuiltinType::Char32:
6347 case BuiltinType::ObjCId:
6348 case BuiltinType::ObjCClass:
6349 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006350#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6351 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006352#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006353 case BuiltinType::OCLSampler:
6354 case BuiltinType::OCLEvent:
6355 case BuiltinType::OCLClkEvent:
6356 case BuiltinType::OCLQueue:
6357 case BuiltinType::OCLNDRange:
6358 case BuiltinType::OCLReserveID:
6359 case BuiltinType::Dependent:
6360 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6361 };
6362
6363 case Type::Enum:
6364 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6365 break;
6366
6367 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006368 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006369 break;
6370
6371 case Type::MemberPointer:
6372 if (CanTy->isMemberDataPointerType())
6373 return offset_type_class;
6374 else {
6375 // We expect member pointers to be either data or function pointers,
6376 // nothing else.
6377 assert(CanTy->isMemberFunctionPointerType());
6378 return method_type_class;
6379 }
6380
6381 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006382 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006383
6384 case Type::FunctionNoProto:
6385 case Type::FunctionProto:
6386 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6387
6388 case Type::Record:
6389 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6390 switch (RT->getDecl()->getTagKind()) {
6391 case TagTypeKind::TTK_Struct:
6392 case TagTypeKind::TTK_Class:
6393 case TagTypeKind::TTK_Interface:
6394 return record_type_class;
6395
6396 case TagTypeKind::TTK_Enum:
6397 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6398
6399 case TagTypeKind::TTK_Union:
6400 return union_type_class;
6401 }
6402 }
David Blaikie83d382b2011-09-23 05:06:16 +00006403 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006404
6405 case Type::ConstantArray:
6406 case Type::VariableArray:
6407 case Type::IncompleteArray:
6408 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6409
6410 case Type::BlockPointer:
6411 case Type::LValueReference:
6412 case Type::RValueReference:
6413 case Type::Vector:
6414 case Type::ExtVector:
6415 case Type::Auto:
6416 case Type::ObjCObject:
6417 case Type::ObjCInterface:
6418 case Type::ObjCObjectPointer:
6419 case Type::Pipe:
6420 case Type::Atomic:
6421 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6422 }
6423
6424 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006425}
6426
Richard Smith5fab0c92011-12-28 19:48:30 +00006427/// EvaluateBuiltinConstantPForLValue - Determine the result of
6428/// __builtin_constant_p when applied to the given lvalue.
6429///
6430/// An lvalue is only "constant" if it is a pointer or reference to the first
6431/// character of a string literal.
6432template<typename LValue>
6433static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006434 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006435 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6436}
6437
6438/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6439/// GCC as we can manage.
6440static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6441 QualType ArgType = Arg->getType();
6442
6443 // __builtin_constant_p always has one operand. The rules which gcc follows
6444 // are not precisely documented, but are as follows:
6445 //
6446 // - If the operand is of integral, floating, complex or enumeration type,
6447 // and can be folded to a known value of that type, it returns 1.
6448 // - If the operand and can be folded to a pointer to the first character
6449 // of a string literal (or such a pointer cast to an integral type), it
6450 // returns 1.
6451 //
6452 // Otherwise, it returns 0.
6453 //
6454 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6455 // its support for this does not currently work.
6456 if (ArgType->isIntegralOrEnumerationType()) {
6457 Expr::EvalResult Result;
6458 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6459 return false;
6460
6461 APValue &V = Result.Val;
6462 if (V.getKind() == APValue::Int)
6463 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006464 if (V.getKind() == APValue::LValue)
6465 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006466 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6467 return Arg->isEvaluatable(Ctx);
6468 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6469 LValue LV;
6470 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006471 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006472 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6473 : EvaluatePointer(Arg, LV, Info)) &&
6474 !Status.HasSideEffects)
6475 return EvaluateBuiltinConstantPForLValue(LV);
6476 }
6477
6478 // Anything else isn't considered to be sufficiently constant.
6479 return false;
6480}
6481
John McCall95007602010-05-10 23:27:23 +00006482/// Retrieves the "underlying object type" of the given expression,
6483/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006484static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006485 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6486 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006487 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006488 } else if (const Expr *E = B.get<const Expr*>()) {
6489 if (isa<CompoundLiteralExpr>(E))
6490 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006491 }
6492
6493 return QualType();
6494}
6495
George Burgess IV3a03fab2015-09-04 21:28:13 +00006496/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006497/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6498/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006499/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6500///
6501/// Always returns an RValue with a pointer representation.
6502static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6503 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6504
6505 auto *NoParens = E->IgnoreParens();
6506 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006507 if (Cast == nullptr)
6508 return NoParens;
6509
6510 // We only conservatively allow a few kinds of casts, because this code is
6511 // inherently a simple solution that seeks to support the common case.
6512 auto CastKind = Cast->getCastKind();
6513 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6514 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006515 return NoParens;
6516
6517 auto *SubExpr = Cast->getSubExpr();
6518 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6519 return NoParens;
6520 return ignorePointerCastsAndParens(SubExpr);
6521}
6522
George Burgess IVa51c4072015-10-16 01:49:01 +00006523/// Checks to see if the given LValue's Designator is at the end of the LValue's
6524/// record layout. e.g.
6525/// struct { struct { int a, b; } fst, snd; } obj;
6526/// obj.fst // no
6527/// obj.snd // yes
6528/// obj.fst.a // no
6529/// obj.fst.b // no
6530/// obj.snd.a // no
6531/// obj.snd.b // yes
6532///
6533/// Please note: this function is specialized for how __builtin_object_size
6534/// views "objects".
6535static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6536 assert(!LVal.Designator.Invalid);
6537
6538 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6539 if (FD->getParent()->isUnion())
6540 return true;
6541 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6542 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6543 };
6544
6545 auto &Base = LVal.getLValueBase();
6546 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6547 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6548 if (!IsLastFieldDecl(FD))
6549 return false;
6550 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6551 for (auto *FD : IFD->chain())
6552 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6553 return false;
6554 }
6555 }
6556
6557 QualType BaseType = getType(Base);
6558 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6559 if (BaseType->isArrayType()) {
6560 // Because __builtin_object_size treats arrays as objects, we can ignore
6561 // the index iff this is the last array in the Designator.
6562 if (I + 1 == E)
6563 return true;
6564 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6565 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6566 if (Index + 1 != CAT->getSize())
6567 return false;
6568 BaseType = CAT->getElementType();
6569 } else if (BaseType->isAnyComplexType()) {
6570 auto *CT = BaseType->castAs<ComplexType>();
6571 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6572 if (Index != 1)
6573 return false;
6574 BaseType = CT->getElementType();
6575 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6576 if (!IsLastFieldDecl(FD))
6577 return false;
6578 BaseType = FD->getType();
6579 } else {
6580 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6581 "Expecting cast to a base class");
6582 return false;
6583 }
6584 }
6585 return true;
6586}
6587
6588/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6589static bool refersToCompleteObject(const LValue &LVal) {
6590 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6591 return false;
6592
6593 if (!LVal.InvalidBase)
6594 return true;
6595
6596 auto *E = LVal.Base.dyn_cast<const Expr *>();
6597 (void)E;
6598 assert(E != nullptr && isa<MemberExpr>(E));
6599 return false;
6600}
6601
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006602/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6603/// true and stores the result in @p Size.
6604///
6605/// If @p WasError is non-null, this will report whether the failure to evaluate
6606/// is to be treated as an Error in IntExprEvaluator.
6607static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6608 EvalInfo &Info, uint64_t &Size,
6609 bool *WasError = nullptr) {
6610 if (WasError != nullptr)
6611 *WasError = false;
6612
6613 auto Error = [&](const Expr *E) {
6614 if (WasError != nullptr)
6615 *WasError = true;
6616 return false;
6617 };
6618
6619 auto Success = [&](uint64_t S, const Expr *E) {
6620 Size = S;
6621 return true;
6622 };
6623
George Burgess IVbdb5b262015-08-19 02:19:07 +00006624 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006625 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006626 {
6627 // The operand of __builtin_object_size is never evaluated for side-effects.
6628 // If there are any, but we can determine the pointed-to object anyway, then
6629 // ignore the side-effects.
6630 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006631 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006632
6633 if (E->isGLValue()) {
6634 // It's possible for us to be given GLValues if we're called via
6635 // Expr::tryEvaluateObjectSize.
6636 APValue RVal;
6637 if (!EvaluateAsRValue(Info, E, RVal))
6638 return false;
6639 Base.setFrom(Info.Ctx, RVal);
6640 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006641 return false;
6642 }
John McCall95007602010-05-10 23:27:23 +00006643
George Burgess IVbdb5b262015-08-19 02:19:07 +00006644 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006645 // If we point to before the start of the object, there are no accessible
6646 // bytes.
6647 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006648 return Success(0, E);
6649
George Burgess IV3a03fab2015-09-04 21:28:13 +00006650 // In the case where we're not dealing with a subobject, we discard the
6651 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006652 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006653
6654 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6655 // exist. If we can't verify the base, then we can't do that.
6656 //
6657 // As a special case, we produce a valid object size for an unknown object
6658 // with a known designator if Type & 1 is 1. For instance:
6659 //
6660 // extern struct X { char buff[32]; int a, b, c; } *p;
6661 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6662 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6663 //
6664 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006665 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006666 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006667
George Burgess IVa51c4072015-10-16 01:49:01 +00006668 // If we're not examining only the subobject, then we reset to a complete
6669 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006670 //
6671 // If Type is 1 and we've lost track of the subobject, just find the complete
6672 // object instead. (If Type is 3, that's not correct behavior and we should
6673 // return 0 instead.)
6674 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006675 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006676 QualType T = getObjectType(End.getLValueBase());
6677 if (T.isNull())
6678 End.Designator.setInvalid();
6679 else {
6680 End.Designator = SubobjectDesignator(T);
6681 End.Offset = CharUnits::Zero();
6682 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006683 }
John McCall95007602010-05-10 23:27:23 +00006684
George Burgess IVbdb5b262015-08-19 02:19:07 +00006685 // If it is not possible to determine which objects ptr points to at compile
6686 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6687 // and (size_t) 0 for type 2 or 3.
6688 if (End.Designator.Invalid)
6689 return false;
6690
6691 // According to the GCC documentation, we want the size of the subobject
6692 // denoted by the pointer. But that's not quite right -- what we actually
6693 // want is the size of the immediately-enclosing array, if there is one.
6694 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006695 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006696 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6697 // We got a pointer to an array. Step to its end.
6698 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006699 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006700 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006701 // We're already pointing at the end of the object.
6702 AmountToAdd = 0;
6703 }
6704
George Burgess IV3a03fab2015-09-04 21:28:13 +00006705 QualType PointeeType = End.Designator.MostDerivedType;
6706 assert(!PointeeType.isNull());
6707 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006708 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006709
George Burgess IVbdb5b262015-08-19 02:19:07 +00006710 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6711 AmountToAdd))
6712 return false;
John McCall95007602010-05-10 23:27:23 +00006713
George Burgess IVbdb5b262015-08-19 02:19:07 +00006714 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006715
6716 // The following is a moderately common idiom in C:
6717 //
6718 // struct Foo { int a; char c[1]; };
6719 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6720 // strcpy(&F->c[0], Bar);
6721 //
6722 // So, if we see that we're examining a 1-length (or 0-length) array at the
6723 // end of a struct with an unknown base, we give up instead of breaking code
6724 // that behaves this way. Note that we only do this when Type=1, because
6725 // Type=3 is a lower bound, so answering conservatively is fine.
6726 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6727 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6728 End.Designator.MostDerivedIsArrayElement &&
6729 End.Designator.MostDerivedArraySize < 2 &&
6730 isDesignatorAtObjectEnd(Info.Ctx, End))
6731 return false;
6732
George Burgess IVbdb5b262015-08-19 02:19:07 +00006733 if (BaseOffset > EndOffset)
6734 return Success(0, E);
6735
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006736 return Success((EndOffset - BaseOffset).getQuantity(), E);
6737}
6738
6739bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6740 unsigned Type) {
6741 uint64_t Size;
6742 bool WasError;
6743 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6744 return Success(Size, E);
6745 if (WasError)
6746 return Error(E);
6747 return false;
John McCall95007602010-05-10 23:27:23 +00006748}
6749
Peter Collingbournee9200682011-05-13 03:29:01 +00006750bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006751 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006752 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006753 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006754
6755 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006756 // The type was checked when we built the expression.
6757 unsigned Type =
6758 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6759 assert(Type <= 3 && "unexpected type");
6760
6761 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006762 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006763
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006764 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006765 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006766
Richard Smith01ade172012-05-23 04:13:20 +00006767 // Expression had no side effects, but we couldn't statically determine the
6768 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006769 switch (Info.EvalMode) {
6770 case EvalInfo::EM_ConstantExpression:
6771 case EvalInfo::EM_PotentialConstantExpression:
6772 case EvalInfo::EM_ConstantFold:
6773 case EvalInfo::EM_EvaluateForOverflow:
6774 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006775 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006776 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006777 return Error(E);
6778 case EvalInfo::EM_ConstantExpressionUnevaluated:
6779 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006780 // Reduce it to a constant now.
6781 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006782 }
Mike Stump722cedf2009-10-26 18:35:08 +00006783 }
6784
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006785 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006786 case Builtin::BI__builtin_bswap32:
6787 case Builtin::BI__builtin_bswap64: {
6788 APSInt Val;
6789 if (!EvaluateInteger(E->getArg(0), Val, Info))
6790 return false;
6791
6792 return Success(Val.byteSwap(), E);
6793 }
6794
Richard Smith8889a3d2013-06-13 06:26:32 +00006795 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006796 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006797
6798 // FIXME: BI__builtin_clrsb
6799 // FIXME: BI__builtin_clrsbl
6800 // FIXME: BI__builtin_clrsbll
6801
Richard Smith80b3c8e2013-06-13 05:04:16 +00006802 case Builtin::BI__builtin_clz:
6803 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006804 case Builtin::BI__builtin_clzll:
6805 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006806 APSInt Val;
6807 if (!EvaluateInteger(E->getArg(0), Val, Info))
6808 return false;
6809 if (!Val)
6810 return Error(E);
6811
6812 return Success(Val.countLeadingZeros(), E);
6813 }
6814
Richard Smith8889a3d2013-06-13 06:26:32 +00006815 case Builtin::BI__builtin_constant_p:
6816 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6817
Richard Smith80b3c8e2013-06-13 05:04:16 +00006818 case Builtin::BI__builtin_ctz:
6819 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006820 case Builtin::BI__builtin_ctzll:
6821 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006822 APSInt Val;
6823 if (!EvaluateInteger(E->getArg(0), Val, Info))
6824 return false;
6825 if (!Val)
6826 return Error(E);
6827
6828 return Success(Val.countTrailingZeros(), E);
6829 }
6830
Richard Smith8889a3d2013-06-13 06:26:32 +00006831 case Builtin::BI__builtin_eh_return_data_regno: {
6832 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6833 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6834 return Success(Operand, E);
6835 }
6836
6837 case Builtin::BI__builtin_expect:
6838 return Visit(E->getArg(0));
6839
6840 case Builtin::BI__builtin_ffs:
6841 case Builtin::BI__builtin_ffsl:
6842 case Builtin::BI__builtin_ffsll: {
6843 APSInt Val;
6844 if (!EvaluateInteger(E->getArg(0), Val, Info))
6845 return false;
6846
6847 unsigned N = Val.countTrailingZeros();
6848 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6849 }
6850
6851 case Builtin::BI__builtin_fpclassify: {
6852 APFloat Val(0.0);
6853 if (!EvaluateFloat(E->getArg(5), Val, Info))
6854 return false;
6855 unsigned Arg;
6856 switch (Val.getCategory()) {
6857 case APFloat::fcNaN: Arg = 0; break;
6858 case APFloat::fcInfinity: Arg = 1; break;
6859 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6860 case APFloat::fcZero: Arg = 4; break;
6861 }
6862 return Visit(E->getArg(Arg));
6863 }
6864
6865 case Builtin::BI__builtin_isinf_sign: {
6866 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006867 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006868 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6869 }
6870
Richard Smithea3019d2013-10-15 19:07:14 +00006871 case Builtin::BI__builtin_isinf: {
6872 APFloat Val(0.0);
6873 return EvaluateFloat(E->getArg(0), Val, Info) &&
6874 Success(Val.isInfinity() ? 1 : 0, E);
6875 }
6876
6877 case Builtin::BI__builtin_isfinite: {
6878 APFloat Val(0.0);
6879 return EvaluateFloat(E->getArg(0), Val, Info) &&
6880 Success(Val.isFinite() ? 1 : 0, E);
6881 }
6882
6883 case Builtin::BI__builtin_isnan: {
6884 APFloat Val(0.0);
6885 return EvaluateFloat(E->getArg(0), Val, Info) &&
6886 Success(Val.isNaN() ? 1 : 0, E);
6887 }
6888
6889 case Builtin::BI__builtin_isnormal: {
6890 APFloat Val(0.0);
6891 return EvaluateFloat(E->getArg(0), Val, Info) &&
6892 Success(Val.isNormal() ? 1 : 0, E);
6893 }
6894
Richard Smith8889a3d2013-06-13 06:26:32 +00006895 case Builtin::BI__builtin_parity:
6896 case Builtin::BI__builtin_parityl:
6897 case Builtin::BI__builtin_parityll: {
6898 APSInt Val;
6899 if (!EvaluateInteger(E->getArg(0), Val, Info))
6900 return false;
6901
6902 return Success(Val.countPopulation() % 2, E);
6903 }
6904
Richard Smith80b3c8e2013-06-13 05:04:16 +00006905 case Builtin::BI__builtin_popcount:
6906 case Builtin::BI__builtin_popcountl:
6907 case Builtin::BI__builtin_popcountll: {
6908 APSInt Val;
6909 if (!EvaluateInteger(E->getArg(0), Val, Info))
6910 return false;
6911
6912 return Success(Val.countPopulation(), E);
6913 }
6914
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006915 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006916 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006917 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006918 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006919 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6920 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006921 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006922 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006923 case Builtin::BI__builtin_strlen: {
6924 // As an extension, we support __builtin_strlen() as a constant expression,
6925 // and support folding strlen() to a constant.
6926 LValue String;
6927 if (!EvaluatePointer(E->getArg(0), String, Info))
6928 return false;
6929
6930 // Fast path: if it's a string literal, search the string value.
6931 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6932 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006933 // The string literal may have embedded null characters. Find the first
6934 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006935 StringRef Str = S->getBytes();
6936 int64_t Off = String.Offset.getQuantity();
6937 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6938 S->getCharByteWidth() == 1) {
6939 Str = Str.substr(Off);
6940
6941 StringRef::size_type Pos = Str.find(0);
6942 if (Pos != StringRef::npos)
6943 Str = Str.substr(0, Pos);
6944
6945 return Success(Str.size(), E);
6946 }
6947
6948 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006949 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006950
6951 // Slow path: scan the bytes of the string looking for the terminating 0.
6952 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6953 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6954 APValue Char;
6955 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6956 !Char.isInt())
6957 return false;
6958 if (!Char.getInt())
6959 return Success(Strlen, E);
6960 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6961 return false;
6962 }
6963 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006964
Richard Smith01ba47d2012-04-13 00:45:38 +00006965 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006966 case Builtin::BI__atomic_is_lock_free:
6967 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006968 APSInt SizeVal;
6969 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6970 return false;
6971
6972 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6973 // of two less than the maximum inline atomic width, we know it is
6974 // lock-free. If the size isn't a power of two, or greater than the
6975 // maximum alignment where we promote atomics, we know it is not lock-free
6976 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6977 // the answer can only be determined at runtime; for example, 16-byte
6978 // atomics have lock-free implementations on some, but not all,
6979 // x86-64 processors.
6980
6981 // Check power-of-two.
6982 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006983 if (Size.isPowerOfTwo()) {
6984 // Check against inlining width.
6985 unsigned InlineWidthBits =
6986 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6987 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6988 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6989 Size == CharUnits::One() ||
6990 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6991 Expr::NPC_NeverValueDependent))
6992 // OK, we will inline appropriately-aligned operations of this size,
6993 // and _Atomic(T) is appropriately-aligned.
6994 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006995
Richard Smith01ba47d2012-04-13 00:45:38 +00006996 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6997 castAs<PointerType>()->getPointeeType();
6998 if (!PointeeType->isIncompleteType() &&
6999 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7000 // OK, we will inline operations on this object.
7001 return Success(1, E);
7002 }
7003 }
7004 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007005
Richard Smith01ba47d2012-04-13 00:45:38 +00007006 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7007 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007008 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007009 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007010}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007011
Richard Smith8b3497e2011-10-31 01:37:14 +00007012static bool HasSameBase(const LValue &A, const LValue &B) {
7013 if (!A.getLValueBase())
7014 return !B.getLValueBase();
7015 if (!B.getLValueBase())
7016 return false;
7017
Richard Smithce40ad62011-11-12 22:28:03 +00007018 if (A.getLValueBase().getOpaqueValue() !=
7019 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007020 const Decl *ADecl = GetLValueBaseDecl(A);
7021 if (!ADecl)
7022 return false;
7023 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007024 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007025 return false;
7026 }
7027
7028 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007029 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007030}
7031
Richard Smithd20f1e62014-10-21 23:01:04 +00007032/// \brief Determine whether this is a pointer past the end of the complete
7033/// object referred to by the lvalue.
7034static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7035 const LValue &LV) {
7036 // A null pointer can be viewed as being "past the end" but we don't
7037 // choose to look at it that way here.
7038 if (!LV.getLValueBase())
7039 return false;
7040
7041 // If the designator is valid and refers to a subobject, we're not pointing
7042 // past the end.
7043 if (!LV.getLValueDesignator().Invalid &&
7044 !LV.getLValueDesignator().isOnePastTheEnd())
7045 return false;
7046
David Majnemerc378ca52015-08-29 08:32:55 +00007047 // A pointer to an incomplete type might be past-the-end if the type's size is
7048 // zero. We cannot tell because the type is incomplete.
7049 QualType Ty = getType(LV.getLValueBase());
7050 if (Ty->isIncompleteType())
7051 return true;
7052
Richard Smithd20f1e62014-10-21 23:01:04 +00007053 // We're a past-the-end pointer if we point to the byte after the object,
7054 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007055 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007056 return LV.getLValueOffset() == Size;
7057}
7058
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007059namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007060
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007061/// \brief Data recursive integer evaluator of certain binary operators.
7062///
7063/// We use a data recursive algorithm for binary operators so that we are able
7064/// to handle extreme cases of chained binary operators without causing stack
7065/// overflow.
7066class DataRecursiveIntBinOpEvaluator {
7067 struct EvalResult {
7068 APValue Val;
7069 bool Failed;
7070
7071 EvalResult() : Failed(false) { }
7072
7073 void swap(EvalResult &RHS) {
7074 Val.swap(RHS.Val);
7075 Failed = RHS.Failed;
7076 RHS.Failed = false;
7077 }
7078 };
7079
7080 struct Job {
7081 const Expr *E;
7082 EvalResult LHSResult; // meaningful only for binary operator expression.
7083 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007084
David Blaikie73726062015-08-12 23:09:24 +00007085 Job() = default;
7086 Job(Job &&J)
7087 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
George Burgess IV8c892b52016-05-25 22:31:54 +00007088 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
David Blaikie73726062015-08-12 23:09:24 +00007089
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007090 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007091 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007092 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007093
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007094 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007095 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007096 };
7097
7098 SmallVector<Job, 16> Queue;
7099
7100 IntExprEvaluator &IntEval;
7101 EvalInfo &Info;
7102 APValue &FinalResult;
7103
7104public:
7105 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7106 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7107
7108 /// \brief True if \param E is a binary operator that we are going to handle
7109 /// data recursively.
7110 /// We handle binary operators that are comma, logical, or that have operands
7111 /// with integral or enumeration type.
7112 static bool shouldEnqueue(const BinaryOperator *E) {
7113 return E->getOpcode() == BO_Comma ||
7114 E->isLogicalOp() ||
7115 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7116 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007117 }
7118
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007119 bool Traverse(const BinaryOperator *E) {
7120 enqueue(E);
7121 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007122 while (!Queue.empty())
7123 process(PrevResult);
7124
7125 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007126
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007127 FinalResult.swap(PrevResult.Val);
7128 return true;
7129 }
7130
7131private:
7132 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7133 return IntEval.Success(Value, E, Result);
7134 }
7135 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7136 return IntEval.Success(Value, E, Result);
7137 }
7138 bool Error(const Expr *E) {
7139 return IntEval.Error(E);
7140 }
7141 bool Error(const Expr *E, diag::kind D) {
7142 return IntEval.Error(E, D);
7143 }
7144
7145 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7146 return Info.CCEDiag(E, D);
7147 }
7148
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007149 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7150 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007151 bool &SuppressRHSDiags);
7152
7153 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7154 const BinaryOperator *E, APValue &Result);
7155
7156 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7157 Result.Failed = !Evaluate(Result.Val, Info, E);
7158 if (Result.Failed)
7159 Result.Val = APValue();
7160 }
7161
Richard Trieuba4d0872012-03-21 23:30:30 +00007162 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007163
7164 void enqueue(const Expr *E) {
7165 E = E->IgnoreParens();
7166 Queue.resize(Queue.size()+1);
7167 Queue.back().E = E;
7168 Queue.back().Kind = Job::AnyExprKind;
7169 }
7170};
7171
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007172}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007173
7174bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007175 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007176 bool &SuppressRHSDiags) {
7177 if (E->getOpcode() == BO_Comma) {
7178 // Ignore LHS but note if we could not evaluate it.
7179 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007180 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007181 return true;
7182 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007183
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007184 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007185 bool LHSAsBool;
7186 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007187 // We were able to evaluate the LHS, see if we can get away with not
7188 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007189 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7190 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007191 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007192 }
7193 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007194 LHSResult.Failed = true;
7195
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007196 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007197 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007198 if (!Info.noteSideEffect())
7199 return false;
7200
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007201 // We can't evaluate the LHS; however, sometimes the result
7202 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7203 // Don't ignore RHS and suppress diagnostics from this arm.
7204 SuppressRHSDiags = true;
7205 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007206
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007207 return true;
7208 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007209
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007210 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7211 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007212
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007213 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007214 return false; // Ignore RHS;
7215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007216 return true;
7217}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007219bool DataRecursiveIntBinOpEvaluator::
7220 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7221 const BinaryOperator *E, APValue &Result) {
7222 if (E->getOpcode() == BO_Comma) {
7223 if (RHSResult.Failed)
7224 return false;
7225 Result = RHSResult.Val;
7226 return true;
7227 }
7228
7229 if (E->isLogicalOp()) {
7230 bool lhsResult, rhsResult;
7231 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7232 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7233
7234 if (LHSIsOK) {
7235 if (RHSIsOK) {
7236 if (E->getOpcode() == BO_LOr)
7237 return Success(lhsResult || rhsResult, E, Result);
7238 else
7239 return Success(lhsResult && rhsResult, E, Result);
7240 }
7241 } else {
7242 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007243 // We can't evaluate the LHS; however, sometimes the result
7244 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7245 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007246 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007247 }
7248 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007249
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007250 return false;
7251 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007252
7253 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7254 E->getRHS()->getType()->isIntegralOrEnumerationType());
7255
7256 if (LHSResult.Failed || RHSResult.Failed)
7257 return false;
7258
7259 const APValue &LHSVal = LHSResult.Val;
7260 const APValue &RHSVal = RHSResult.Val;
7261
7262 // Handle cases like (unsigned long)&a + 4.
7263 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7264 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007265 CharUnits AdditionalOffset =
7266 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007267 if (E->getOpcode() == BO_Add)
7268 Result.getLValueOffset() += AdditionalOffset;
7269 else
7270 Result.getLValueOffset() -= AdditionalOffset;
7271 return true;
7272 }
7273
7274 // Handle cases like 4 + (unsigned long)&a
7275 if (E->getOpcode() == BO_Add &&
7276 RHSVal.isLValue() && LHSVal.isInt()) {
7277 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007278 Result.getLValueOffset() +=
7279 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007280 return true;
7281 }
7282
7283 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7284 // Handle (intptr_t)&&A - (intptr_t)&&B.
7285 if (!LHSVal.getLValueOffset().isZero() ||
7286 !RHSVal.getLValueOffset().isZero())
7287 return false;
7288 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7289 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7290 if (!LHSExpr || !RHSExpr)
7291 return false;
7292 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7293 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7294 if (!LHSAddrExpr || !RHSAddrExpr)
7295 return false;
7296 // Make sure both labels come from the same function.
7297 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7298 RHSAddrExpr->getLabel()->getDeclContext())
7299 return false;
7300 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7301 return true;
7302 }
Richard Smith43e77732013-05-07 04:50:00 +00007303
7304 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007305 if (!LHSVal.isInt() || !RHSVal.isInt())
7306 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007307
7308 // Set up the width and signedness manually, in case it can't be deduced
7309 // from the operation we're performing.
7310 // FIXME: Don't do this in the cases where we can deduce it.
7311 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7312 E->getType()->isUnsignedIntegerOrEnumerationType());
7313 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7314 RHSVal.getInt(), Value))
7315 return false;
7316 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007317}
7318
Richard Trieuba4d0872012-03-21 23:30:30 +00007319void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007320 Job &job = Queue.back();
7321
7322 switch (job.Kind) {
7323 case Job::AnyExprKind: {
7324 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7325 if (shouldEnqueue(Bop)) {
7326 job.Kind = Job::BinOpKind;
7327 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007328 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007329 }
7330 }
7331
7332 EvaluateExpr(job.E, Result);
7333 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007334 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007335 }
7336
7337 case Job::BinOpKind: {
7338 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007339 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007340 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007341 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007342 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007343 }
7344 if (SuppressRHSDiags)
7345 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007346 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007347 job.Kind = Job::BinOpVisitedLHSKind;
7348 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007349 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007350 }
7351
7352 case Job::BinOpVisitedLHSKind: {
7353 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7354 EvalResult RHS;
7355 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007356 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007357 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007358 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007359 }
7360 }
7361
7362 llvm_unreachable("Invalid Job::Kind!");
7363}
7364
George Burgess IV8c892b52016-05-25 22:31:54 +00007365namespace {
7366/// Used when we determine that we should fail, but can keep evaluating prior to
7367/// noting that we had a failure.
7368class DelayedNoteFailureRAII {
7369 EvalInfo &Info;
7370 bool NoteFailure;
7371
7372public:
7373 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7374 : Info(Info), NoteFailure(NoteFailure) {}
7375 ~DelayedNoteFailureRAII() {
7376 if (NoteFailure) {
7377 bool ContinueAfterFailure = Info.noteFailure();
7378 (void)ContinueAfterFailure;
7379 assert(ContinueAfterFailure &&
7380 "Shouldn't have kept evaluating on failure.");
7381 }
7382 }
7383};
7384}
7385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007386bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007387 // We don't call noteFailure immediately because the assignment happens after
7388 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007389 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007390 return Error(E);
7391
George Burgess IV8c892b52016-05-25 22:31:54 +00007392 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007393 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7394 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007395
Anders Carlssonacc79812008-11-16 07:17:21 +00007396 QualType LHSTy = E->getLHS()->getType();
7397 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007398
Chandler Carruthb29a7432014-10-11 11:03:30 +00007399 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007400 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007401 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007402 if (E->isAssignmentOp()) {
7403 LValue LV;
7404 EvaluateLValue(E->getLHS(), LV, Info);
7405 LHSOK = false;
7406 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007407 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7408 if (LHSOK) {
7409 LHS.makeComplexFloat();
7410 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7411 }
7412 } else {
7413 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7414 }
Richard Smith253c2a32012-01-27 01:14:48 +00007415 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007416 return false;
7417
Chandler Carruthb29a7432014-10-11 11:03:30 +00007418 if (E->getRHS()->getType()->isRealFloatingType()) {
7419 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7420 return false;
7421 RHS.makeComplexFloat();
7422 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7423 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007424 return false;
7425
7426 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007427 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007428 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007429 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007430 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7431
John McCalle3027922010-08-25 11:45:40 +00007432 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007433 return Success((CR_r == APFloat::cmpEqual &&
7434 CR_i == APFloat::cmpEqual), E);
7435 else {
John McCalle3027922010-08-25 11:45:40 +00007436 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007437 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007438 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007439 CR_r == APFloat::cmpLessThan ||
7440 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007441 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007442 CR_i == APFloat::cmpLessThan ||
7443 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007444 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007445 } else {
John McCalle3027922010-08-25 11:45:40 +00007446 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007447 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7448 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7449 else {
John McCalle3027922010-08-25 11:45:40 +00007450 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007451 "Invalid compex comparison.");
7452 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7453 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7454 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007455 }
7456 }
Mike Stump11289f42009-09-09 15:08:12 +00007457
Anders Carlssonacc79812008-11-16 07:17:21 +00007458 if (LHSTy->isRealFloatingType() &&
7459 RHSTy->isRealFloatingType()) {
7460 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007461
Richard Smith253c2a32012-01-27 01:14:48 +00007462 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7463 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007464 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007465
Richard Smith253c2a32012-01-27 01:14:48 +00007466 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007467 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007468
Anders Carlssonacc79812008-11-16 07:17:21 +00007469 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007470
Anders Carlssonacc79812008-11-16 07:17:21 +00007471 switch (E->getOpcode()) {
7472 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007473 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007474 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007475 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007476 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007477 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007478 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007479 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007480 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007481 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007482 E);
John McCalle3027922010-08-25 11:45:40 +00007483 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007484 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007485 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007486 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007487 || CR == APFloat::cmpLessThan
7488 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007489 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007490 }
Mike Stump11289f42009-09-09 15:08:12 +00007491
Eli Friedmana38da572009-04-28 19:17:36 +00007492 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007493 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007494 LValue LHSValue, RHSValue;
7495
7496 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
Richard Smith0c6124b2015-12-03 01:36:22 +00007497 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007498 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007499
Richard Smith253c2a32012-01-27 01:14:48 +00007500 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007501 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007502
Richard Smith8b3497e2011-10-31 01:37:14 +00007503 // Reject differing bases from the normal codepath; we special-case
7504 // comparisons to null.
7505 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007506 if (E->getOpcode() == BO_Sub) {
7507 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007508 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007509 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007510 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007511 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007512 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007513 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007514 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7515 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7516 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007517 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007518 // Make sure both labels come from the same function.
7519 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7520 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007521 return Error(E);
7522 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007523 }
Richard Smith83c68212011-10-31 05:11:32 +00007524 // Inequalities and subtractions between unrelated pointers have
7525 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007526 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007527 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007528 // A constant address may compare equal to the address of a symbol.
7529 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007530 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007531 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7532 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007533 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007534 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007535 // distinct addresses. In clang, the result of such a comparison is
7536 // unspecified, so it is not a constant expression. However, we do know
7537 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007538 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7539 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007540 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007541 // We can't tell whether weak symbols will end up pointing to the same
7542 // object.
7543 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007544 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007545 // We can't compare the address of the start of one object with the
7546 // past-the-end address of another object, per C++ DR1652.
7547 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7548 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7549 (RHSValue.Base && RHSValue.Offset.isZero() &&
7550 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7551 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007552 // We can't tell whether an object is at the same address as another
7553 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007554 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7555 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007556 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007557 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007558 // (Note that clang defaults to -fmerge-all-constants, which can
7559 // lead to inconsistent results for comparisons involving the address
7560 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007561 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007562 }
Eli Friedman64004332009-03-23 04:38:34 +00007563
Richard Smith1b470412012-02-01 08:10:20 +00007564 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7565 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7566
Richard Smith84f6dcf2012-02-02 01:16:57 +00007567 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7568 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7569
John McCalle3027922010-08-25 11:45:40 +00007570 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007571 // C++11 [expr.add]p6:
7572 // Unless both pointers point to elements of the same array object, or
7573 // one past the last element of the array object, the behavior is
7574 // undefined.
7575 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7576 !AreElementsOfSameArray(getType(LHSValue.Base),
7577 LHSDesignator, RHSDesignator))
7578 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7579
Chris Lattner882bdf22010-04-20 17:13:14 +00007580 QualType Type = E->getLHS()->getType();
7581 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007582
Richard Smithd62306a2011-11-10 06:34:14 +00007583 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007584 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007585 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007586
Richard Smith84c6b3d2013-09-10 21:34:14 +00007587 // As an extension, a type may have zero size (empty struct or union in
7588 // C, array of zero length). Pointer subtraction in such cases has
7589 // undefined behavior, so is not constant.
7590 if (ElementSize.isZero()) {
7591 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7592 << ElementType;
7593 return false;
7594 }
7595
Richard Smith1b470412012-02-01 08:10:20 +00007596 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7597 // and produce incorrect results when it overflows. Such behavior
7598 // appears to be non-conforming, but is common, so perhaps we should
7599 // assume the standard intended for such cases to be undefined behavior
7600 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007601
Richard Smith1b470412012-02-01 08:10:20 +00007602 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7603 // overflow in the final conversion to ptrdiff_t.
7604 APSInt LHS(
7605 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7606 APSInt RHS(
7607 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7608 APSInt ElemSize(
7609 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7610 APSInt TrueResult = (LHS - RHS) / ElemSize;
7611 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7612
Richard Smith0c6124b2015-12-03 01:36:22 +00007613 if (Result.extend(65) != TrueResult &&
7614 !HandleOverflow(Info, E, TrueResult, E->getType()))
7615 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007616 return Success(Result, E);
7617 }
Richard Smithde21b242012-01-31 06:41:30 +00007618
7619 // C++11 [expr.rel]p3:
7620 // Pointers to void (after pointer conversions) can be compared, with a
7621 // result defined as follows: If both pointers represent the same
7622 // address or are both the null pointer value, the result is true if the
7623 // operator is <= or >= and false otherwise; otherwise the result is
7624 // unspecified.
7625 // We interpret this as applying to pointers to *cv* void.
7626 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007627 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007628 CCEDiag(E, diag::note_constexpr_void_comparison);
7629
Richard Smith84f6dcf2012-02-02 01:16:57 +00007630 // C++11 [expr.rel]p2:
7631 // - If two pointers point to non-static data members of the same object,
7632 // or to subobjects or array elements fo such members, recursively, the
7633 // pointer to the later declared member compares greater provided the
7634 // two members have the same access control and provided their class is
7635 // not a union.
7636 // [...]
7637 // - Otherwise pointer comparisons are unspecified.
7638 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7639 E->isRelationalOp()) {
7640 bool WasArrayIndex;
7641 unsigned Mismatch =
7642 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7643 RHSDesignator, WasArrayIndex);
7644 // At the point where the designators diverge, the comparison has a
7645 // specified value if:
7646 // - we are comparing array indices
7647 // - we are comparing fields of a union, or fields with the same access
7648 // Otherwise, the result is unspecified and thus the comparison is not a
7649 // constant expression.
7650 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7651 Mismatch < RHSDesignator.Entries.size()) {
7652 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7653 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7654 if (!LF && !RF)
7655 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7656 else if (!LF)
7657 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7658 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7659 << RF->getParent() << RF;
7660 else if (!RF)
7661 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7662 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7663 << LF->getParent() << LF;
7664 else if (!LF->getParent()->isUnion() &&
7665 LF->getAccess() != RF->getAccess())
7666 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7667 << LF << LF->getAccess() << RF << RF->getAccess()
7668 << LF->getParent();
7669 }
7670 }
7671
Eli Friedman6c31cb42012-04-16 04:30:08 +00007672 // The comparison here must be unsigned, and performed with the same
7673 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007674 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7675 uint64_t CompareLHS = LHSOffset.getQuantity();
7676 uint64_t CompareRHS = RHSOffset.getQuantity();
7677 assert(PtrSize <= 64 && "Unexpected pointer width");
7678 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7679 CompareLHS &= Mask;
7680 CompareRHS &= Mask;
7681
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007682 // If there is a base and this is a relational operator, we can only
7683 // compare pointers within the object in question; otherwise, the result
7684 // depends on where the object is located in memory.
7685 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7686 QualType BaseTy = getType(LHSValue.Base);
7687 if (BaseTy->isIncompleteType())
7688 return Error(E);
7689 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7690 uint64_t OffsetLimit = Size.getQuantity();
7691 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7692 return Error(E);
7693 }
7694
Richard Smith8b3497e2011-10-31 01:37:14 +00007695 switch (E->getOpcode()) {
7696 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007697 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7698 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7699 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7700 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7701 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7702 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007703 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007704 }
7705 }
Richard Smith7bb00672012-02-01 01:42:44 +00007706
7707 if (LHSTy->isMemberPointerType()) {
7708 assert(E->isEqualityOp() && "unexpected member pointer operation");
7709 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7710
7711 MemberPtr LHSValue, RHSValue;
7712
7713 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IV8c892b52016-05-25 22:31:54 +00007714 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007715 return false;
7716
7717 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7718 return false;
7719
7720 // C++11 [expr.eq]p2:
7721 // If both operands are null, they compare equal. Otherwise if only one is
7722 // null, they compare unequal.
7723 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7724 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7725 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7726 }
7727
7728 // Otherwise if either is a pointer to a virtual member function, the
7729 // result is unspecified.
7730 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7731 if (MD->isVirtual())
7732 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7733 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7734 if (MD->isVirtual())
7735 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7736
7737 // Otherwise they compare equal if and only if they would refer to the
7738 // same member of the same most derived object or the same subobject if
7739 // they were dereferenced with a hypothetical object of the associated
7740 // class type.
7741 bool Equal = LHSValue == RHSValue;
7742 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7743 }
7744
Richard Smithab44d9b2012-02-14 22:35:28 +00007745 if (LHSTy->isNullPtrType()) {
7746 assert(E->isComparisonOp() && "unexpected nullptr operation");
7747 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7748 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7749 // are compared, the result is true of the operator is <=, >= or ==, and
7750 // false otherwise.
7751 BinaryOperator::Opcode Opcode = E->getOpcode();
7752 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7753 }
7754
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007755 assert((!LHSTy->isIntegralOrEnumerationType() ||
7756 !RHSTy->isIntegralOrEnumerationType()) &&
7757 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7758 // We can't continue from here for non-integral types.
7759 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007760}
7761
Peter Collingbournee190dee2011-03-11 19:24:49 +00007762/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7763/// a result as the expression's type.
7764bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7765 const UnaryExprOrTypeTraitExpr *E) {
7766 switch(E->getKind()) {
7767 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007768 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007769 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007770 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007771 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007772 }
Eli Friedman64004332009-03-23 04:38:34 +00007773
Peter Collingbournee190dee2011-03-11 19:24:49 +00007774 case UETT_VecStep: {
7775 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007776
Peter Collingbournee190dee2011-03-11 19:24:49 +00007777 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007778 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007779
Peter Collingbournee190dee2011-03-11 19:24:49 +00007780 // The vec_step built-in functions that take a 3-component
7781 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7782 if (n == 3)
7783 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007784
Peter Collingbournee190dee2011-03-11 19:24:49 +00007785 return Success(n, E);
7786 } else
7787 return Success(1, E);
7788 }
7789
7790 case UETT_SizeOf: {
7791 QualType SrcTy = E->getTypeOfArgument();
7792 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7793 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007794 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7795 SrcTy = Ref->getPointeeType();
7796
Richard Smithd62306a2011-11-10 06:34:14 +00007797 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007798 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007799 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007800 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007801 }
Alexey Bataev00396512015-07-02 03:40:19 +00007802 case UETT_OpenMPRequiredSimdAlign:
7803 assert(E->isArgumentType());
7804 return Success(
7805 Info.Ctx.toCharUnitsFromBits(
7806 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7807 .getQuantity(),
7808 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007809 }
7810
7811 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007812}
7813
Peter Collingbournee9200682011-05-13 03:29:01 +00007814bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007815 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007816 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007817 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007818 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007819 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007820 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007821 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007822 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007823 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007824 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007825 APSInt IdxResult;
7826 if (!EvaluateInteger(Idx, IdxResult, Info))
7827 return false;
7828 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7829 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007830 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007831 CurrentType = AT->getElementType();
7832 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7833 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007834 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007835 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007836
James Y Knight7281c352015-12-29 22:31:18 +00007837 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007838 FieldDecl *MemberDecl = ON.getField();
7839 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007840 if (!RT)
7841 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007842 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007843 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007844 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007845 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007846 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007847 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007848 CurrentType = MemberDecl->getType().getNonReferenceType();
7849 break;
7850 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007851
James Y Knight7281c352015-12-29 22:31:18 +00007852 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007853 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007854
James Y Knight7281c352015-12-29 22:31:18 +00007855 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007856 CXXBaseSpecifier *BaseSpec = ON.getBase();
7857 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007858 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007859
7860 // Find the layout of the class whose base we are looking into.
7861 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007862 if (!RT)
7863 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007864 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007865 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007866 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7867
7868 // Find the base class itself.
7869 CurrentType = BaseSpec->getType();
7870 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7871 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007872 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007873
7874 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007875 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007876 break;
7877 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007878 }
7879 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007880 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007881}
7882
Chris Lattnere13042c2008-07-11 19:10:17 +00007883bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007884 switch (E->getOpcode()) {
7885 default:
7886 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7887 // See C99 6.6p3.
7888 return Error(E);
7889 case UO_Extension:
7890 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7891 // If so, we could clear the diagnostic ID.
7892 return Visit(E->getSubExpr());
7893 case UO_Plus:
7894 // The result is just the value.
7895 return Visit(E->getSubExpr());
7896 case UO_Minus: {
7897 if (!Visit(E->getSubExpr()))
7898 return false;
7899 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007900 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007901 if (Value.isSigned() && Value.isMinSignedValue() &&
7902 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7903 E->getType()))
7904 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007905 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007906 }
7907 case UO_Not: {
7908 if (!Visit(E->getSubExpr()))
7909 return false;
7910 if (!Result.isInt()) return Error(E);
7911 return Success(~Result.getInt(), E);
7912 }
7913 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007914 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007915 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007916 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007917 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007918 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007919 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007920}
Mike Stump11289f42009-09-09 15:08:12 +00007921
Chris Lattner477c4be2008-07-12 01:15:53 +00007922/// HandleCast - This is used to evaluate implicit or explicit casts where the
7923/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007924bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7925 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007926 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007927 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007928
Eli Friedmanc757de22011-03-25 00:43:55 +00007929 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007930 case CK_BaseToDerived:
7931 case CK_DerivedToBase:
7932 case CK_UncheckedDerivedToBase:
7933 case CK_Dynamic:
7934 case CK_ToUnion:
7935 case CK_ArrayToPointerDecay:
7936 case CK_FunctionToPointerDecay:
7937 case CK_NullToPointer:
7938 case CK_NullToMemberPointer:
7939 case CK_BaseToDerivedMemberPointer:
7940 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007941 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007942 case CK_ConstructorConversion:
7943 case CK_IntegralToPointer:
7944 case CK_ToVoid:
7945 case CK_VectorSplat:
7946 case CK_IntegralToFloating:
7947 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007948 case CK_CPointerToObjCPointerCast:
7949 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007950 case CK_AnyPointerToBlockPointerCast:
7951 case CK_ObjCObjectLValueCast:
7952 case CK_FloatingRealToComplex:
7953 case CK_FloatingComplexToReal:
7954 case CK_FloatingComplexCast:
7955 case CK_FloatingComplexToIntegralComplex:
7956 case CK_IntegralRealToComplex:
7957 case CK_IntegralComplexCast:
7958 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007959 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007960 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007961 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007962 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007963 llvm_unreachable("invalid cast kind for integral value");
7964
Eli Friedman9faf2f92011-03-25 19:07:11 +00007965 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007966 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007967 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007968 case CK_ARCProduceObject:
7969 case CK_ARCConsumeObject:
7970 case CK_ARCReclaimReturnedObject:
7971 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007972 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007973 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007974
Richard Smith4ef685b2012-01-17 21:17:26 +00007975 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007976 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007977 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007978 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007979 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007980
7981 case CK_MemberPointerToBoolean:
7982 case CK_PointerToBoolean:
7983 case CK_IntegralToBoolean:
7984 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00007985 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00007986 case CK_FloatingComplexToBoolean:
7987 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007988 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007989 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007990 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00007991 uint64_t IntResult = BoolResult;
7992 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
7993 IntResult = (uint64_t)-1;
7994 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007995 }
7996
Eli Friedmanc757de22011-03-25 00:43:55 +00007997 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007998 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007999 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008000
Eli Friedman742421e2009-02-20 01:15:07 +00008001 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008002 // Allow casts of address-of-label differences if they are no-ops
8003 // or narrowing. (The narrowing case isn't actually guaranteed to
8004 // be constant-evaluatable except in some narrow cases which are hard
8005 // to detect here. We let it through on the assumption the user knows
8006 // what they are doing.)
8007 if (Result.isAddrLabelDiff())
8008 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008009 // Only allow casts of lvalues if they are lossless.
8010 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8011 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008012
Richard Smith911e1422012-01-30 22:27:01 +00008013 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8014 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008015 }
Mike Stump11289f42009-09-09 15:08:12 +00008016
Eli Friedmanc757de22011-03-25 00:43:55 +00008017 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008018 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8019
John McCall45d55e42010-05-07 21:00:08 +00008020 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008021 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008022 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008023
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008024 if (LV.getLValueBase()) {
8025 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008026 // FIXME: Allow a larger integer size than the pointer size, and allow
8027 // narrowing back down to pointer width in subsequent integral casts.
8028 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008029 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008030 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008031
Richard Smithcf74da72011-11-16 07:18:12 +00008032 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008033 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008034 return true;
8035 }
8036
Ken Dyck02990832010-01-15 12:37:54 +00008037 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8038 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008039 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008040 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008041
Eli Friedmanc757de22011-03-25 00:43:55 +00008042 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008043 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008044 if (!EvaluateComplex(SubExpr, C, Info))
8045 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008046 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008047 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008048
Eli Friedmanc757de22011-03-25 00:43:55 +00008049 case CK_FloatingToIntegral: {
8050 APFloat F(0.0);
8051 if (!EvaluateFloat(SubExpr, F, Info))
8052 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008053
Richard Smith357362d2011-12-13 06:39:58 +00008054 APSInt Value;
8055 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8056 return false;
8057 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008058 }
8059 }
Mike Stump11289f42009-09-09 15:08:12 +00008060
Eli Friedmanc757de22011-03-25 00:43:55 +00008061 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008062}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008063
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008064bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8065 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008066 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008067 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8068 return false;
8069 if (!LV.isComplexInt())
8070 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008071 return Success(LV.getComplexIntReal(), E);
8072 }
8073
8074 return Visit(E->getSubExpr());
8075}
8076
Eli Friedman4e7a2412009-02-27 04:45:43 +00008077bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008078 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008079 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008080 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8081 return false;
8082 if (!LV.isComplexInt())
8083 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008084 return Success(LV.getComplexIntImag(), E);
8085 }
8086
Richard Smith4a678122011-10-24 18:44:57 +00008087 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008088 return Success(0, E);
8089}
8090
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008091bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8092 return Success(E->getPackLength(), E);
8093}
8094
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008095bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8096 return Success(E->getValue(), E);
8097}
8098
Chris Lattner05706e882008-07-11 18:11:29 +00008099//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008100// Float Evaluation
8101//===----------------------------------------------------------------------===//
8102
8103namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008104class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008105 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008106 APFloat &Result;
8107public:
8108 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008109 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008110
Richard Smith2e312c82012-03-03 22:46:17 +00008111 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008112 Result = V.getFloat();
8113 return true;
8114 }
Eli Friedman24c01542008-08-22 00:06:13 +00008115
Richard Smithfddd3842011-12-30 21:15:51 +00008116 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008117 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8118 return true;
8119 }
8120
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008121 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008122
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008123 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008124 bool VisitBinaryOperator(const BinaryOperator *E);
8125 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008126 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008127
John McCallb1fb0d32010-05-07 22:08:54 +00008128 bool VisitUnaryReal(const UnaryOperator *E);
8129 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008130
Richard Smithfddd3842011-12-30 21:15:51 +00008131 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008132};
8133} // end anonymous namespace
8134
8135static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008136 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008137 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008138}
8139
Jay Foad39c79802011-01-12 09:06:06 +00008140static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008141 QualType ResultTy,
8142 const Expr *Arg,
8143 bool SNaN,
8144 llvm::APFloat &Result) {
8145 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8146 if (!S) return false;
8147
8148 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8149
8150 llvm::APInt fill;
8151
8152 // Treat empty strings as if they were zero.
8153 if (S->getString().empty())
8154 fill = llvm::APInt(32, 0);
8155 else if (S->getString().getAsInteger(0, fill))
8156 return false;
8157
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008158 if (Context.getTargetInfo().isNan2008()) {
8159 if (SNaN)
8160 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8161 else
8162 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8163 } else {
8164 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8165 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8166 // a different encoding to what became a standard in 2008, and for pre-
8167 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8168 // sNaN. This is now known as "legacy NaN" encoding.
8169 if (SNaN)
8170 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8171 else
8172 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8173 }
8174
John McCall16291492010-02-28 13:00:19 +00008175 return true;
8176}
8177
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008178bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008179 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008180 default:
8181 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8182
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008183 case Builtin::BI__builtin_huge_val:
8184 case Builtin::BI__builtin_huge_valf:
8185 case Builtin::BI__builtin_huge_vall:
8186 case Builtin::BI__builtin_inf:
8187 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008188 case Builtin::BI__builtin_infl: {
8189 const llvm::fltSemantics &Sem =
8190 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008191 Result = llvm::APFloat::getInf(Sem);
8192 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008193 }
Mike Stump11289f42009-09-09 15:08:12 +00008194
John McCall16291492010-02-28 13:00:19 +00008195 case Builtin::BI__builtin_nans:
8196 case Builtin::BI__builtin_nansf:
8197 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008198 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8199 true, Result))
8200 return Error(E);
8201 return true;
John McCall16291492010-02-28 13:00:19 +00008202
Chris Lattner0b7282e2008-10-06 06:31:58 +00008203 case Builtin::BI__builtin_nan:
8204 case Builtin::BI__builtin_nanf:
8205 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008206 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008207 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008208 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8209 false, Result))
8210 return Error(E);
8211 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008212
8213 case Builtin::BI__builtin_fabs:
8214 case Builtin::BI__builtin_fabsf:
8215 case Builtin::BI__builtin_fabsl:
8216 if (!EvaluateFloat(E->getArg(0), Result, Info))
8217 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008218
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008219 if (Result.isNegative())
8220 Result.changeSign();
8221 return true;
8222
Richard Smith8889a3d2013-06-13 06:26:32 +00008223 // FIXME: Builtin::BI__builtin_powi
8224 // FIXME: Builtin::BI__builtin_powif
8225 // FIXME: Builtin::BI__builtin_powil
8226
Mike Stump11289f42009-09-09 15:08:12 +00008227 case Builtin::BI__builtin_copysign:
8228 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008229 case Builtin::BI__builtin_copysignl: {
8230 APFloat RHS(0.);
8231 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8232 !EvaluateFloat(E->getArg(1), RHS, Info))
8233 return false;
8234 Result.copySign(RHS);
8235 return true;
8236 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008237 }
8238}
8239
John McCallb1fb0d32010-05-07 22:08:54 +00008240bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008241 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8242 ComplexValue CV;
8243 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8244 return false;
8245 Result = CV.FloatReal;
8246 return true;
8247 }
8248
8249 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008250}
8251
8252bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008253 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8254 ComplexValue CV;
8255 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8256 return false;
8257 Result = CV.FloatImag;
8258 return true;
8259 }
8260
Richard Smith4a678122011-10-24 18:44:57 +00008261 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008262 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8263 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008264 return true;
8265}
8266
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008267bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008268 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008269 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008270 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008271 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008272 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008273 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8274 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008275 Result.changeSign();
8276 return true;
8277 }
8278}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008279
Eli Friedman24c01542008-08-22 00:06:13 +00008280bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008281 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8282 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008283
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008284 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008285 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8286 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008287 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008288 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8289 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008290}
8291
8292bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8293 Result = E->getValue();
8294 return true;
8295}
8296
Peter Collingbournee9200682011-05-13 03:29:01 +00008297bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8298 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008299
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008300 switch (E->getCastKind()) {
8301 default:
Richard Smith11562c52011-10-28 17:51:58 +00008302 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008303
8304 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008305 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008306 return EvaluateInteger(SubExpr, IntResult, Info) &&
8307 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8308 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008309 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008310
8311 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008312 if (!Visit(SubExpr))
8313 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008314 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8315 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008316 }
John McCalld7646252010-11-14 08:17:51 +00008317
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008318 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008319 ComplexValue V;
8320 if (!EvaluateComplex(SubExpr, V, Info))
8321 return false;
8322 Result = V.getComplexFloatReal();
8323 return true;
8324 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008325 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008326}
8327
Eli Friedman24c01542008-08-22 00:06:13 +00008328//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008329// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008330//===----------------------------------------------------------------------===//
8331
8332namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008333class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008334 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008335 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008336
Anders Carlsson537969c2008-11-16 20:27:53 +00008337public:
John McCall93d91dc2010-05-07 17:22:02 +00008338 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008339 : ExprEvaluatorBaseTy(info), Result(Result) {}
8340
Richard Smith2e312c82012-03-03 22:46:17 +00008341 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008342 Result.setFrom(V);
8343 return true;
8344 }
Mike Stump11289f42009-09-09 15:08:12 +00008345
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008346 bool ZeroInitialization(const Expr *E);
8347
Anders Carlsson537969c2008-11-16 20:27:53 +00008348 //===--------------------------------------------------------------------===//
8349 // Visitor Methods
8350 //===--------------------------------------------------------------------===//
8351
Peter Collingbournee9200682011-05-13 03:29:01 +00008352 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008353 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008354 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008355 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008356 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008357};
8358} // end anonymous namespace
8359
John McCall93d91dc2010-05-07 17:22:02 +00008360static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8361 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008362 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008363 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008364}
8365
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008366bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008367 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008368 if (ElemTy->isRealFloatingType()) {
8369 Result.makeComplexFloat();
8370 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8371 Result.FloatReal = Zero;
8372 Result.FloatImag = Zero;
8373 } else {
8374 Result.makeComplexInt();
8375 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8376 Result.IntReal = Zero;
8377 Result.IntImag = Zero;
8378 }
8379 return true;
8380}
8381
Peter Collingbournee9200682011-05-13 03:29:01 +00008382bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8383 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008384
8385 if (SubExpr->getType()->isRealFloatingType()) {
8386 Result.makeComplexFloat();
8387 APFloat &Imag = Result.FloatImag;
8388 if (!EvaluateFloat(SubExpr, Imag, Info))
8389 return false;
8390
8391 Result.FloatReal = APFloat(Imag.getSemantics());
8392 return true;
8393 } else {
8394 assert(SubExpr->getType()->isIntegerType() &&
8395 "Unexpected imaginary literal.");
8396
8397 Result.makeComplexInt();
8398 APSInt &Imag = Result.IntImag;
8399 if (!EvaluateInteger(SubExpr, Imag, Info))
8400 return false;
8401
8402 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8403 return true;
8404 }
8405}
8406
Peter Collingbournee9200682011-05-13 03:29:01 +00008407bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008408
John McCallfcef3cf2010-12-14 17:51:41 +00008409 switch (E->getCastKind()) {
8410 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008411 case CK_BaseToDerived:
8412 case CK_DerivedToBase:
8413 case CK_UncheckedDerivedToBase:
8414 case CK_Dynamic:
8415 case CK_ToUnion:
8416 case CK_ArrayToPointerDecay:
8417 case CK_FunctionToPointerDecay:
8418 case CK_NullToPointer:
8419 case CK_NullToMemberPointer:
8420 case CK_BaseToDerivedMemberPointer:
8421 case CK_DerivedToBaseMemberPointer:
8422 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008423 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008424 case CK_ConstructorConversion:
8425 case CK_IntegralToPointer:
8426 case CK_PointerToIntegral:
8427 case CK_PointerToBoolean:
8428 case CK_ToVoid:
8429 case CK_VectorSplat:
8430 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008431 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008432 case CK_IntegralToBoolean:
8433 case CK_IntegralToFloating:
8434 case CK_FloatingToIntegral:
8435 case CK_FloatingToBoolean:
8436 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008437 case CK_CPointerToObjCPointerCast:
8438 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008439 case CK_AnyPointerToBlockPointerCast:
8440 case CK_ObjCObjectLValueCast:
8441 case CK_FloatingComplexToReal:
8442 case CK_FloatingComplexToBoolean:
8443 case CK_IntegralComplexToReal:
8444 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008445 case CK_ARCProduceObject:
8446 case CK_ARCConsumeObject:
8447 case CK_ARCReclaimReturnedObject:
8448 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008449 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008450 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008451 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008452 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008453 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008454 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008455
John McCallfcef3cf2010-12-14 17:51:41 +00008456 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008457 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008458 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008460
8461 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008462 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008463 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008464 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008465
8466 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008467 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008468 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008469 return false;
8470
John McCallfcef3cf2010-12-14 17:51:41 +00008471 Result.makeComplexFloat();
8472 Result.FloatImag = APFloat(Real.getSemantics());
8473 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008474 }
8475
John McCallfcef3cf2010-12-14 17:51:41 +00008476 case CK_FloatingComplexCast: {
8477 if (!Visit(E->getSubExpr()))
8478 return false;
8479
8480 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8481 QualType From
8482 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8483
Richard Smith357362d2011-12-13 06:39:58 +00008484 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8485 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008486 }
8487
8488 case CK_FloatingComplexToIntegralComplex: {
8489 if (!Visit(E->getSubExpr()))
8490 return false;
8491
8492 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8493 QualType From
8494 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8495 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008496 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8497 To, Result.IntReal) &&
8498 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8499 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008500 }
8501
8502 case CK_IntegralRealToComplex: {
8503 APSInt &Real = Result.IntReal;
8504 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8505 return false;
8506
8507 Result.makeComplexInt();
8508 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8509 return true;
8510 }
8511
8512 case CK_IntegralComplexCast: {
8513 if (!Visit(E->getSubExpr()))
8514 return false;
8515
8516 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8517 QualType From
8518 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8519
Richard Smith911e1422012-01-30 22:27:01 +00008520 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8521 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008522 return true;
8523 }
8524
8525 case CK_IntegralComplexToFloatingComplex: {
8526 if (!Visit(E->getSubExpr()))
8527 return false;
8528
Ted Kremenek28831752012-08-23 20:46:57 +00008529 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008530 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008531 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008532 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008533 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8534 To, Result.FloatReal) &&
8535 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8536 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008537 }
8538 }
8539
8540 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008541}
8542
John McCall93d91dc2010-05-07 17:22:02 +00008543bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008544 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008545 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8546
Chandler Carrutha216cad2014-10-11 00:57:18 +00008547 // Track whether the LHS or RHS is real at the type system level. When this is
8548 // the case we can simplify our evaluation strategy.
8549 bool LHSReal = false, RHSReal = false;
8550
8551 bool LHSOK;
8552 if (E->getLHS()->getType()->isRealFloatingType()) {
8553 LHSReal = true;
8554 APFloat &Real = Result.FloatReal;
8555 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8556 if (LHSOK) {
8557 Result.makeComplexFloat();
8558 Result.FloatImag = APFloat(Real.getSemantics());
8559 }
8560 } else {
8561 LHSOK = Visit(E->getLHS());
8562 }
Richard Smith253c2a32012-01-27 01:14:48 +00008563 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008564 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008565
John McCall93d91dc2010-05-07 17:22:02 +00008566 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008567 if (E->getRHS()->getType()->isRealFloatingType()) {
8568 RHSReal = true;
8569 APFloat &Real = RHS.FloatReal;
8570 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8571 return false;
8572 RHS.makeComplexFloat();
8573 RHS.FloatImag = APFloat(Real.getSemantics());
8574 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008575 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008576
Chandler Carrutha216cad2014-10-11 00:57:18 +00008577 assert(!(LHSReal && RHSReal) &&
8578 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008579 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008580 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008581 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008582 if (Result.isComplexFloat()) {
8583 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8584 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008585 if (LHSReal)
8586 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8587 else if (!RHSReal)
8588 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8589 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008590 } else {
8591 Result.getComplexIntReal() += RHS.getComplexIntReal();
8592 Result.getComplexIntImag() += RHS.getComplexIntImag();
8593 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008594 break;
John McCalle3027922010-08-25 11:45:40 +00008595 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008596 if (Result.isComplexFloat()) {
8597 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8598 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008599 if (LHSReal) {
8600 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8601 Result.getComplexFloatImag().changeSign();
8602 } else if (!RHSReal) {
8603 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8604 APFloat::rmNearestTiesToEven);
8605 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008606 } else {
8607 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8608 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8609 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008610 break;
John McCalle3027922010-08-25 11:45:40 +00008611 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008612 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008613 // This is an implementation of complex multiplication according to the
8614 // constraints laid out in C11 Annex G. The implemantion uses the
8615 // following naming scheme:
8616 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008617 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008618 APFloat &A = LHS.getComplexFloatReal();
8619 APFloat &B = LHS.getComplexFloatImag();
8620 APFloat &C = RHS.getComplexFloatReal();
8621 APFloat &D = RHS.getComplexFloatImag();
8622 APFloat &ResR = Result.getComplexFloatReal();
8623 APFloat &ResI = Result.getComplexFloatImag();
8624 if (LHSReal) {
8625 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8626 ResR = A * C;
8627 ResI = A * D;
8628 } else if (RHSReal) {
8629 ResR = C * A;
8630 ResI = C * B;
8631 } else {
8632 // In the fully general case, we need to handle NaNs and infinities
8633 // robustly.
8634 APFloat AC = A * C;
8635 APFloat BD = B * D;
8636 APFloat AD = A * D;
8637 APFloat BC = B * C;
8638 ResR = AC - BD;
8639 ResI = AD + BC;
8640 if (ResR.isNaN() && ResI.isNaN()) {
8641 bool Recalc = false;
8642 if (A.isInfinity() || B.isInfinity()) {
8643 A = APFloat::copySign(
8644 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8645 B = APFloat::copySign(
8646 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8647 if (C.isNaN())
8648 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8649 if (D.isNaN())
8650 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8651 Recalc = true;
8652 }
8653 if (C.isInfinity() || D.isInfinity()) {
8654 C = APFloat::copySign(
8655 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8656 D = APFloat::copySign(
8657 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8658 if (A.isNaN())
8659 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8660 if (B.isNaN())
8661 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8662 Recalc = true;
8663 }
8664 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8665 AD.isInfinity() || BC.isInfinity())) {
8666 if (A.isNaN())
8667 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8668 if (B.isNaN())
8669 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8670 if (C.isNaN())
8671 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8672 if (D.isNaN())
8673 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8674 Recalc = true;
8675 }
8676 if (Recalc) {
8677 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8678 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8679 }
8680 }
8681 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008682 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008683 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008684 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008685 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8686 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008687 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008688 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8689 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8690 }
8691 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008692 case BO_Div:
8693 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008694 // This is an implementation of complex division according to the
8695 // constraints laid out in C11 Annex G. The implemantion uses the
8696 // following naming scheme:
8697 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008698 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008699 APFloat &A = LHS.getComplexFloatReal();
8700 APFloat &B = LHS.getComplexFloatImag();
8701 APFloat &C = RHS.getComplexFloatReal();
8702 APFloat &D = RHS.getComplexFloatImag();
8703 APFloat &ResR = Result.getComplexFloatReal();
8704 APFloat &ResI = Result.getComplexFloatImag();
8705 if (RHSReal) {
8706 ResR = A / C;
8707 ResI = B / C;
8708 } else {
8709 if (LHSReal) {
8710 // No real optimizations we can do here, stub out with zero.
8711 B = APFloat::getZero(A.getSemantics());
8712 }
8713 int DenomLogB = 0;
8714 APFloat MaxCD = maxnum(abs(C), abs(D));
8715 if (MaxCD.isFinite()) {
8716 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008717 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8718 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008719 }
8720 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008721 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8722 APFloat::rmNearestTiesToEven);
8723 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8724 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008725 if (ResR.isNaN() && ResI.isNaN()) {
8726 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8727 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8728 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8729 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8730 D.isFinite()) {
8731 A = APFloat::copySign(
8732 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8733 B = APFloat::copySign(
8734 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8735 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8736 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8737 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8738 C = APFloat::copySign(
8739 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8740 D = APFloat::copySign(
8741 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8742 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8743 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8744 }
8745 }
8746 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008747 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008748 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8749 return Error(E, diag::note_expr_divide_by_zero);
8750
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008751 ComplexValue LHS = Result;
8752 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8753 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8754 Result.getComplexIntReal() =
8755 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8756 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8757 Result.getComplexIntImag() =
8758 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8759 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8760 }
8761 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008762 }
8763
John McCall93d91dc2010-05-07 17:22:02 +00008764 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008765}
8766
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008767bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8768 // Get the operand value into 'Result'.
8769 if (!Visit(E->getSubExpr()))
8770 return false;
8771
8772 switch (E->getOpcode()) {
8773 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008774 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008775 case UO_Extension:
8776 return true;
8777 case UO_Plus:
8778 // The result is always just the subexpr.
8779 return true;
8780 case UO_Minus:
8781 if (Result.isComplexFloat()) {
8782 Result.getComplexFloatReal().changeSign();
8783 Result.getComplexFloatImag().changeSign();
8784 }
8785 else {
8786 Result.getComplexIntReal() = -Result.getComplexIntReal();
8787 Result.getComplexIntImag() = -Result.getComplexIntImag();
8788 }
8789 return true;
8790 case UO_Not:
8791 if (Result.isComplexFloat())
8792 Result.getComplexFloatImag().changeSign();
8793 else
8794 Result.getComplexIntImag() = -Result.getComplexIntImag();
8795 return true;
8796 }
8797}
8798
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008799bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8800 if (E->getNumInits() == 2) {
8801 if (E->getType()->isComplexType()) {
8802 Result.makeComplexFloat();
8803 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8804 return false;
8805 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8806 return false;
8807 } else {
8808 Result.makeComplexInt();
8809 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8810 return false;
8811 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8812 return false;
8813 }
8814 return true;
8815 }
8816 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8817}
8818
Anders Carlsson537969c2008-11-16 20:27:53 +00008819//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008820// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8821// implicit conversion.
8822//===----------------------------------------------------------------------===//
8823
8824namespace {
8825class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008826 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008827 APValue &Result;
8828public:
8829 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8830 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8831
8832 bool Success(const APValue &V, const Expr *E) {
8833 Result = V;
8834 return true;
8835 }
8836
8837 bool ZeroInitialization(const Expr *E) {
8838 ImplicitValueInitExpr VIE(
8839 E->getType()->castAs<AtomicType>()->getValueType());
8840 return Evaluate(Result, Info, &VIE);
8841 }
8842
8843 bool VisitCastExpr(const CastExpr *E) {
8844 switch (E->getCastKind()) {
8845 default:
8846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8847 case CK_NonAtomicToAtomic:
8848 return Evaluate(Result, Info, E->getSubExpr());
8849 }
8850 }
8851};
8852} // end anonymous namespace
8853
8854static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8855 assert(E->isRValue() && E->getType()->isAtomicType());
8856 return AtomicExprEvaluator(Info, Result).Visit(E);
8857}
8858
8859//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008860// Void expression evaluation, primarily for a cast to void on the LHS of a
8861// comma operator
8862//===----------------------------------------------------------------------===//
8863
8864namespace {
8865class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008866 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008867public:
8868 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8869
Richard Smith2e312c82012-03-03 22:46:17 +00008870 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008871
8872 bool VisitCastExpr(const CastExpr *E) {
8873 switch (E->getCastKind()) {
8874 default:
8875 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8876 case CK_ToVoid:
8877 VisitIgnoredValue(E->getSubExpr());
8878 return true;
8879 }
8880 }
Hal Finkela8443c32014-07-17 14:49:58 +00008881
8882 bool VisitCallExpr(const CallExpr *E) {
8883 switch (E->getBuiltinCallee()) {
8884 default:
8885 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8886 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008887 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008888 // The argument is not evaluated!
8889 return true;
8890 }
8891 }
Richard Smith42d3af92011-12-07 00:43:50 +00008892};
8893} // end anonymous namespace
8894
8895static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8896 assert(E->isRValue() && E->getType()->isVoidType());
8897 return VoidExprEvaluator(Info).Visit(E);
8898}
8899
8900//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008901// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008902//===----------------------------------------------------------------------===//
8903
Richard Smith2e312c82012-03-03 22:46:17 +00008904static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008905 // In C, function designators are not lvalues, but we evaluate them as if they
8906 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008907 QualType T = E->getType();
8908 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008909 LValue LV;
8910 if (!EvaluateLValue(E, LV, Info))
8911 return false;
8912 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008913 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008914 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008915 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008916 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008917 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008918 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008919 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008920 LValue LV;
8921 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008922 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008923 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008924 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008925 llvm::APFloat F(0.0);
8926 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008927 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008928 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008929 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008930 ComplexValue C;
8931 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008932 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008933 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008934 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008935 MemberPtr P;
8936 if (!EvaluateMemberPointer(E, P, Info))
8937 return false;
8938 P.moveInto(Result);
8939 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008940 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008941 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008942 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008943 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8944 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008945 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008946 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008947 } else if (T->isRecordType()) {
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 (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008952 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008953 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008954 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008955 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008956 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008957 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008958 if (!EvaluateVoid(E, Info))
8959 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008960 } else if (T->isAtomicType()) {
8961 if (!EvaluateAtomic(E, Result, Info))
8962 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008963 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008964 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008965 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008966 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008967 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008968 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008969 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008970
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008971 return true;
8972}
8973
Richard Smithb228a862012-02-15 02:18:13 +00008974/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8975/// cases, the in-place evaluation is essential, since later initializers for
8976/// an object can indirectly refer to subobjects which were initialized earlier.
8977static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008978 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008979 assert(!E->isValueDependent());
8980
Richard Smith7525ff62013-05-09 07:14:00 +00008981 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008982 return false;
8983
8984 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008985 // Evaluate arrays and record types in-place, so that later initializers can
8986 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008987 if (E->getType()->isArrayType())
8988 return EvaluateArray(E, This, Result, Info);
8989 else if (E->getType()->isRecordType())
8990 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008991 }
8992
8993 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008994 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008995}
8996
Richard Smithf57d8cb2011-12-09 22:58:01 +00008997/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8998/// lvalue-to-rvalue cast if it is an lvalue.
8999static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009000 if (E->getType().isNull())
9001 return false;
9002
Richard Smithfddd3842011-12-30 21:15:51 +00009003 if (!CheckLiteralType(Info, E))
9004 return false;
9005
Richard Smith2e312c82012-03-03 22:46:17 +00009006 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009007 return false;
9008
9009 if (E->isGLValue()) {
9010 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009011 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009012 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009013 return false;
9014 }
9015
Richard Smith2e312c82012-03-03 22:46:17 +00009016 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009017 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009018}
Richard Smith11562c52011-10-28 17:51:58 +00009019
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009020static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9021 const ASTContext &Ctx, bool &IsConst) {
9022 // Fast-path evaluations of integer literals, since we sometimes see files
9023 // containing vast quantities of these.
9024 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9025 Result.Val = APValue(APSInt(L->getValue(),
9026 L->getType()->isUnsignedIntegerType()));
9027 IsConst = true;
9028 return true;
9029 }
James Dennett0492ef02014-03-14 17:44:10 +00009030
9031 // This case should be rare, but we need to check it before we check on
9032 // the type below.
9033 if (Exp->getType().isNull()) {
9034 IsConst = false;
9035 return true;
9036 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009037
9038 // FIXME: Evaluating values of large array and record types can cause
9039 // performance problems. Only do so in C++11 for now.
9040 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9041 Exp->getType()->isRecordType()) &&
9042 !Ctx.getLangOpts().CPlusPlus11) {
9043 IsConst = false;
9044 return true;
9045 }
9046 return false;
9047}
9048
9049
Richard Smith7b553f12011-10-29 00:50:52 +00009050/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009051/// any crazy technique (that has nothing to do with language standards) that
9052/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009053/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9054/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009055bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009056 bool IsConst;
9057 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9058 return IsConst;
9059
Richard Smith6d4c6582013-11-05 22:18:15 +00009060 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009061 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009062}
9063
Jay Foad39c79802011-01-12 09:06:06 +00009064bool Expr::EvaluateAsBooleanCondition(bool &Result,
9065 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009066 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009067 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009068 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009069}
9070
Richard Smithce8eca52015-12-08 03:21:47 +00009071static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9072 Expr::SideEffectsKind SEK) {
9073 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9074 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9075}
9076
Richard Smith5fab0c92011-12-28 19:48:30 +00009077bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9078 SideEffectsKind AllowSideEffects) const {
9079 if (!getType()->isIntegralOrEnumerationType())
9080 return false;
9081
Richard Smith11562c52011-10-28 17:51:58 +00009082 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009083 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009084 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009085 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009086
Richard Smith11562c52011-10-28 17:51:58 +00009087 Result = ExprResult.Val.getInt();
9088 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009089}
9090
Richard Trieube234c32016-04-21 21:04:55 +00009091bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9092 SideEffectsKind AllowSideEffects) const {
9093 if (!getType()->isRealFloatingType())
9094 return false;
9095
9096 EvalResult ExprResult;
9097 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9098 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9099 return false;
9100
9101 Result = ExprResult.Val.getFloat();
9102 return true;
9103}
9104
Jay Foad39c79802011-01-12 09:06:06 +00009105bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009106 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009107
John McCall45d55e42010-05-07 21:00:08 +00009108 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009109 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9110 !CheckLValueConstantExpression(Info, getExprLoc(),
9111 Ctx.getLValueReferenceType(getType()), LV))
9112 return false;
9113
Richard Smith2e312c82012-03-03 22:46:17 +00009114 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009115 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009116}
9117
Richard Smithd0b4dd62011-12-19 06:19:21 +00009118bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9119 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009120 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009121 // FIXME: Evaluating initializers for large array and record types can cause
9122 // performance problems. Only do so in C++11 for now.
9123 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009124 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009125 return false;
9126
Richard Smithd0b4dd62011-12-19 06:19:21 +00009127 Expr::EvalStatus EStatus;
9128 EStatus.Diag = &Notes;
9129
Richard Smith0c6124b2015-12-03 01:36:22 +00009130 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9131 ? EvalInfo::EM_ConstantExpression
9132 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009133 InitInfo.setEvaluatingDecl(VD, Value);
9134
9135 LValue LVal;
9136 LVal.set(VD);
9137
Richard Smithfddd3842011-12-30 21:15:51 +00009138 // C++11 [basic.start.init]p2:
9139 // Variables with static storage duration or thread storage duration shall be
9140 // zero-initialized before any other initialization takes place.
9141 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009142 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009143 !VD->getType()->isReferenceType()) {
9144 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009145 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009146 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009147 return false;
9148 }
9149
Richard Smith7525ff62013-05-09 07:14:00 +00009150 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9151 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009152 EStatus.HasSideEffects)
9153 return false;
9154
9155 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9156 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009157}
9158
Richard Smith7b553f12011-10-29 00:50:52 +00009159/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9160/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009161bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009162 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009163 return EvaluateAsRValue(Result, Ctx) &&
9164 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009165}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009166
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009167APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009168 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009169 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009170 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009171 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009172 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009173 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009174 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009175
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009176 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009177}
John McCall864e3962010-05-07 05:32:02 +00009178
Richard Smithe9ff7702013-11-05 22:23:30 +00009179void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009180 bool IsConst;
9181 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009182 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009183 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009184 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9185 }
9186}
9187
Richard Smithe6c01442013-06-05 00:46:14 +00009188bool Expr::EvalResult::isGlobalLValue() const {
9189 assert(Val.isLValue());
9190 return IsGlobalLValue(Val.getLValueBase());
9191}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009192
9193
John McCall864e3962010-05-07 05:32:02 +00009194/// isIntegerConstantExpr - this recursive routine will test if an expression is
9195/// an integer constant expression.
9196
9197/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9198/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009199
9200// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009201// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9202// and a (possibly null) SourceLocation indicating the location of the problem.
9203//
John McCall864e3962010-05-07 05:32:02 +00009204// Note that to reduce code duplication, this helper does no evaluation
9205// itself; the caller checks whether the expression is evaluatable, and
9206// in the rare cases where CheckICE actually cares about the evaluated
9207// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009208
Dan Gohman28ade552010-07-26 21:25:24 +00009209namespace {
9210
Richard Smith9e575da2012-12-28 13:25:52 +00009211enum ICEKind {
9212 /// This expression is an ICE.
9213 IK_ICE,
9214 /// This expression is not an ICE, but if it isn't evaluated, it's
9215 /// a legal subexpression for an ICE. This return value is used to handle
9216 /// the comma operator in C99 mode, and non-constant subexpressions.
9217 IK_ICEIfUnevaluated,
9218 /// This expression is not an ICE, and is not a legal subexpression for one.
9219 IK_NotICE
9220};
9221
John McCall864e3962010-05-07 05:32:02 +00009222struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009223 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009224 SourceLocation Loc;
9225
Richard Smith9e575da2012-12-28 13:25:52 +00009226 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009227};
9228
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009229}
Dan Gohman28ade552010-07-26 21:25:24 +00009230
Richard Smith9e575da2012-12-28 13:25:52 +00009231static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9232
9233static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009234
Craig Toppera31a8822013-08-22 07:09:37 +00009235static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009236 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009237 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009238 !EVResult.Val.isInt())
9239 return ICEDiag(IK_NotICE, E->getLocStart());
9240
John McCall864e3962010-05-07 05:32:02 +00009241 return NoDiag();
9242}
9243
Craig Toppera31a8822013-08-22 07:09:37 +00009244static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009245 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009246 if (!E->getType()->isIntegralOrEnumerationType())
9247 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009248
9249 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009250#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009251#define STMT(Node, Base) case Expr::Node##Class:
9252#define EXPR(Node, Base)
9253#include "clang/AST/StmtNodes.inc"
9254 case Expr::PredefinedExprClass:
9255 case Expr::FloatingLiteralClass:
9256 case Expr::ImaginaryLiteralClass:
9257 case Expr::StringLiteralClass:
9258 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009259 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009260 case Expr::MemberExprClass:
9261 case Expr::CompoundAssignOperatorClass:
9262 case Expr::CompoundLiteralExprClass:
9263 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009264 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009265 case Expr::NoInitExprClass:
9266 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009267 case Expr::ImplicitValueInitExprClass:
9268 case Expr::ParenListExprClass:
9269 case Expr::VAArgExprClass:
9270 case Expr::AddrLabelExprClass:
9271 case Expr::StmtExprClass:
9272 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009273 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009274 case Expr::CXXDynamicCastExprClass:
9275 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009276 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009277 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009278 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009279 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009280 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009281 case Expr::CXXThisExprClass:
9282 case Expr::CXXThrowExprClass:
9283 case Expr::CXXNewExprClass:
9284 case Expr::CXXDeleteExprClass:
9285 case Expr::CXXPseudoDestructorExprClass:
9286 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009287 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009288 case Expr::DependentScopeDeclRefExprClass:
9289 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009290 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009291 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009292 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009293 case Expr::CXXTemporaryObjectExprClass:
9294 case Expr::CXXUnresolvedConstructExprClass:
9295 case Expr::CXXDependentScopeMemberExprClass:
9296 case Expr::UnresolvedMemberExprClass:
9297 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009298 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009299 case Expr::ObjCArrayLiteralClass:
9300 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009301 case Expr::ObjCEncodeExprClass:
9302 case Expr::ObjCMessageExprClass:
9303 case Expr::ObjCSelectorExprClass:
9304 case Expr::ObjCProtocolExprClass:
9305 case Expr::ObjCIvarRefExprClass:
9306 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009307 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009308 case Expr::ObjCIsaExprClass:
9309 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009310 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009311 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009312 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009313 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009314 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009315 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009316 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009317 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009318 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009319 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009320 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009321 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009322 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009323 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009324 case Expr::CoawaitExprClass:
9325 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009326 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009327
Richard Smithf137f932014-01-25 20:50:08 +00009328 case Expr::InitListExprClass: {
9329 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9330 // form "T x = { a };" is equivalent to "T x = a;".
9331 // Unless we're initializing a reference, T is a scalar as it is known to be
9332 // of integral or enumeration type.
9333 if (E->isRValue())
9334 if (cast<InitListExpr>(E)->getNumInits() == 1)
9335 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9336 return ICEDiag(IK_NotICE, E->getLocStart());
9337 }
9338
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009339 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009340 case Expr::GNUNullExprClass:
9341 // GCC considers the GNU __null value to be an integral constant expression.
9342 return NoDiag();
9343
John McCall7c454bb2011-07-15 05:09:51 +00009344 case Expr::SubstNonTypeTemplateParmExprClass:
9345 return
9346 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9347
John McCall864e3962010-05-07 05:32:02 +00009348 case Expr::ParenExprClass:
9349 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009350 case Expr::GenericSelectionExprClass:
9351 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009352 case Expr::IntegerLiteralClass:
9353 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009354 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009355 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009356 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009357 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009358 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009359 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009360 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009361 return NoDiag();
9362 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009363 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009364 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9365 // constant expressions, but they can never be ICEs because an ICE cannot
9366 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009367 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009368 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009369 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009370 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009371 }
Richard Smith6365c912012-02-24 22:12:32 +00009372 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009373 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9374 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009375 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009376 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009377 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009378 // Parameter variables are never constants. Without this check,
9379 // getAnyInitializer() can find a default argument, which leads
9380 // to chaos.
9381 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009382 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009383
9384 // C++ 7.1.5.1p2
9385 // A variable of non-volatile const-qualified integral or enumeration
9386 // type initialized by an ICE can be used in ICEs.
9387 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009388 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009389 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009390
Richard Smithd0b4dd62011-12-19 06:19:21 +00009391 const VarDecl *VD;
9392 // Look for a declaration of this variable that has an initializer, and
9393 // check whether it is an ICE.
9394 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9395 return NoDiag();
9396 else
Richard Smith9e575da2012-12-28 13:25:52 +00009397 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009398 }
9399 }
Richard Smith9e575da2012-12-28 13:25:52 +00009400 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009401 }
John McCall864e3962010-05-07 05:32:02 +00009402 case Expr::UnaryOperatorClass: {
9403 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9404 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009405 case UO_PostInc:
9406 case UO_PostDec:
9407 case UO_PreInc:
9408 case UO_PreDec:
9409 case UO_AddrOf:
9410 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009411 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009412 // C99 6.6/3 allows increment and decrement within unevaluated
9413 // subexpressions of constant expressions, but they can never be ICEs
9414 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009415 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009416 case UO_Extension:
9417 case UO_LNot:
9418 case UO_Plus:
9419 case UO_Minus:
9420 case UO_Not:
9421 case UO_Real:
9422 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009423 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009424 }
Richard Smith9e575da2012-12-28 13:25:52 +00009425
John McCall864e3962010-05-07 05:32:02 +00009426 // OffsetOf falls through here.
9427 }
9428 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009429 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9430 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9431 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9432 // compliance: we should warn earlier for offsetof expressions with
9433 // array subscripts that aren't ICEs, and if the array subscripts
9434 // are ICEs, the value of the offsetof must be an integer constant.
9435 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009436 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009437 case Expr::UnaryExprOrTypeTraitExprClass: {
9438 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9439 if ((Exp->getKind() == UETT_SizeOf) &&
9440 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009441 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009442 return NoDiag();
9443 }
9444 case Expr::BinaryOperatorClass: {
9445 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9446 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009447 case BO_PtrMemD:
9448 case BO_PtrMemI:
9449 case BO_Assign:
9450 case BO_MulAssign:
9451 case BO_DivAssign:
9452 case BO_RemAssign:
9453 case BO_AddAssign:
9454 case BO_SubAssign:
9455 case BO_ShlAssign:
9456 case BO_ShrAssign:
9457 case BO_AndAssign:
9458 case BO_XorAssign:
9459 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009460 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9461 // constant expressions, but they can never be ICEs because an ICE cannot
9462 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009463 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009464
John McCalle3027922010-08-25 11:45:40 +00009465 case BO_Mul:
9466 case BO_Div:
9467 case BO_Rem:
9468 case BO_Add:
9469 case BO_Sub:
9470 case BO_Shl:
9471 case BO_Shr:
9472 case BO_LT:
9473 case BO_GT:
9474 case BO_LE:
9475 case BO_GE:
9476 case BO_EQ:
9477 case BO_NE:
9478 case BO_And:
9479 case BO_Xor:
9480 case BO_Or:
9481 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009482 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9483 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009484 if (Exp->getOpcode() == BO_Div ||
9485 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009486 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009487 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009488 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009489 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009490 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009491 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009492 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009493 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009494 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009495 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009496 }
9497 }
9498 }
John McCalle3027922010-08-25 11:45:40 +00009499 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009500 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009501 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9502 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009503 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9504 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009505 } else {
9506 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009507 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009508 }
9509 }
Richard Smith9e575da2012-12-28 13:25:52 +00009510 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009511 }
John McCalle3027922010-08-25 11:45:40 +00009512 case BO_LAnd:
9513 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009514 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009516 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009517 // Rare case where the RHS has a comma "side-effect"; we need
9518 // to actually check the condition to see whether the side
9519 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009520 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009521 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009522 return RHSResult;
9523 return NoDiag();
9524 }
9525
Richard Smith9e575da2012-12-28 13:25:52 +00009526 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009527 }
9528 }
9529 }
9530 case Expr::ImplicitCastExprClass:
9531 case Expr::CStyleCastExprClass:
9532 case Expr::CXXFunctionalCastExprClass:
9533 case Expr::CXXStaticCastExprClass:
9534 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009535 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009536 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009537 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009538 if (isa<ExplicitCastExpr>(E)) {
9539 if (const FloatingLiteral *FL
9540 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9541 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9542 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9543 APSInt IgnoredVal(DestWidth, !DestSigned);
9544 bool Ignored;
9545 // If the value does not fit in the destination type, the behavior is
9546 // undefined, so we are not required to treat it as a constant
9547 // expression.
9548 if (FL->getValue().convertToInteger(IgnoredVal,
9549 llvm::APFloat::rmTowardZero,
9550 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009551 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009552 return NoDiag();
9553 }
9554 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009555 switch (cast<CastExpr>(E)->getCastKind()) {
9556 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009557 case CK_AtomicToNonAtomic:
9558 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009559 case CK_NoOp:
9560 case CK_IntegralToBoolean:
9561 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009562 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009563 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009564 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009565 }
John McCall864e3962010-05-07 05:32:02 +00009566 }
John McCallc07a0c72011-02-17 10:25:35 +00009567 case Expr::BinaryConditionalOperatorClass: {
9568 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9569 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009570 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009571 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009572 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9573 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9574 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009575 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009576 return FalseResult;
9577 }
John McCall864e3962010-05-07 05:32:02 +00009578 case Expr::ConditionalOperatorClass: {
9579 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9580 // If the condition (ignoring parens) is a __builtin_constant_p call,
9581 // then only the true side is actually considered in an integer constant
9582 // expression, and it is fully evaluated. This is an important GNU
9583 // extension. See GCC PR38377 for discussion.
9584 if (const CallExpr *CallCE
9585 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009586 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009587 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009588 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009589 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009590 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009591
Richard Smithf57d8cb2011-12-09 22:58:01 +00009592 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9593 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009594
Richard Smith9e575da2012-12-28 13:25:52 +00009595 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009596 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009597 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009598 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009599 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009600 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009601 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009602 return NoDiag();
9603 // Rare case where the diagnostics depend on which side is evaluated
9604 // Note that if we get here, CondResult is 0, and at least one of
9605 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009606 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009607 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009608 return TrueResult;
9609 }
9610 case Expr::CXXDefaultArgExprClass:
9611 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009612 case Expr::CXXDefaultInitExprClass:
9613 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009614 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009615 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009616 }
9617 }
9618
David Blaikiee4d798f2012-01-20 21:50:17 +00009619 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009620}
9621
Richard Smithf57d8cb2011-12-09 22:58:01 +00009622/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009623static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009624 const Expr *E,
9625 llvm::APSInt *Value,
9626 SourceLocation *Loc) {
9627 if (!E->getType()->isIntegralOrEnumerationType()) {
9628 if (Loc) *Loc = E->getExprLoc();
9629 return false;
9630 }
9631
Richard Smith66e05fe2012-01-18 05:21:49 +00009632 APValue Result;
9633 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009634 return false;
9635
Richard Smith98710fc2014-11-13 23:03:19 +00009636 if (!Result.isInt()) {
9637 if (Loc) *Loc = E->getExprLoc();
9638 return false;
9639 }
9640
Richard Smith66e05fe2012-01-18 05:21:49 +00009641 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009642 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009643}
9644
Craig Toppera31a8822013-08-22 07:09:37 +00009645bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9646 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009647 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009648 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009649
Richard Smith9e575da2012-12-28 13:25:52 +00009650 ICEDiag D = CheckICE(this, Ctx);
9651 if (D.Kind != IK_ICE) {
9652 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009653 return false;
9654 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009655 return true;
9656}
9657
Craig Toppera31a8822013-08-22 07:09:37 +00009658bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009659 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009660 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009661 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9662
9663 if (!isIntegerConstantExpr(Ctx, Loc))
9664 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009665 // The only possible side-effects here are due to UB discovered in the
9666 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9667 // required to treat the expression as an ICE, so we produce the folded
9668 // value.
9669 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009670 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009671 return true;
9672}
Richard Smith66e05fe2012-01-18 05:21:49 +00009673
Craig Toppera31a8822013-08-22 07:09:37 +00009674bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009675 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009676}
9677
Craig Toppera31a8822013-08-22 07:09:37 +00009678bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009679 SourceLocation *Loc) const {
9680 // We support this checking in C++98 mode in order to diagnose compatibility
9681 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009682 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009683
Richard Smith98a0a492012-02-14 21:38:30 +00009684 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009685 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009686 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009687 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009688 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009689
9690 APValue Scratch;
9691 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9692
9693 if (!Diags.empty()) {
9694 IsConstExpr = false;
9695 if (Loc) *Loc = Diags[0].first;
9696 } else if (!IsConstExpr) {
9697 // FIXME: This shouldn't happen.
9698 if (Loc) *Loc = getExprLoc();
9699 }
9700
9701 return IsConstExpr;
9702}
Richard Smith253c2a32012-01-27 01:14:48 +00009703
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009704bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9705 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009706 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009707 Expr::EvalStatus Status;
9708 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9709
9710 ArgVector ArgValues(Args.size());
9711 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9712 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009713 if ((*I)->isValueDependent() ||
9714 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009715 // If evaluation fails, throw away the argument entirely.
9716 ArgValues[I - Args.begin()] = APValue();
9717 if (Info.EvalStatus.HasSideEffects)
9718 return false;
9719 }
9720
9721 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009722 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009723 ArgValues.data());
9724 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9725}
9726
Richard Smith253c2a32012-01-27 01:14:48 +00009727bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009728 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009729 PartialDiagnosticAt> &Diags) {
9730 // FIXME: It would be useful to check constexpr function templates, but at the
9731 // moment the constant expression evaluator cannot cope with the non-rigorous
9732 // ASTs which we build for dependent expressions.
9733 if (FD->isDependentContext())
9734 return true;
9735
9736 Expr::EvalStatus Status;
9737 Status.Diag = &Diags;
9738
Richard Smith6d4c6582013-11-05 22:18:15 +00009739 EvalInfo Info(FD->getASTContext(), Status,
9740 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009741
9742 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009743 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009744
Richard Smith7525ff62013-05-09 07:14:00 +00009745 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009746 // is a temporary being used as the 'this' pointer.
9747 LValue This;
9748 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009749 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009750
Richard Smith253c2a32012-01-27 01:14:48 +00009751 ArrayRef<const Expr*> Args;
9752
9753 SourceLocation Loc = FD->getLocation();
9754
Richard Smith2e312c82012-03-03 22:46:17 +00009755 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009756 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9757 // Evaluate the call as a constant initializer, to allow the construction
9758 // of objects of non-literal types.
9759 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009760 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009761 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009762 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009763 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009764
9765 return Diags.empty();
9766}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009767
9768bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9769 const FunctionDecl *FD,
9770 SmallVectorImpl<
9771 PartialDiagnosticAt> &Diags) {
9772 Expr::EvalStatus Status;
9773 Status.Diag = &Diags;
9774
9775 EvalInfo Info(FD->getASTContext(), Status,
9776 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9777
9778 // Fabricate a call stack frame to give the arguments a plausible cover story.
9779 ArrayRef<const Expr*> Args;
9780 ArgVector ArgValues(0);
9781 bool Success = EvaluateArgs(Args, ArgValues, Info);
9782 (void)Success;
9783 assert(Success &&
9784 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009785 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009786
9787 APValue ResultScratch;
9788 Evaluate(ResultScratch, Info, E);
9789 return Diags.empty();
9790}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009791
9792bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9793 unsigned Type) const {
9794 if (!getType()->isPointerType())
9795 return false;
9796
9797 Expr::EvalStatus Status;
9798 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9799 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9800}