blob: 2022b07bffedf9c96764720f8abd8d8a8ae36e5b [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"
Tim Northover314fbfa2018-11-02 13:14:11 +000042#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000043#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000044#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000045#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000046#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Fangrui Song407659a2018-11-30 23:41:18 +000048#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000049#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000050#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000051#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000052
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000053#define DEBUG_TYPE "exprconstant"
54
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000056using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000057using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058
Richard Smithb228a862012-02-15 02:18:13 +000059static bool IsGlobalLValue(APValue::LValueBase B);
60
John McCall93d91dc2010-05-07 17:22:02 +000061namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000062 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000063 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000064 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000065
Richard Smithb228a862012-02-15 02:18:13 +000066 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000067 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000068 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000070 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000071 //
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000074 //
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
80 return T;
81 }
82 return D->getType();
83 }
Richard Smith84401042013-06-03 05:03:02 +000084
85 const Expr *Base = B.get<const Expr*>();
86
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95 Adjustments);
96 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000097 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000099 return Inner->getType();
100 }
101
102 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000103 }
104
Richard Smithd62306a2011-11-10 06:34:14 +0000105 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000107 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000109 APValue::BaseOrMemberType Value;
110 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000111 return Value;
112 }
113
114 /// Get an LValue path entry, which is known to not be an array index, as a
115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000123 }
124 /// Determine whether this LValue path entry for a base class names a virtual
125 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000127 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000128 }
129
George Burgess IVe3763372016-12-22 02:50:20 +0000130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 }
135
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
138 ///
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
142 return nullptr;
143
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000150
George Burgess IVe3763372016-12-22 02:50:20 +0000151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
153
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
156 return nullptr;
157 }
158
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 }
165
Richard Smith6f4f0f12017-10-20 22:56:25 +0000166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
171
George Burgess IVe3763372016-12-22 02:50:20 +0000172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000176 static unsigned
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000185 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000186 Type = getType(Base);
187
Richard Smith80815602011-11-07 05:07:52 +0000188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000189 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
197 } else {
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
201 }
Richard Smith66c96992012-02-18 22:04:06 +0000202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
205 ArraySize = 2;
206 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000212 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 } else {
Richard Smith80815602011-11-07 05:07:52 +0000214 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000216 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 }
Richard Smith80815602011-11-07 05:07:52 +0000218 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000220 }
221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000225 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 };
227
Richard Smith96e0c102011-11-04 02:25:55 +0000228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Daniel Jasperffdee092017-05-02 19:21:42 +0000238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000240
George Burgess IVa51c4072015-10-16 01:49:01 +0000241 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// The length of the path to the most-derived object of which this is a
245 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000246 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247
George Burgess IVa51c4072015-10-16 01:49:01 +0000248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000252 ///
253 /// If the current array is an unsized array, the value of this is
254 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 uint64_t MostDerivedArraySize;
256
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000259
Richard Smith80815602011-11-07 05:07:52 +0000260 typedef APValue::LValuePathEntry PathEntry;
261
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000266
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000272
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000278 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000282 if (V.getLValueBase()) {
283 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000284 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000288 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000290 }
Richard Smith80815602011-11-07 05:07:52 +0000291 }
292 }
293
Richard Smith96e0c102011-11-04 02:25:55 +0000294 void setInvalid() {
295 Invalid = true;
296 Entries.clear();
297 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000298
George Burgess IVe3763372016-12-22 02:50:20 +0000299 /// Determine whether the most derived subobject is an array without a
300 /// known bound.
301 bool isMostDerivedAnUnsizedArray() const {
302 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 }
305
306 /// Determine what the most derived array's size is. Results in an assertion
307 /// failure if the most derived array lacks a size.
308 uint64_t getMostDerivedArraySize() const {
309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310 return MostDerivedArraySize;
311 }
312
Richard Smitha8105bc2012-01-06 16:39:00 +0000313 /// Determine whether this is a one-past-the-end pointer.
314 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000315 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000316 if (IsOnePastTheEnd)
317 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320 return true;
321 return false;
322 }
323
Richard Smith06f71b52018-08-04 00:57:17 +0000324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
329 return {0, 0};
330
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
336 uint64_t ArrayIndex =
337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338 uint64_t ArraySize =
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
345 if (Invalid)
346 return false;
347 return !isOnePastTheEnd();
348 }
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352
Richard Smith06f71b52018-08-04 00:57:17 +0000353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
357 ? MostDerivedType
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359 }
360
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000363 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000364 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // This is a most-derived object.
368 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000369 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000370 MostDerivedArraySize = CAT->getSize().getZExtValue();
371 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000372 }
George Burgess IVe3763372016-12-22 02:50:20 +0000373 /// Update this designator to refer to the first element within the array of
374 /// elements of type T. This is an array of unknown size.
375 void addUnsizedArrayUnchecked(QualType ElemTy) {
376 PathEntry Entry;
377 Entry.ArrayIndex = 0;
378 Entries.push_back(Entry);
379
380 MostDerivedType = ElemTy;
381 MostDerivedIsArrayElement = true;
382 // The value in MostDerivedArraySize is undefined in this case. So, set it
383 // to an arbitrary value that's likely to loudly break things if it's
384 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000385 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith96e0c102011-11-04 02:25:55 +0000388 /// Update this designator to refer to the given base or member of this
389 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000391 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000392 APValue::BaseOrMemberType Value(D, Virtual);
393 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000394 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000395
396 // If this isn't a base class, it's a new most-derived object.
397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = 0;
401 MostDerivedPathLength = Entries.size();
402 }
Richard Smith96e0c102011-11-04 02:25:55 +0000403 }
Richard Smith66c96992012-02-18 22:04:06 +0000404 /// Update this designator to refer to the given complex component.
405 void addComplexUnchecked(QualType EltTy, bool Imag) {
406 PathEntry Entry;
407 Entry.ArrayIndex = Imag;
408 Entries.push_back(Entry);
409
410 // This is technically a most-derived object, though in practice this
411 // is unlikely to matter.
412 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000413 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000414 MostDerivedArraySize = 2;
415 MostDerivedPathLength = Entries.size();
416 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000420 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422 if (Invalid || !N) return;
423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000425 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000426 // Can't verify -- trust that the user is doing the right thing (or if
427 // not, trust that the caller will catch the bad behavior).
428 // FIXME: Should we reject if this overflows, at least?
429 Entries.back().ArrayIndex += TruncatedN;
430 return;
431 }
432
433 // [expr.add]p4: For the purposes of these operators, a pointer to a
434 // nonarray object behaves the same as a pointer to the first element of
435 // an array of length one with the type of the object as its element type.
436 bool IsArray = MostDerivedPathLength == Entries.size() &&
437 MostDerivedIsArrayElement;
438 uint64_t ArrayIndex =
439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440 uint64_t ArraySize =
441 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442
443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444 // Calculate the actual index in a wide enough type, so we can include
445 // it in the note.
446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447 (llvm::APInt&)N += ArrayIndex;
448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449 diagnosePointerArithmetic(Info, E, N);
450 setInvalid();
451 return;
452 }
453
454 ArrayIndex += TruncatedN;
455 assert(ArrayIndex <= ArraySize &&
456 "bounds check succeeded for out-of-bounds index");
457
458 if (IsArray)
459 Entries.back().ArrayIndex = ArrayIndex;
460 else
461 IsOnePastTheEnd = (ArrayIndex != 0);
462 }
Richard Smith96e0c102011-11-04 02:25:55 +0000463 };
464
Richard Smith254a73d2011-10-28 22:34:42 +0000465 /// A stack frame in the constexpr call stack.
466 struct CallStackFrame {
467 EvalInfo &Info;
468
469 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000470 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Callee - The function which was called.
473 const FunctionDecl *Callee;
474
Richard Smithd62306a2011-11-10 06:34:14 +0000475 /// This - The binding for the this pointer in this call, if any.
476 const LValue *This;
477
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000478 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000480 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000481
Eli Friedman4830ec82012-06-25 21:21:08 +0000482 // Note that we intentionally use std::map here so that references to
483 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000484 typedef std::pair<const void *, unsigned> MapKeyTy;
485 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 /// Temporaries - Temporary lvalues materialized within this stack frame.
487 MapTy Temporaries;
488
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000489 /// CallLoc - The location of the call expression for this call.
490 SourceLocation CallLoc;
491
492 /// Index - The call index of this call.
493 unsigned Index;
494
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000495 /// The stack of integers for tracking version numbers for temporaries.
496 SmallVector<unsigned, 2> TempVersionStack = {1};
497 unsigned CurTempVersion = TempVersionStack.back();
498
499 unsigned getTempVersion() const { return TempVersionStack.back(); }
500
501 void pushTempVersion() {
502 TempVersionStack.push_back(++CurTempVersion);
503 }
504
505 void popTempVersion() {
506 TempVersionStack.pop_back();
507 }
508
Faisal Vali051e3a22017-02-16 04:12:21 +0000509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000510 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000511 // (We should cache this map rather than recomputing it repeatedly.)
512 // But let's try this and see how it goes; we can look into caching the map
513 // as a later change.
514
515 /// LambdaCaptureFields - Mapping from captured variables/this to
516 /// corresponding data members in the closure class.
517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518 FieldDecl *LambdaThisCaptureField;
519
Richard Smithf6f003a2011-12-16 19:06:07 +0000520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000522 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000524
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000525 // Return the temporary for Key whose version number is Version.
526 APValue *getTemporary(const void *Key, unsigned Version) {
527 MapKeyTy KV(Key, Version);
528 auto LB = Temporaries.lower_bound(KV);
529 if (LB != Temporaries.end() && LB->first == KV)
530 return &LB->second;
531 // Pair (Key,Version) wasn't found in the map. Check that no elements
532 // in the map have 'Key' as their key.
533 assert((LB == Temporaries.end() || LB->first.first != Key) &&
534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535 "Element with key 'Key' found in map");
536 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000538
539 // Return the current temporary for Key in the map.
540 APValue *getCurrentTemporary(const void *Key) {
541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543 return &std::prev(UB)->second;
544 return nullptr;
545 }
546
547 // Return the version number of the current temporary for Key.
548 unsigned getCurrentTemporaryVersion(const void *Key) const {
549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551 return std::prev(UB)->first.second;
552 return 0;
553 }
554
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000556 };
557
Richard Smith852c9db2013-04-20 22:23:05 +0000558 /// Temporarily override 'this'.
559 class ThisOverrideRAII {
560 public:
561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562 : Frame(Frame), OldThis(Frame.This) {
563 if (Enable)
564 Frame.This = NewThis;
565 }
566 ~ThisOverrideRAII() {
567 Frame.This = OldThis;
568 }
569 private:
570 CallStackFrame &Frame;
571 const LValue *OldThis;
572 };
573
Richard Smith92b1ce02011-12-12 09:28:41 +0000574 /// A partial diagnostic which we might know in advance that we are not going
575 /// to emit.
576 class OptionalDiagnostic {
577 PartialDiagnostic *Diag;
578
579 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000582
583 template<typename T>
584 OptionalDiagnostic &operator<<(const T &v) {
585 if (Diag)
586 *Diag << v;
587 return *this;
588 }
Richard Smithfe800032012-01-31 04:08:20 +0000589
590 OptionalDiagnostic &operator<<(const APSInt &I) {
591 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000592 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000593 I.toString(Buffer);
594 *Diag << StringRef(Buffer.data(), Buffer.size());
595 }
596 return *this;
597 }
598
599 OptionalDiagnostic &operator<<(const APFloat &F) {
600 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000601 // FIXME: Force the precision of the source value down so we don't
602 // print digits which are usually useless (we don't really care here if
603 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000604 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000605 // representation which rounds to the correct value, but it's a bit
606 // tricky to implement.
607 unsigned precision =
608 llvm::APFloat::semanticsPrecision(F.getSemantics());
609 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000611 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 };
617
Richard Smith08d6a2c2013-07-24 07:11:57 +0000618 /// A cleanup, and a flag indicating whether it is lifetime-extended.
619 class Cleanup {
620 llvm::PointerIntPair<APValue*, 1, bool> Value;
621
622 public:
623 Cleanup(APValue *Val, bool IsLifetimeExtended)
624 : Value(Val, IsLifetimeExtended) {}
625
626 bool isLifetimeExtended() const { return Value.getInt(); }
627 void endLifetime() {
628 *Value.getPointer() = APValue();
629 }
630 };
631
Richard Smithb228a862012-02-15 02:18:13 +0000632 /// EvalInfo - This is a private struct used by the evaluator to capture
633 /// information about a subexpression as it is folded. It retains information
634 /// about the AST context, but also maintains information about the folded
635 /// expression.
636 ///
637 /// If an expression could be evaluated, it is still possible it is not a C
638 /// "integer constant expression" or constant expression. If not, this struct
639 /// captures information about how and why not.
640 ///
641 /// One bit of information passed *into* the request for constant folding
642 /// indicates whether the subexpression is "evaluated" or not according to C
643 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
644 /// evaluate the expression regardless of what the RHS is, but C only allows
645 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000646 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000647 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000648
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000649 /// EvalStatus - Contains information about the evaluation.
650 Expr::EvalStatus &EvalStatus;
651
652 /// CurrentCall - The top of the constexpr call stack.
653 CallStackFrame *CurrentCall;
654
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000655 /// CallStackDepth - The number of calls in the call stack right now.
656 unsigned CallStackDepth;
657
Richard Smithb228a862012-02-15 02:18:13 +0000658 /// NextCallIndex - The next call index to assign.
659 unsigned NextCallIndex;
660
Richard Smitha3d3bd22013-05-08 02:12:03 +0000661 /// StepsLeft - The remaining number of evaluation steps we're permitted
662 /// to perform. This is essentially a limit for the number of statements
663 /// we will evaluate.
664 unsigned StepsLeft;
665
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000667 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000668 CallStackFrame BottomFrame;
669
Richard Smith08d6a2c2013-07-24 07:11:57 +0000670 /// A stack of values whose lifetimes end at the end of some surrounding
671 /// evaluation frame.
672 llvm::SmallVector<Cleanup, 16> CleanupStack;
673
Richard Smithd62306a2011-11-10 06:34:14 +0000674 /// EvaluatingDecl - This is the declaration whose initializer is being
675 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000676 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000677
678 /// EvaluatingDeclValue - This is the value being constructed for the
679 /// declaration whose initializer is being evaluated, if any.
680 APValue *EvaluatingDeclValue;
681
Erik Pilkington42925492017-10-04 00:18:55 +0000682 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
683 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000684 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
685 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000686
687 /// EvaluatingConstructors - Set of objects that are currently being
688 /// constructed.
689 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
690
691 struct EvaluatingConstructorRAII {
692 EvalInfo &EI;
693 EvaluatingObject Object;
694 bool DidInsert;
695 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
696 : EI(EI), Object(Object) {
697 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
698 }
699 ~EvaluatingConstructorRAII() {
700 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
701 }
702 };
703
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000704 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
705 unsigned Version) {
706 return EvaluatingConstructors.count(
707 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000708 }
709
Richard Smith410306b2016-12-12 02:53:20 +0000710 /// The current array initialization index, if we're performing array
711 /// initialization.
712 uint64_t ArrayInitIndex = -1;
713
Richard Smith357362d2011-12-13 06:39:58 +0000714 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
715 /// notes attached to it will also be stored, otherwise they will not be.
716 bool HasActiveDiagnostic;
717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000718 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000719 /// fold (not just why it's not strictly a constant expression)?
720 bool HasFoldFailureDiagnostic;
721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000722 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000723 bool IsSpeculativelyEvaluating;
724
Fangrui Song407659a2018-11-30 23:41:18 +0000725 /// Whether or not we're in a context where the front end requires a
726 /// constant value.
727 bool InConstantContext;
728
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 enum EvaluationMode {
730 /// Evaluate as a constant expression. Stop if we find that the expression
731 /// is not a constant expression.
732 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000733
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 /// Evaluate as a potential constant expression. Keep going if we hit a
735 /// construct that we can't evaluate yet (because we don't yet know the
736 /// value of something) but stop if we hit something that could never be
737 /// a constant expression.
738 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000739
Richard Smith6d4c6582013-11-05 22:18:15 +0000740 /// Fold the expression to a constant. Stop if we hit a side-effect that
741 /// we can't model.
742 EM_ConstantFold,
743
744 /// Evaluate the expression looking for integer overflow and similar
745 /// issues. Don't worry about side-effects, and try to visit all
746 /// subexpressions.
747 EM_EvaluateForOverflow,
748
749 /// Evaluate in any way we know how. Don't worry about side-effects that
750 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000751 EM_IgnoreSideEffects,
752
753 /// Evaluate as a constant expression. Stop if we find that the expression
754 /// is not a constant expression. Some expressions can be retried in the
755 /// optimizer if we don't constant fold them here, but in an unevaluated
756 /// context we try to fold them immediately since the optimizer never
757 /// gets a chance to look at it.
758 EM_ConstantExpressionUnevaluated,
759
760 /// Evaluate as a potential constant expression. Keep going if we hit a
761 /// construct that we can't evaluate yet (because we don't yet know the
762 /// value of something) but stop if we hit something that could never be
763 /// a constant expression. Some expressions can be retried in the
764 /// optimizer if we don't constant fold them here, but in an unevaluated
765 /// context we try to fold them immediately since the optimizer never
766 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000767 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000768 } EvalMode;
769
770 /// Are we checking whether the expression is a potential constant
771 /// expression?
772 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000773 return EvalMode == EM_PotentialConstantExpression ||
774 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000775 }
776
777 /// Are we checking an expression for overflow?
778 // FIXME: We should check for any kind of undefined or suspicious behavior
779 // in such constructs, not just overflow.
780 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
781
782 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000783 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000784 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000785 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000786 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
787 EvaluatingDecl((const ValueDecl *)nullptr),
788 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000789 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000790 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000791
Richard Smith7525ff62013-05-09 07:14:00 +0000792 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
793 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000794 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000795 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000796 }
797
David Blaikiebbafb8a2012-03-11 07:00:24 +0000798 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000799
Richard Smith357362d2011-12-13 06:39:58 +0000800 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000801 // Don't perform any constexpr calls (other than the call we're checking)
802 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000804 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000805 if (NextCallIndex == 0) {
806 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000807 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000808 return false;
809 }
Richard Smith357362d2011-12-13 06:39:58 +0000810 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
811 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000812 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000813 << getLangOpts().ConstexprCallDepth;
814 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000815 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000816
Richard Smithb228a862012-02-15 02:18:13 +0000817 CallStackFrame *getCallFrame(unsigned CallIndex) {
818 assert(CallIndex && "no call index in getCallFrame");
819 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
820 // be null in this loop.
821 CallStackFrame *Frame = CurrentCall;
822 while (Frame->Index > CallIndex)
823 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000824 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000825 }
826
Richard Smitha3d3bd22013-05-08 02:12:03 +0000827 bool nextStep(const Stmt *S) {
828 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000829 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000830 return false;
831 }
832 --StepsLeft;
833 return true;
834 }
835
Richard Smith357362d2011-12-13 06:39:58 +0000836 private:
837 /// Add a diagnostic to the diagnostics list.
838 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
839 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
840 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
841 return EvalStatus.Diag->back().second;
842 }
843
Richard Smithf6f003a2011-12-16 19:06:07 +0000844 /// Add notes containing a call stack to the current point of evaluation.
845 void addCallStack(unsigned Limit);
846
Faisal Valie690b7a2016-07-02 22:34:24 +0000847 private:
848 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
849 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000850
Richard Smith92b1ce02011-12-12 09:28:41 +0000851 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000852 // If we have a prior diagnostic, it will be noting that the expression
853 // isn't a constant expression. This diagnostic is more important,
854 // unless we require this evaluation to produce a constant expression.
855 //
856 // FIXME: We might want to show both diagnostics to the user in
857 // EM_ConstantFold mode.
858 if (!EvalStatus.Diag->empty()) {
859 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000860 case EM_ConstantFold:
861 case EM_IgnoreSideEffects:
862 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000863 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000864 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000865 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000866 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000867 case EM_ConstantExpression:
868 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000869 case EM_ConstantExpressionUnevaluated:
870 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000871 HasActiveDiagnostic = false;
872 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000873 }
874 }
875
Richard Smithf6f003a2011-12-16 19:06:07 +0000876 unsigned CallStackNotes = CallStackDepth - 1;
877 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
878 if (Limit)
879 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000881 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000882
Richard Smith357362d2011-12-13 06:39:58 +0000883 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000884 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000885 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000886 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
887 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000889 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000890 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000891 }
Richard Smith357362d2011-12-13 06:39:58 +0000892 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000893 return OptionalDiagnostic();
894 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000895 public:
896 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
897 OptionalDiagnostic
898 FFDiag(SourceLocation Loc,
899 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
900 unsigned ExtraNotes = 0) {
901 return Diag(Loc, DiagId, ExtraNotes, false);
902 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000903
Faisal Valie690b7a2016-07-02 22:34:24 +0000904 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000905 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000906 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000907 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000908 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000909 HasActiveDiagnostic = false;
910 return OptionalDiagnostic();
911 }
912
Richard Smith92b1ce02011-12-12 09:28:41 +0000913 /// Diagnose that the evaluation does not produce a C++11 core constant
914 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 ///
916 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
917 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000918 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000919 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000920 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000921 // Don't override a previous diagnostic. Don't bother collecting
922 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000923 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000924 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000925 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000926 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000927 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000928 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000929 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
930 = diag::note_invalid_subexpr_in_const_expr,
931 unsigned ExtraNotes = 0) {
932 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
933 }
Richard Smith357362d2011-12-13 06:39:58 +0000934 /// Add a note to a prior diagnostic.
935 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
936 if (!HasActiveDiagnostic)
937 return OptionalDiagnostic();
938 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000939 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000940
941 /// Add a stack of notes to a prior diagnostic.
942 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
943 if (HasActiveDiagnostic) {
944 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
945 Diags.begin(), Diags.end());
946 }
947 }
Richard Smith253c2a32012-01-27 01:14:48 +0000948
Richard Smith6d4c6582013-11-05 22:18:15 +0000949 /// Should we continue evaluation after encountering a side-effect that we
950 /// couldn't model?
951 bool keepEvaluatingAfterSideEffect() {
952 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000953 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000954 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000955 case EM_EvaluateForOverflow:
956 case EM_IgnoreSideEffects:
957 return true;
958
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000960 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000961 case EM_ConstantFold:
962 return false;
963 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000964 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000965 }
966
967 /// Note that we have had a side-effect, and determine whether we should
968 /// keep evaluating.
969 bool noteSideEffect() {
970 EvalStatus.HasSideEffects = true;
971 return keepEvaluatingAfterSideEffect();
972 }
973
Richard Smithce8eca52015-12-08 03:21:47 +0000974 /// Should we continue evaluation after encountering undefined behavior?
975 bool keepEvaluatingAfterUndefinedBehavior() {
976 switch (EvalMode) {
977 case EM_EvaluateForOverflow:
978 case EM_IgnoreSideEffects:
979 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000980 return true;
981
982 case EM_PotentialConstantExpression:
983 case EM_PotentialConstantExpressionUnevaluated:
984 case EM_ConstantExpression:
985 case EM_ConstantExpressionUnevaluated:
986 return false;
987 }
988 llvm_unreachable("Missed EvalMode case");
989 }
990
991 /// Note that we hit something that was technically undefined behavior, but
992 /// that we can evaluate past it (such as signed overflow or floating-point
993 /// division by zero.)
994 bool noteUndefinedBehavior() {
995 EvalStatus.HasUndefinedBehavior = true;
996 return keepEvaluatingAfterUndefinedBehavior();
997 }
998
Richard Smith253c2a32012-01-27 01:14:48 +0000999 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001000 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001001 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001002 if (!StepsLeft)
1003 return false;
1004
1005 switch (EvalMode) {
1006 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001007 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001008 case EM_EvaluateForOverflow:
1009 return true;
1010
1011 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001012 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001013 case EM_ConstantFold:
1014 case EM_IgnoreSideEffects:
1015 return false;
1016 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001017 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001018 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001019
George Burgess IV8c892b52016-05-25 22:31:54 +00001020 /// Notes that we failed to evaluate an expression that other expressions
1021 /// directly depend on, and determine if we should keep evaluating. This
1022 /// should only be called if we actually intend to keep evaluating.
1023 ///
1024 /// Call noteSideEffect() instead if we may be able to ignore the value that
1025 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1026 ///
1027 /// (Foo(), 1) // use noteSideEffect
1028 /// (Foo() || true) // use noteSideEffect
1029 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001030 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001031 // Failure when evaluating some expression often means there is some
1032 // subexpression whose evaluation was skipped. Therefore, (because we
1033 // don't track whether we skipped an expression when unwinding after an
1034 // evaluation failure) every evaluation failure that bubbles up from a
1035 // subexpression implies that a side-effect has potentially happened. We
1036 // skip setting the HasSideEffects flag to true until we decide to
1037 // continue evaluating after that point, which happens here.
1038 bool KeepGoing = keepEvaluatingAfterFailure();
1039 EvalStatus.HasSideEffects |= KeepGoing;
1040 return KeepGoing;
1041 }
1042
Richard Smith410306b2016-12-12 02:53:20 +00001043 class ArrayInitLoopIndex {
1044 EvalInfo &Info;
1045 uint64_t OuterIndex;
1046
1047 public:
1048 ArrayInitLoopIndex(EvalInfo &Info)
1049 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1050 Info.ArrayInitIndex = 0;
1051 }
1052 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1053
1054 operator uint64_t&() { return Info.ArrayInitIndex; }
1055 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001056 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001057
1058 /// Object used to treat all foldable expressions as constant expressions.
1059 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001060 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001061 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001062 bool HadNoPriorDiags;
1063 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001064
Richard Smith6d4c6582013-11-05 22:18:15 +00001065 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1066 : Info(Info),
1067 Enabled(Enabled),
1068 HadNoPriorDiags(Info.EvalStatus.Diag &&
1069 Info.EvalStatus.Diag->empty() &&
1070 !Info.EvalStatus.HasSideEffects),
1071 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001072 if (Enabled &&
1073 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1074 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001075 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001076 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001077 void keepDiagnostics() { Enabled = false; }
1078 ~FoldConstant() {
1079 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001080 !Info.EvalStatus.HasSideEffects)
1081 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001082 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001083 }
1084 };
Richard Smith17100ba2012-02-16 02:46:34 +00001085
James Y Knight892b09b2018-10-10 02:53:43 +00001086 /// RAII object used to set the current evaluation mode to ignore
1087 /// side-effects.
1088 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 EvalInfo &Info;
1090 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001091 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092 : Info(Info), OldMode(Info.EvalMode) {
1093 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001094 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001095 }
1096
James Y Knight892b09b2018-10-10 02:53:43 +00001097 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001098 };
1099
George Burgess IV8c892b52016-05-25 22:31:54 +00001100 /// RAII object used to optionally suppress diagnostics and side-effects from
1101 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001102 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001103 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001104 Expr::EvalStatus OldStatus;
1105 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001106
George Burgess IV8c892b52016-05-25 22:31:54 +00001107 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001108 Info = Other.Info;
1109 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001110 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001111 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001112 }
1113
1114 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001115 if (!Info)
1116 return;
1117
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001118 Info->EvalStatus = OldStatus;
1119 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001120 }
1121
Richard Smith17100ba2012-02-16 02:46:34 +00001122 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001123 SpeculativeEvaluationRAII() = default;
1124
1125 SpeculativeEvaluationRAII(
1126 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001127 : Info(&Info), OldStatus(Info.EvalStatus),
1128 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001129 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001130 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001131 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001132
1133 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1134 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1135 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001136 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001137
1138 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1139 maybeRestoreState();
1140 moveFromAndCancel(std::move(Other));
1141 return *this;
1142 }
1143
1144 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001145 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001146
1147 /// RAII object wrapping a full-expression or block scope, and handling
1148 /// the ending of the lifetime of temporaries created within it.
1149 template<bool IsFullExpression>
1150 class ScopeRAII {
1151 EvalInfo &Info;
1152 unsigned OldStackSize;
1153 public:
1154 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001155 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1156 // Push a new temporary version. This is needed to distinguish between
1157 // temporaries created in different iterations of a loop.
1158 Info.CurrentCall->pushTempVersion();
1159 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001160 ~ScopeRAII() {
1161 // Body moved to a static method to encourage the compiler to inline away
1162 // instances of this class.
1163 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001164 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001165 }
1166 private:
1167 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1168 unsigned NewEnd = OldStackSize;
1169 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1170 I != N; ++I) {
1171 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1172 // Full-expression cleanup of a lifetime-extended temporary: nothing
1173 // to do, just move this cleanup to the right place in the stack.
1174 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1175 ++NewEnd;
1176 } else {
1177 // End the lifetime of the object.
1178 Info.CleanupStack[I].endLifetime();
1179 }
1180 }
1181 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1182 Info.CleanupStack.end());
1183 }
1184 };
1185 typedef ScopeRAII<false> BlockScopeRAII;
1186 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001187}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001188
Richard Smitha8105bc2012-01-06 16:39:00 +00001189bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1190 CheckSubobjectKind CSK) {
1191 if (Invalid)
1192 return false;
1193 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001194 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001195 << CSK;
1196 setInvalid();
1197 return false;
1198 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001199 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1200 // must actually be at least one array element; even a VLA cannot have a
1201 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001202 return true;
1203}
1204
Richard Smith6f4f0f12017-10-20 22:56:25 +00001205void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1206 const Expr *E) {
1207 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1208 // Do not set the designator as invalid: we can represent this situation,
1209 // and correct handling of __builtin_object_size requires us to do so.
1210}
1211
Richard Smitha8105bc2012-01-06 16:39:00 +00001212void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001213 const Expr *E,
1214 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001215 // If we're complaining, we must be able to statically determine the size of
1216 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001217 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001218 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001219 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001220 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001221 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001222 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001223 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001224 setInvalid();
1225}
1226
Richard Smithf6f003a2011-12-16 19:06:07 +00001227CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1228 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001229 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001230 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1231 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001232 Info.CurrentCall = this;
1233 ++Info.CallStackDepth;
1234}
1235
1236CallStackFrame::~CallStackFrame() {
1237 assert(Info.CurrentCall == this && "calls retired out of order");
1238 --Info.CallStackDepth;
1239 Info.CurrentCall = Caller;
1240}
1241
Richard Smith08d6a2c2013-07-24 07:11:57 +00001242APValue &CallStackFrame::createTemporary(const void *Key,
1243 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001244 unsigned Version = Info.CurrentCall->getTempVersion();
1245 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001246 assert(Result.isUninit() && "temporary created multiple times");
1247 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1248 return Result;
1249}
1250
Richard Smith84401042013-06-03 05:03:02 +00001251static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001252
1253void EvalInfo::addCallStack(unsigned Limit) {
1254 // Determine which calls to skip, if any.
1255 unsigned ActiveCalls = CallStackDepth - 1;
1256 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1257 if (Limit && Limit < ActiveCalls) {
1258 SkipStart = Limit / 2 + Limit % 2;
1259 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001260 }
1261
Richard Smithf6f003a2011-12-16 19:06:07 +00001262 // Walk the call stack and add the diagnostics.
1263 unsigned CallIdx = 0;
1264 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1265 Frame = Frame->Caller, ++CallIdx) {
1266 // Skip this call?
1267 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1268 if (CallIdx == SkipStart) {
1269 // Note that we're skipping calls.
1270 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1271 << unsigned(ActiveCalls - Limit);
1272 }
1273 continue;
1274 }
1275
Richard Smith5179eb72016-06-28 19:03:57 +00001276 // Use a different note for an inheriting constructor, because from the
1277 // user's perspective it's not really a function at all.
1278 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1279 if (CD->isInheritingConstructor()) {
1280 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1281 << CD->getParent();
1282 continue;
1283 }
1284 }
1285
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001286 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001287 llvm::raw_svector_ostream Out(Buffer);
1288 describeCall(Frame, Out);
1289 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1290 }
1291}
1292
Hubert Tong147b7432018-12-12 16:53:43 +00001293/// Kinds of access we can perform on an object, for diagnostics.
1294enum AccessKinds {
1295 AK_Read,
1296 AK_Assign,
1297 AK_Increment,
1298 AK_Decrement
1299};
1300
Richard Smithf6f003a2011-12-16 19:06:07 +00001301namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001302 struct ComplexValue {
1303 private:
1304 bool IsInt;
1305
1306 public:
1307 APSInt IntReal, IntImag;
1308 APFloat FloatReal, FloatImag;
1309
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001310 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001311
1312 void makeComplexFloat() { IsInt = false; }
1313 bool isComplexFloat() const { return !IsInt; }
1314 APFloat &getComplexFloatReal() { return FloatReal; }
1315 APFloat &getComplexFloatImag() { return FloatImag; }
1316
1317 void makeComplexInt() { IsInt = true; }
1318 bool isComplexInt() const { return IsInt; }
1319 APSInt &getComplexIntReal() { return IntReal; }
1320 APSInt &getComplexIntImag() { return IntImag; }
1321
Richard Smith2e312c82012-03-03 22:46:17 +00001322 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001323 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001324 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001325 else
Richard Smith2e312c82012-03-03 22:46:17 +00001326 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001327 }
Richard Smith2e312c82012-03-03 22:46:17 +00001328 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001329 assert(v.isComplexFloat() || v.isComplexInt());
1330 if (v.isComplexFloat()) {
1331 makeComplexFloat();
1332 FloatReal = v.getComplexFloatReal();
1333 FloatImag = v.getComplexFloatImag();
1334 } else {
1335 makeComplexInt();
1336 IntReal = v.getComplexIntReal();
1337 IntImag = v.getComplexIntImag();
1338 }
1339 }
John McCall93d91dc2010-05-07 17:22:02 +00001340 };
John McCall45d55e42010-05-07 21:00:08 +00001341
1342 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001343 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001344 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001345 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001346 bool IsNullPtr : 1;
1347 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001348
Richard Smithce40ad62011-11-12 22:28:03 +00001349 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001350 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001351 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001352 SubobjectDesignator &getLValueDesignator() { return Designator; }
1353 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001354 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001355
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001356 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1357 unsigned getLValueVersion() const { return Base.getVersion(); }
1358
Richard Smith2e312c82012-03-03 22:46:17 +00001359 void moveInto(APValue &V) const {
1360 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001361 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001362 else {
1363 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001364 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001365 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001366 }
John McCall45d55e42010-05-07 21:00:08 +00001367 }
Richard Smith2e312c82012-03-03 22:46:17 +00001368 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001369 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001370 Base = V.getLValueBase();
1371 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001372 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001373 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001374 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001375 }
1376
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001377 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001378#ifndef NDEBUG
1379 // We only allow a few types of invalid bases. Enforce that here.
1380 if (BInvalid) {
1381 const auto *E = B.get<const Expr *>();
1382 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1383 "Unexpected type of invalid base");
1384 }
1385#endif
1386
Richard Smithce40ad62011-11-12 22:28:03 +00001387 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001388 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001389 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001390 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001391 IsNullPtr = false;
1392 }
1393
1394 void setNull(QualType PointerTy, uint64_t TargetVal) {
1395 Base = (Expr *)nullptr;
1396 Offset = CharUnits::fromQuantity(TargetVal);
1397 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001398 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1399 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001400 }
1401
George Burgess IV3a03fab2015-09-04 21:28:13 +00001402 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001403 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001404 }
1405
Hubert Tong147b7432018-12-12 16:53:43 +00001406 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 // Check that this LValue is not based on a null pointer. If it is, produce
1408 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001409 template <typename GenDiagType>
1410 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 if (Designator.Invalid)
1412 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001413 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001414 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001415 Designator.setInvalid();
1416 return false;
1417 }
1418 return true;
1419 }
1420
Hubert Tong147b7432018-12-12 16:53:43 +00001421 public:
1422 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1423 CheckSubobjectKind CSK) {
1424 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1425 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1426 });
1427 }
1428
1429 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1430 AccessKinds AK) {
1431 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1432 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1433 });
1434 }
1435
Richard Smitha8105bc2012-01-06 16:39:00 +00001436 // Check this LValue refers to an object. If not, set the designator to be
1437 // invalid and emit a diagnostic.
1438 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001439 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001440 Designator.checkSubobject(Info, E, CSK);
1441 }
1442
1443 void addDecl(EvalInfo &Info, const Expr *E,
1444 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001445 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1446 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001447 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001448 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1449 if (!Designator.Entries.empty()) {
1450 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1451 Designator.setInvalid();
1452 return;
1453 }
Richard Smithefdb5032017-11-15 03:03:56 +00001454 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1455 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1456 Designator.FirstEntryIsAnUnsizedArray = true;
1457 Designator.addUnsizedArrayUnchecked(ElemTy);
1458 }
George Burgess IVe3763372016-12-22 02:50:20 +00001459 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001460 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001461 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1462 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
Richard Smith66c96992012-02-18 22:04:06 +00001464 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001465 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1466 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001467 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001468 void clearIsNullPointer() {
1469 IsNullPtr = false;
1470 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001471 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1472 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001473 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1474 // but we're not required to diagnose it and it's valid in C++.)
1475 if (!Index)
1476 return;
1477
1478 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1479 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1480 // offsets.
1481 uint64_t Offset64 = Offset.getQuantity();
1482 uint64_t ElemSize64 = ElementSize.getQuantity();
1483 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1484 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1485
1486 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001487 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001488 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001489 }
1490 void adjustOffset(CharUnits N) {
1491 Offset += N;
1492 if (N.getQuantity())
1493 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001494 }
John McCall45d55e42010-05-07 21:00:08 +00001495 };
Richard Smith027bf112011-11-17 22:56:20 +00001496
1497 struct MemberPtr {
1498 MemberPtr() {}
1499 explicit MemberPtr(const ValueDecl *Decl) :
1500 DeclAndIsDerivedMember(Decl, false), Path() {}
1501
1502 /// The member or (direct or indirect) field referred to by this member
1503 /// pointer, or 0 if this is a null member pointer.
1504 const ValueDecl *getDecl() const {
1505 return DeclAndIsDerivedMember.getPointer();
1506 }
1507 /// Is this actually a member of some type derived from the relevant class?
1508 bool isDerivedMember() const {
1509 return DeclAndIsDerivedMember.getInt();
1510 }
1511 /// Get the class which the declaration actually lives in.
1512 const CXXRecordDecl *getContainingRecord() const {
1513 return cast<CXXRecordDecl>(
1514 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1515 }
1516
Richard Smith2e312c82012-03-03 22:46:17 +00001517 void moveInto(APValue &V) const {
1518 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001519 }
Richard Smith2e312c82012-03-03 22:46:17 +00001520 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001521 assert(V.isMemberPointer());
1522 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1523 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1524 Path.clear();
1525 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1526 Path.insert(Path.end(), P.begin(), P.end());
1527 }
1528
1529 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1530 /// whether the member is a member of some class derived from the class type
1531 /// of the member pointer.
1532 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1533 /// Path - The path of base/derived classes from the member declaration's
1534 /// class (exclusive) to the class type of the member pointer (inclusive).
1535 SmallVector<const CXXRecordDecl*, 4> Path;
1536
1537 /// Perform a cast towards the class of the Decl (either up or down the
1538 /// hierarchy).
1539 bool castBack(const CXXRecordDecl *Class) {
1540 assert(!Path.empty());
1541 const CXXRecordDecl *Expected;
1542 if (Path.size() >= 2)
1543 Expected = Path[Path.size() - 2];
1544 else
1545 Expected = getContainingRecord();
1546 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1547 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1548 // if B does not contain the original member and is not a base or
1549 // derived class of the class containing the original member, the result
1550 // of the cast is undefined.
1551 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1552 // (D::*). We consider that to be a language defect.
1553 return false;
1554 }
1555 Path.pop_back();
1556 return true;
1557 }
1558 /// Perform a base-to-derived member pointer cast.
1559 bool castToDerived(const CXXRecordDecl *Derived) {
1560 if (!getDecl())
1561 return true;
1562 if (!isDerivedMember()) {
1563 Path.push_back(Derived);
1564 return true;
1565 }
1566 if (!castBack(Derived))
1567 return false;
1568 if (Path.empty())
1569 DeclAndIsDerivedMember.setInt(false);
1570 return true;
1571 }
1572 /// Perform a derived-to-base member pointer cast.
1573 bool castToBase(const CXXRecordDecl *Base) {
1574 if (!getDecl())
1575 return true;
1576 if (Path.empty())
1577 DeclAndIsDerivedMember.setInt(true);
1578 if (isDerivedMember()) {
1579 Path.push_back(Base);
1580 return true;
1581 }
1582 return castBack(Base);
1583 }
1584 };
Richard Smith357362d2011-12-13 06:39:58 +00001585
Richard Smith7bb00672012-02-01 01:42:44 +00001586 /// Compare two member pointers, which are assumed to be of the same type.
1587 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1588 if (!LHS.getDecl() || !RHS.getDecl())
1589 return !LHS.getDecl() && !RHS.getDecl();
1590 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1591 return false;
1592 return LHS.Path == RHS.Path;
1593 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001594}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001595
Richard Smith2e312c82012-03-03 22:46:17 +00001596static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001597static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1598 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001599 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001600static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1601 bool InvalidBaseOK = false);
1602static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1603 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001604static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1605 EvalInfo &Info);
1606static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001607static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001608static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001609 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001610static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001611static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001612static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1613 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001614static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001615
1616//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001617// Misc utilities
1618//===----------------------------------------------------------------------===//
1619
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001620/// A helper function to create a temporary and set an LValue.
1621template <class KeyTy>
1622static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1623 LValue &LV, CallStackFrame &Frame) {
1624 LV.set({Key, Frame.Info.CurrentCall->Index,
1625 Frame.Info.CurrentCall->getTempVersion()});
1626 return Frame.createTemporary(Key, IsLifetimeExtended);
1627}
1628
Richard Smithd6cc1982017-01-31 02:23:02 +00001629/// Negate an APSInt in place, converting it to a signed form if necessary, and
1630/// preserving its value (by extending by up to one bit as needed).
1631static void negateAsSigned(APSInt &Int) {
1632 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1633 Int = Int.extend(Int.getBitWidth() + 1);
1634 Int.setIsSigned(true);
1635 }
1636 Int = -Int;
1637}
1638
Richard Smith84401042013-06-03 05:03:02 +00001639/// Produce a string describing the given constexpr call.
1640static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1641 unsigned ArgIndex = 0;
1642 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1643 !isa<CXXConstructorDecl>(Frame->Callee) &&
1644 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1645
1646 if (!IsMemberCall)
1647 Out << *Frame->Callee << '(';
1648
1649 if (Frame->This && IsMemberCall) {
1650 APValue Val;
1651 Frame->This->moveInto(Val);
1652 Val.printPretty(Out, Frame->Info.Ctx,
1653 Frame->This->Designator.MostDerivedType);
1654 // FIXME: Add parens around Val if needed.
1655 Out << "->" << *Frame->Callee << '(';
1656 IsMemberCall = false;
1657 }
1658
1659 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1660 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1661 if (ArgIndex > (unsigned)IsMemberCall)
1662 Out << ", ";
1663
1664 const ParmVarDecl *Param = *I;
1665 const APValue &Arg = Frame->Arguments[ArgIndex];
1666 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1667
1668 if (ArgIndex == 0 && IsMemberCall)
1669 Out << "->" << *Frame->Callee << '(';
1670 }
1671
1672 Out << ')';
1673}
1674
Richard Smithd9f663b2013-04-22 15:31:51 +00001675/// Evaluate an expression to see if it had side-effects, and discard its
1676/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001677/// \return \c true if the caller should keep evaluating.
1678static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001679 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001680 if (!Evaluate(Scratch, Info, E))
1681 // We don't need the value, but we might have skipped a side effect here.
1682 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001683 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001684}
1685
Richard Smithd62306a2011-11-10 06:34:14 +00001686/// Should this call expression be treated as a string literal?
1687static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001688 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001689 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1690 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1691}
1692
Richard Smithce40ad62011-11-12 22:28:03 +00001693static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001694 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1695 // constant expression of pointer type that evaluates to...
1696
1697 // ... a null pointer value, or a prvalue core constant expression of type
1698 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001699 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001700
Richard Smithce40ad62011-11-12 22:28:03 +00001701 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1702 // ... the address of an object with static storage duration,
1703 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1704 return VD->hasGlobalStorage();
1705 // ... the address of a function,
1706 return isa<FunctionDecl>(D);
1707 }
1708
1709 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001710 switch (E->getStmtClass()) {
1711 default:
1712 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001713 case Expr::CompoundLiteralExprClass: {
1714 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1715 return CLE->isFileScope() && CLE->isLValue();
1716 }
Richard Smithe6c01442013-06-05 00:46:14 +00001717 case Expr::MaterializeTemporaryExprClass:
1718 // A materialized temporary might have been lifetime-extended to static
1719 // storage duration.
1720 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001721 // A string literal has static storage duration.
1722 case Expr::StringLiteralClass:
1723 case Expr::PredefinedExprClass:
1724 case Expr::ObjCStringLiteralClass:
1725 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001726 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001727 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001728 return true;
1729 case Expr::CallExprClass:
1730 return IsStringLiteralCall(cast<CallExpr>(E));
1731 // For GCC compatibility, &&label has static storage duration.
1732 case Expr::AddrLabelExprClass:
1733 return true;
1734 // A Block literal expression may be used as the initialization value for
1735 // Block variables at global or local static scope.
1736 case Expr::BlockExprClass:
1737 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001738 case Expr::ImplicitValueInitExprClass:
1739 // FIXME:
1740 // We can never form an lvalue with an implicit value initialization as its
1741 // base through expression evaluation, so these only appear in one case: the
1742 // implicit variable declaration we invent when checking whether a constexpr
1743 // constructor can produce a constant expression. We must assume that such
1744 // an expression might be a global lvalue.
1745 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001746 }
John McCall95007602010-05-10 23:27:23 +00001747}
1748
Richard Smith06f71b52018-08-04 00:57:17 +00001749static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1750 return LVal.Base.dyn_cast<const ValueDecl*>();
1751}
1752
1753static bool IsLiteralLValue(const LValue &Value) {
1754 if (Value.getLValueCallIndex())
1755 return false;
1756 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1757 return E && !isa<MaterializeTemporaryExpr>(E);
1758}
1759
1760static bool IsWeakLValue(const LValue &Value) {
1761 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1762 return Decl && Decl->isWeak();
1763}
1764
1765static bool isZeroSized(const LValue &Value) {
1766 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1767 if (Decl && isa<VarDecl>(Decl)) {
1768 QualType Ty = Decl->getType();
1769 if (Ty->isArrayType())
1770 return Ty->isIncompleteType() ||
1771 Decl->getASTContext().getTypeSize(Ty) == 0;
1772 }
1773 return false;
1774}
1775
1776static bool HasSameBase(const LValue &A, const LValue &B) {
1777 if (!A.getLValueBase())
1778 return !B.getLValueBase();
1779 if (!B.getLValueBase())
1780 return false;
1781
1782 if (A.getLValueBase().getOpaqueValue() !=
1783 B.getLValueBase().getOpaqueValue()) {
1784 const Decl *ADecl = GetLValueBaseDecl(A);
1785 if (!ADecl)
1786 return false;
1787 const Decl *BDecl = GetLValueBaseDecl(B);
1788 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1789 return false;
1790 }
1791
1792 return IsGlobalLValue(A.getLValueBase()) ||
1793 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1794 A.getLValueVersion() == B.getLValueVersion());
1795}
1796
Richard Smithb228a862012-02-15 02:18:13 +00001797static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1798 assert(Base && "no location for a null lvalue");
1799 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1800 if (VD)
1801 Info.Note(VD->getLocation(), diag::note_declared_at);
1802 else
Ted Kremenek28831752012-08-23 20:46:57 +00001803 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001804 diag::note_constexpr_temporary_here);
1805}
1806
Richard Smith80815602011-11-07 05:07:52 +00001807/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001808/// value for an address or reference constant expression. Return true if we
1809/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001810static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001811 QualType Type, const LValue &LVal,
1812 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001813 bool IsReferenceType = Type->isReferenceType();
1814
Richard Smith357362d2011-12-13 06:39:58 +00001815 APValue::LValueBase Base = LVal.getLValueBase();
1816 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1817
Richard Smith0dea49e2012-02-18 04:58:18 +00001818 // Check that the object is a global. Note that the fake 'this' object we
1819 // manufacture when checking potential constant expressions is conservatively
1820 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001821 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001822 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001823 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001824 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001825 << IsReferenceType << !Designator.Entries.empty()
1826 << !!VD << VD;
1827 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001828 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001829 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001830 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001831 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001832 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001833 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001834 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001835 LVal.getLValueCallIndex() == 0) &&
1836 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001837
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001838 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1839 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001840 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001841 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001842 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001843
Hans Wennborg82dd8772014-06-25 22:19:48 +00001844 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001845 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001846 return false;
1847 }
1848 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1849 // __declspec(dllimport) must be handled very carefully:
1850 // We must never initialize an expression with the thunk in C++.
1851 // Doing otherwise would allow the same id-expression to yield
1852 // different addresses for the same function in different translation
1853 // units. However, this means that we must dynamically initialize the
1854 // expression with the contents of the import address table at runtime.
1855 //
1856 // The C language has no notion of ODR; furthermore, it has no notion of
1857 // dynamic initialization. This means that we are permitted to
1858 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001859 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1860 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001861 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001862 }
1863 }
1864
Richard Smitha8105bc2012-01-06 16:39:00 +00001865 // Allow address constant expressions to be past-the-end pointers. This is
1866 // an extension: the standard requires them to point to an object.
1867 if (!IsReferenceType)
1868 return true;
1869
1870 // A reference constant expression must refer to an object.
1871 if (!Base) {
1872 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001873 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001874 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001875 }
1876
Richard Smith357362d2011-12-13 06:39:58 +00001877 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001878 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001879 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001880 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001881 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001882 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001883 }
1884
Richard Smith80815602011-11-07 05:07:52 +00001885 return true;
1886}
1887
Reid Klecknercd016d82017-07-07 22:04:29 +00001888/// Member pointers are constant expressions unless they point to a
1889/// non-virtual dllimport member function.
1890static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1891 SourceLocation Loc,
1892 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001893 const APValue &Value,
1894 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001895 const ValueDecl *Member = Value.getMemberPointerDecl();
1896 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1897 if (!FD)
1898 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001899 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1900 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001901}
1902
Richard Smithfddd3842011-12-30 21:15:51 +00001903/// Check that this core constant expression is of literal type, and if not,
1904/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001905static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001906 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001907 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001908 return true;
1909
Richard Smith7525ff62013-05-09 07:14:00 +00001910 // C++1y: A constant initializer for an object o [...] may also invoke
1911 // constexpr constructors for o and its subobjects even if those objects
1912 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001913 //
1914 // C++11 missed this detail for aggregates, so classes like this:
1915 // struct foo_t { union { int i; volatile int j; } u; };
1916 // are not (obviously) initializable like so:
1917 // __attribute__((__require_constant_initialization__))
1918 // static const foo_t x = {{0}};
1919 // because "i" is a subobject with non-literal initialization (due to the
1920 // volatile member of the union). See:
1921 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1922 // Therefore, we use the C++1y behavior.
1923 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001924 return true;
1925
Richard Smithfddd3842011-12-30 21:15:51 +00001926 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001927 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001928 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001929 << E->getType();
1930 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001931 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001932 return false;
1933}
1934
Richard Smith0b0a0b62011-10-29 20:57:55 +00001935/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001936/// constant expression. If not, report an appropriate diagnostic. Does not
1937/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001938static bool
1939CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1940 const APValue &Value,
1941 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001942 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001943 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001944 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001945 return false;
1946 }
1947
Richard Smith77be48a2014-07-31 06:31:19 +00001948 // We allow _Atomic(T) to be initialized from anything that T can be
1949 // initialized from.
1950 if (const AtomicType *AT = Type->getAs<AtomicType>())
1951 Type = AT->getValueType();
1952
Richard Smithb228a862012-02-15 02:18:13 +00001953 // Core issue 1454: For a literal constant expression of array or class type,
1954 // each subobject of its value shall have been initialized by a constant
1955 // expression.
1956 if (Value.isArray()) {
1957 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1958 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1959 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001960 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001961 return false;
1962 }
1963 if (!Value.hasArrayFiller())
1964 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001965 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1966 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001967 }
Richard Smithb228a862012-02-15 02:18:13 +00001968 if (Value.isUnion() && Value.getUnionField()) {
1969 return CheckConstantExpression(Info, DiagLoc,
1970 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001971 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001972 }
1973 if (Value.isStruct()) {
1974 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1975 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1976 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001977 for (const CXXBaseSpecifier &BS : CD->bases()) {
1978 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1979 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001980 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001981 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001982 }
1983 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001984 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001985 if (I->isUnnamedBitfield())
1986 continue;
1987
David Blaikie2d7c57e2012-04-30 02:36:29 +00001988 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001989 Value.getStructField(I->getFieldIndex()),
1990 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001991 return false;
1992 }
1993 }
1994
1995 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001996 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001997 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001998 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001999 }
2000
Reid Klecknercd016d82017-07-07 22:04:29 +00002001 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002002 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002003
Richard Smithb228a862012-02-15 02:18:13 +00002004 // Everything else is fine.
2005 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002006}
2007
Richard Smith2e312c82012-03-03 22:46:17 +00002008static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002009 // A null base expression indicates a null pointer. These are always
2010 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002011 if (!Value.getLValueBase()) {
2012 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002013 return true;
2014 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002015
Richard Smith027bf112011-11-17 22:56:20 +00002016 // We have a non-null base. These are generally known to be true, but if it's
2017 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002018 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002019 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002020 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002021}
2022
Richard Smith2e312c82012-03-03 22:46:17 +00002023static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002024 switch (Val.getKind()) {
2025 case APValue::Uninitialized:
2026 return false;
2027 case APValue::Int:
2028 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002029 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002030 case APValue::Float:
2031 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002032 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002033 case APValue::ComplexInt:
2034 Result = Val.getComplexIntReal().getBoolValue() ||
2035 Val.getComplexIntImag().getBoolValue();
2036 return true;
2037 case APValue::ComplexFloat:
2038 Result = !Val.getComplexFloatReal().isZero() ||
2039 !Val.getComplexFloatImag().isZero();
2040 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002041 case APValue::LValue:
2042 return EvalPointerValueAsBool(Val, Result);
2043 case APValue::MemberPointer:
2044 Result = Val.getMemberPointerDecl();
2045 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002046 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002047 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002048 case APValue::Struct:
2049 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002050 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002051 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002052 }
2053
Richard Smith11562c52011-10-28 17:51:58 +00002054 llvm_unreachable("unknown APValue kind");
2055}
2056
2057static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2058 EvalInfo &Info) {
2059 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002060 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002061 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002062 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002063 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002064}
2065
Richard Smith357362d2011-12-13 06:39:58 +00002066template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002067static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002068 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002069 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002070 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002071 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002072}
2073
2074static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2075 QualType SrcType, const APFloat &Value,
2076 QualType DestType, APSInt &Result) {
2077 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002078 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002079 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002080
Richard Smith357362d2011-12-13 06:39:58 +00002081 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002082 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002083 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2084 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002085 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002086 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002087}
2088
Richard Smith357362d2011-12-13 06:39:58 +00002089static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2090 QualType SrcType, QualType DestType,
2091 APFloat &Result) {
2092 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002093 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002094 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2095 APFloat::rmNearestTiesToEven, &ignored)
2096 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002097 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002098 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002099}
2100
Richard Smith911e1422012-01-30 22:27:01 +00002101static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2102 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002103 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002104 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002105 // Figure out if this is a truncate, extend or noop cast.
2106 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002107 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002108 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002109 if (DestType->isBooleanType())
2110 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002111 return Result;
2112}
2113
Richard Smith357362d2011-12-13 06:39:58 +00002114static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2115 QualType SrcType, const APSInt &Value,
2116 QualType DestType, APFloat &Result) {
2117 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2118 if (Result.convertFromAPInt(Value, Value.isSigned(),
2119 APFloat::rmNearestTiesToEven)
2120 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002121 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002122 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002123}
2124
Richard Smith49ca8aa2013-08-06 07:09:20 +00002125static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2126 APValue &Value, const FieldDecl *FD) {
2127 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2128
2129 if (!Value.isInt()) {
2130 // Trying to store a pointer-cast-to-integer into a bitfield.
2131 // FIXME: In this case, we should provide the diagnostic for casting
2132 // a pointer to an integer.
2133 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002134 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002135 return false;
2136 }
2137
2138 APSInt &Int = Value.getInt();
2139 unsigned OldBitWidth = Int.getBitWidth();
2140 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2141 if (NewBitWidth < OldBitWidth)
2142 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2143 return true;
2144}
2145
Eli Friedman803acb32011-12-22 03:51:45 +00002146static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2147 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002148 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002149 if (!Evaluate(SVal, Info, E))
2150 return false;
2151 if (SVal.isInt()) {
2152 Res = SVal.getInt();
2153 return true;
2154 }
2155 if (SVal.isFloat()) {
2156 Res = SVal.getFloat().bitcastToAPInt();
2157 return true;
2158 }
2159 if (SVal.isVector()) {
2160 QualType VecTy = E->getType();
2161 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2162 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2163 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2164 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2165 Res = llvm::APInt::getNullValue(VecSize);
2166 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2167 APValue &Elt = SVal.getVectorElt(i);
2168 llvm::APInt EltAsInt;
2169 if (Elt.isInt()) {
2170 EltAsInt = Elt.getInt();
2171 } else if (Elt.isFloat()) {
2172 EltAsInt = Elt.getFloat().bitcastToAPInt();
2173 } else {
2174 // Don't try to handle vectors of anything other than int or float
2175 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002176 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002177 return false;
2178 }
2179 unsigned BaseEltSize = EltAsInt.getBitWidth();
2180 if (BigEndian)
2181 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2182 else
2183 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2184 }
2185 return true;
2186 }
2187 // Give up if the input isn't an int, float, or vector. For example, we
2188 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002189 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002190 return false;
2191}
2192
Richard Smith43e77732013-05-07 04:50:00 +00002193/// Perform the given integer operation, which is known to need at most BitWidth
2194/// bits, and check for overflow in the original type (if that type was not an
2195/// unsigned type).
2196template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002197static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2198 const APSInt &LHS, const APSInt &RHS,
2199 unsigned BitWidth, Operation Op,
2200 APSInt &Result) {
2201 if (LHS.isUnsigned()) {
2202 Result = Op(LHS, RHS);
2203 return true;
2204 }
Richard Smith43e77732013-05-07 04:50:00 +00002205
2206 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002207 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002208 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002209 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002210 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002211 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002212 << Result.toString(10) << E->getType();
2213 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002214 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002215 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002216 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002217}
2218
2219/// Perform the given binary integer operation.
2220static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2221 BinaryOperatorKind Opcode, APSInt RHS,
2222 APSInt &Result) {
2223 switch (Opcode) {
2224 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002225 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002226 return false;
2227 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002228 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2229 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002230 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002231 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2232 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002233 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002234 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2235 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002236 case BO_And: Result = LHS & RHS; return true;
2237 case BO_Xor: Result = LHS ^ RHS; return true;
2238 case BO_Or: Result = LHS | RHS; return true;
2239 case BO_Div:
2240 case BO_Rem:
2241 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002242 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002243 return false;
2244 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002245 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2246 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2247 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002248 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2249 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002250 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2251 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002252 return true;
2253 case BO_Shl: {
2254 if (Info.getLangOpts().OpenCL)
2255 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2256 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2257 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2258 RHS.isUnsigned());
2259 else if (RHS.isSigned() && RHS.isNegative()) {
2260 // During constant-folding, a negative shift is an opposite shift. Such
2261 // a shift is not a constant expression.
2262 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2263 RHS = -RHS;
2264 goto shift_right;
2265 }
2266 shift_left:
2267 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2268 // the shifted type.
2269 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2270 if (SA != RHS) {
2271 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2272 << RHS << E->getType() << LHS.getBitWidth();
2273 } else if (LHS.isSigned()) {
2274 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2275 // operand, and must not overflow the corresponding unsigned type.
2276 if (LHS.isNegative())
2277 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2278 else if (LHS.countLeadingZeros() < SA)
2279 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2280 }
2281 Result = LHS << SA;
2282 return true;
2283 }
2284 case BO_Shr: {
2285 if (Info.getLangOpts().OpenCL)
2286 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2287 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2288 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2289 RHS.isUnsigned());
2290 else if (RHS.isSigned() && RHS.isNegative()) {
2291 // During constant-folding, a negative shift is an opposite shift. Such a
2292 // shift is not a constant expression.
2293 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2294 RHS = -RHS;
2295 goto shift_left;
2296 }
2297 shift_right:
2298 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2299 // shifted type.
2300 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2301 if (SA != RHS)
2302 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2303 << RHS << E->getType() << LHS.getBitWidth();
2304 Result = LHS >> SA;
2305 return true;
2306 }
2307
2308 case BO_LT: Result = LHS < RHS; return true;
2309 case BO_GT: Result = LHS > RHS; return true;
2310 case BO_LE: Result = LHS <= RHS; return true;
2311 case BO_GE: Result = LHS >= RHS; return true;
2312 case BO_EQ: Result = LHS == RHS; return true;
2313 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002314 case BO_Cmp:
2315 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002316 }
2317}
2318
Richard Smith861b5b52013-05-07 23:34:45 +00002319/// Perform the given binary floating-point operation, in-place, on LHS.
2320static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2321 APFloat &LHS, BinaryOperatorKind Opcode,
2322 const APFloat &RHS) {
2323 switch (Opcode) {
2324 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002325 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002326 return false;
2327 case BO_Mul:
2328 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2329 break;
2330 case BO_Add:
2331 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2332 break;
2333 case BO_Sub:
2334 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2335 break;
2336 case BO_Div:
2337 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2338 break;
2339 }
2340
Richard Smith0c6124b2015-12-03 01:36:22 +00002341 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002342 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002343 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002344 }
Richard Smith861b5b52013-05-07 23:34:45 +00002345 return true;
2346}
2347
Richard Smitha8105bc2012-01-06 16:39:00 +00002348/// Cast an lvalue referring to a base subobject to a derived class, by
2349/// truncating the lvalue's path to the given length.
2350static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2351 const RecordDecl *TruncatedType,
2352 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002353 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002354
2355 // Check we actually point to a derived class object.
2356 if (TruncatedElements == D.Entries.size())
2357 return true;
2358 assert(TruncatedElements >= D.MostDerivedPathLength &&
2359 "not casting to a derived class");
2360 if (!Result.checkSubobject(Info, E, CSK_Derived))
2361 return false;
2362
2363 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002364 const RecordDecl *RD = TruncatedType;
2365 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002366 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2368 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002369 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002370 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002371 else
Richard Smithd62306a2011-11-10 06:34:14 +00002372 Result.Offset -= Layout.getBaseClassOffset(Base);
2373 RD = Base;
2374 }
Richard Smith027bf112011-11-17 22:56:20 +00002375 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002376 return true;
2377}
2378
John McCalld7bca762012-05-01 00:38:49 +00002379static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002380 const CXXRecordDecl *Derived,
2381 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002382 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002383 if (!RL) {
2384 if (Derived->isInvalidDecl()) return false;
2385 RL = &Info.Ctx.getASTRecordLayout(Derived);
2386 }
2387
Richard Smithd62306a2011-11-10 06:34:14 +00002388 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002389 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002390 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002391}
2392
Richard Smitha8105bc2012-01-06 16:39:00 +00002393static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002394 const CXXRecordDecl *DerivedDecl,
2395 const CXXBaseSpecifier *Base) {
2396 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2397
John McCalld7bca762012-05-01 00:38:49 +00002398 if (!Base->isVirtual())
2399 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002400
Richard Smitha8105bc2012-01-06 16:39:00 +00002401 SubobjectDesignator &D = Obj.Designator;
2402 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002403 return false;
2404
Richard Smitha8105bc2012-01-06 16:39:00 +00002405 // Extract most-derived object and corresponding type.
2406 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2407 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2408 return false;
2409
2410 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002411 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002412 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2413 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002414 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002415 return true;
2416}
2417
Richard Smith84401042013-06-03 05:03:02 +00002418static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2419 QualType Type, LValue &Result) {
2420 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2421 PathE = E->path_end();
2422 PathI != PathE; ++PathI) {
2423 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2424 *PathI))
2425 return false;
2426 Type = (*PathI)->getType();
2427 }
2428 return true;
2429}
2430
Richard Smithd62306a2011-11-10 06:34:14 +00002431/// Update LVal to refer to the given field, which must be a member of the type
2432/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002433static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002434 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002435 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002436 if (!RL) {
2437 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002438 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002439 }
Richard Smithd62306a2011-11-10 06:34:14 +00002440
2441 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002442 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002444 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002445}
2446
Richard Smith1b78b3d2012-01-25 22:15:11 +00002447/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002448static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002449 LValue &LVal,
2450 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002451 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002452 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002453 return false;
2454 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002455}
2456
Richard Smithd62306a2011-11-10 06:34:14 +00002457/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002458static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2459 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002460 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2461 // extension.
2462 if (Type->isVoidType() || Type->isFunctionType()) {
2463 Size = CharUnits::One();
2464 return true;
2465 }
2466
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002467 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002468 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002469 return false;
2470 }
2471
Richard Smithd62306a2011-11-10 06:34:14 +00002472 if (!Type->isConstantSizeType()) {
2473 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002474 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002475 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002476 return false;
2477 }
2478
2479 Size = Info.Ctx.getTypeSizeInChars(Type);
2480 return true;
2481}
2482
2483/// Update a pointer value to model pointer arithmetic.
2484/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002485/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002486/// \param LVal - The pointer value to be updated.
2487/// \param EltTy - The pointee type represented by LVal.
2488/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002489static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2490 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002491 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002492 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002493 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002494 return false;
2495
Yaxun Liu402804b2016-12-15 08:09:08 +00002496 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002497 return true;
2498}
2499
Richard Smithd6cc1982017-01-31 02:23:02 +00002500static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2501 LValue &LVal, QualType EltTy,
2502 int64_t Adjustment) {
2503 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2504 APSInt::get(Adjustment));
2505}
2506
Richard Smith66c96992012-02-18 22:04:06 +00002507/// Update an lvalue to refer to a component of a complex number.
2508/// \param Info - Information about the ongoing evaluation.
2509/// \param LVal - The lvalue to be updated.
2510/// \param EltTy - The complex number's component type.
2511/// \param Imag - False for the real component, true for the imaginary.
2512static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2513 LValue &LVal, QualType EltTy,
2514 bool Imag) {
2515 if (Imag) {
2516 CharUnits SizeOfComponent;
2517 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2518 return false;
2519 LVal.Offset += SizeOfComponent;
2520 }
2521 LVal.addComplex(Info, E, EltTy, Imag);
2522 return true;
2523}
2524
Faisal Vali051e3a22017-02-16 04:12:21 +00002525static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2526 QualType Type, const LValue &LVal,
2527 APValue &RVal);
2528
Richard Smith27908702011-10-24 17:54:18 +00002529/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002530///
2531/// \param Info Information about the ongoing evaluation.
2532/// \param E An expression to be used when printing diagnostics.
2533/// \param VD The variable whose initializer should be obtained.
2534/// \param Frame The frame in which the variable was created. Must be null
2535/// if this variable is not local to the evaluation.
2536/// \param Result Filled in with a pointer to the value of the variable.
2537static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2538 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002539 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002540
Richard Smith254a73d2011-10-28 22:34:42 +00002541 // If this is a parameter to an active constexpr function call, perform
2542 // argument substitution.
2543 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002544 // Assume arguments of a potential constant expression are unknown
2545 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002546 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002547 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002548 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002549 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002550 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002551 }
Richard Smith3229b742013-05-05 21:17:10 +00002552 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002553 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002554 }
Richard Smith27908702011-10-24 17:54:18 +00002555
Richard Smithd9f663b2013-04-22 15:31:51 +00002556 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002557 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002558 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2559 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002560 if (!Result) {
2561 // Assume variables referenced within a lambda's call operator that were
2562 // not declared within the call operator are captures and during checking
2563 // of a potential constant expression, assume they are unknown constant
2564 // expressions.
2565 assert(isLambdaCallOperator(Frame->Callee) &&
2566 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2567 "missing value for local variable");
2568 if (Info.checkingPotentialConstantExpression())
2569 return false;
2570 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002571 Info.FFDiag(E->getBeginLoc(),
2572 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002573 << "captures not currently allowed";
2574 return false;
2575 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002576 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002577 }
2578
Richard Smithd0b4dd62011-12-19 06:19:21 +00002579 // Dig out the initializer, and use the declaration which it's attached to.
2580 const Expr *Init = VD->getAnyInitializer(VD);
2581 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002582 // If we're checking a potential constant expression, the variable could be
2583 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002584 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002586 return false;
2587 }
2588
Richard Smithd62306a2011-11-10 06:34:14 +00002589 // If we're currently evaluating the initializer of this declaration, use that
2590 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002591 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002592 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002593 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002594 }
2595
Richard Smithcecf1842011-11-01 21:06:14 +00002596 // Never evaluate the initializer of a weak variable. We can't be sure that
2597 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002598 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002599 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002600 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002601 }
Richard Smithcecf1842011-11-01 21:06:14 +00002602
Richard Smithd0b4dd62011-12-19 06:19:21 +00002603 // Check that we can fold the initializer. In C++, we will have already done
2604 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002605 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002606 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002607 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002608 Notes.size() + 1) << VD;
2609 Info.Note(VD->getLocation(), diag::note_declared_at);
2610 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002611 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002612 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002613 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002614 Notes.size() + 1) << VD;
2615 Info.Note(VD->getLocation(), diag::note_declared_at);
2616 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002617 }
Richard Smith27908702011-10-24 17:54:18 +00002618
Richard Smith3229b742013-05-05 21:17:10 +00002619 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002620 return true;
Richard Smith27908702011-10-24 17:54:18 +00002621}
2622
Richard Smith11562c52011-10-28 17:51:58 +00002623static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002624 Qualifiers Quals = T.getQualifiers();
2625 return Quals.hasConst() && !Quals.hasVolatile();
2626}
2627
Richard Smithe97cbd72011-11-11 04:05:33 +00002628/// Get the base index of the given base class within an APValue representing
2629/// the given derived class.
2630static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2631 const CXXRecordDecl *Base) {
2632 Base = Base->getCanonicalDecl();
2633 unsigned Index = 0;
2634 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2635 E = Derived->bases_end(); I != E; ++I, ++Index) {
2636 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2637 return Index;
2638 }
2639
2640 llvm_unreachable("base class missing from derived class's bases list");
2641}
2642
Richard Smith3da88fa2013-04-26 14:36:30 +00002643/// Extract the value of a character from a string literal.
2644static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2645 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002646 // FIXME: Support MakeStringConstant
2647 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2648 std::string Str;
2649 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2650 assert(Index <= Str.size() && "Index too large");
2651 return APSInt::getUnsigned(Str.c_str()[Index]);
2652 }
2653
Alexey Bataevec474782014-10-09 08:45:04 +00002654 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2655 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002656 const StringLiteral *S = cast<StringLiteral>(Lit);
2657 const ConstantArrayType *CAT =
2658 Info.Ctx.getAsConstantArrayType(S->getType());
2659 assert(CAT && "string literal isn't an array");
2660 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002661 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002662
2663 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002664 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002665 if (Index < S->getLength())
2666 Value = S->getCodeUnit(Index);
2667 return Value;
2668}
2669
Richard Smith3da88fa2013-04-26 14:36:30 +00002670// Expand a string literal into an array of characters.
2671static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2672 APValue &Result) {
2673 const StringLiteral *S = cast<StringLiteral>(Lit);
2674 const ConstantArrayType *CAT =
2675 Info.Ctx.getAsConstantArrayType(S->getType());
2676 assert(CAT && "string literal isn't an array");
2677 QualType CharType = CAT->getElementType();
2678 assert(CharType->isIntegerType() && "unexpected character type");
2679
2680 unsigned Elts = CAT->getSize().getZExtValue();
2681 Result = APValue(APValue::UninitArray(),
2682 std::min(S->getLength(), Elts), Elts);
2683 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2684 CharType->isUnsignedIntegerType());
2685 if (Result.hasArrayFiller())
2686 Result.getArrayFiller() = APValue(Value);
2687 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2688 Value = S->getCodeUnit(I);
2689 Result.getArrayInitializedElt(I) = APValue(Value);
2690 }
2691}
2692
2693// Expand an array so that it has more than Index filled elements.
2694static void expandArray(APValue &Array, unsigned Index) {
2695 unsigned Size = Array.getArraySize();
2696 assert(Index < Size);
2697
2698 // Always at least double the number of elements for which we store a value.
2699 unsigned OldElts = Array.getArrayInitializedElts();
2700 unsigned NewElts = std::max(Index+1, OldElts * 2);
2701 NewElts = std::min(Size, std::max(NewElts, 8u));
2702
2703 // Copy the data across.
2704 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2705 for (unsigned I = 0; I != OldElts; ++I)
2706 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2707 for (unsigned I = OldElts; I != NewElts; ++I)
2708 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2709 if (NewValue.hasArrayFiller())
2710 NewValue.getArrayFiller() = Array.getArrayFiller();
2711 Array.swap(NewValue);
2712}
2713
Richard Smithb01fe402014-09-16 01:24:02 +00002714/// Determine whether a type would actually be read by an lvalue-to-rvalue
2715/// conversion. If it's of class type, we may assume that the copy operation
2716/// is trivial. Note that this is never true for a union type with fields
2717/// (because the copy always "reads" the active member) and always true for
2718/// a non-class type.
2719static bool isReadByLvalueToRvalueConversion(QualType T) {
2720 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2721 if (!RD || (RD->isUnion() && !RD->field_empty()))
2722 return true;
2723 if (RD->isEmpty())
2724 return false;
2725
2726 for (auto *Field : RD->fields())
2727 if (isReadByLvalueToRvalueConversion(Field->getType()))
2728 return true;
2729
2730 for (auto &BaseSpec : RD->bases())
2731 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2732 return true;
2733
2734 return false;
2735}
2736
2737/// Diagnose an attempt to read from any unreadable field within the specified
2738/// type, which might be a class type.
2739static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2740 QualType T) {
2741 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2742 if (!RD)
2743 return false;
2744
2745 if (!RD->hasMutableFields())
2746 return false;
2747
2748 for (auto *Field : RD->fields()) {
2749 // If we're actually going to read this field in some way, then it can't
2750 // be mutable. If we're in a union, then assigning to a mutable field
2751 // (even an empty one) can change the active member, so that's not OK.
2752 // FIXME: Add core issue number for the union case.
2753 if (Field->isMutable() &&
2754 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002755 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002756 Info.Note(Field->getLocation(), diag::note_declared_at);
2757 return true;
2758 }
2759
2760 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2761 return true;
2762 }
2763
2764 for (auto &BaseSpec : RD->bases())
2765 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2766 return true;
2767
2768 // All mutable fields were empty, and thus not actually read.
2769 return false;
2770}
2771
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002772namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002773/// A handle to a complete object (an object that is not a subobject of
2774/// another object).
2775struct CompleteObject {
2776 /// The value of the complete object.
2777 APValue *Value;
2778 /// The type of the complete object.
2779 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002780 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002781
Craig Topper36250ad2014-05-12 05:36:57 +00002782 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002783 CompleteObject(APValue *Value, QualType Type,
2784 bool LifetimeStartedInEvaluation)
2785 : Value(Value), Type(Type),
2786 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002787 assert(Value && "missing value for complete object");
2788 }
2789
Aaron Ballman67347662015-02-15 22:00:28 +00002790 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002791};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002792} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002793
Richard Smith3da88fa2013-04-26 14:36:30 +00002794/// Find the designated sub-object of an rvalue.
2795template<typename SubobjectHandler>
2796typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002797findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002799 if (Sub.Invalid)
2800 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002801 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002802 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002803 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002804 Info.FFDiag(E, Sub.isOnePastTheEnd()
2805 ? diag::note_constexpr_access_past_end
2806 : diag::note_constexpr_access_unsized_array)
2807 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002808 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002809 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002810 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002811 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002812
Richard Smith3229b742013-05-05 21:17:10 +00002813 APValue *O = Obj.Value;
2814 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002815 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002816 const bool MayReadMutableMembers =
2817 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002818
Richard Smithd62306a2011-11-10 06:34:14 +00002819 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002820 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2821 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002822 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002823 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002824 return handler.failed();
2825 }
2826
Richard Smith49ca8aa2013-08-06 07:09:20 +00002827 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002828 // If we are reading an object of class type, there may still be more
2829 // things we need to check: if there are any mutable subobjects, we
2830 // cannot perform this read. (This only happens when performing a trivial
2831 // copy or assignment.)
2832 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002833 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002834 return handler.failed();
2835
Richard Smith49ca8aa2013-08-06 07:09:20 +00002836 if (!handler.found(*O, ObjType))
2837 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002838
Richard Smith49ca8aa2013-08-06 07:09:20 +00002839 // If we modified a bit-field, truncate it to the right width.
2840 if (handler.AccessKind != AK_Read &&
2841 LastField && LastField->isBitField() &&
2842 !truncateBitfieldValue(Info, E, *O, LastField))
2843 return false;
2844
2845 return true;
2846 }
2847
Craig Topper36250ad2014-05-12 05:36:57 +00002848 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002849 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002850 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002851 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002852 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002853 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002854 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002855 // Note, it should not be possible to form a pointer with a valid
2856 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002857 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002858 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002859 << handler.AccessKind;
2860 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002861 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002863 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002864
2865 ObjType = CAT->getElementType();
2866
Richard Smith14a94132012-02-17 03:35:37 +00002867 // An array object is represented as either an Array APValue or as an
2868 // LValue which refers to a string literal.
2869 if (O->isLValue()) {
2870 assert(I == N - 1 && "extracting subobject of character?");
2871 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002872 if (handler.AccessKind != AK_Read)
2873 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2874 *O);
2875 else
2876 return handler.foundString(*O, ObjType, Index);
2877 }
2878
2879 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002880 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002881 else if (handler.AccessKind != AK_Read) {
2882 expandArray(*O, Index);
2883 O = &O->getArrayInitializedElt(Index);
2884 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002885 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002886 } else if (ObjType->isAnyComplexType()) {
2887 // Next subobject is a complex number.
2888 uint64_t Index = Sub.Entries[I].ArrayIndex;
2889 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002890 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002891 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002892 << handler.AccessKind;
2893 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002894 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002895 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002896 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002897
2898 bool WasConstQualified = ObjType.isConstQualified();
2899 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2900 if (WasConstQualified)
2901 ObjType.addConst();
2902
Richard Smith66c96992012-02-18 22:04:06 +00002903 assert(I == N - 1 && "extracting subobject of scalar?");
2904 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002905 return handler.found(Index ? O->getComplexIntImag()
2906 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002907 } else {
2908 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 return handler.found(Index ? O->getComplexFloatImag()
2910 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002911 }
Richard Smithd62306a2011-11-10 06:34:14 +00002912 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002913 // In C++14 onwards, it is permitted to read a mutable member whose
2914 // lifetime began within the evaluation.
2915 // FIXME: Should we also allow this in C++11?
2916 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2917 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002918 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002919 << Field;
2920 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002921 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002922 }
2923
Richard Smithd62306a2011-11-10 06:34:14 +00002924 // Next subobject is a class, struct or union field.
2925 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2926 if (RD->isUnion()) {
2927 const FieldDecl *UnionField = O->getUnionField();
2928 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002929 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002930 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002931 << handler.AccessKind << Field << !UnionField << UnionField;
2932 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002933 }
Richard Smithd62306a2011-11-10 06:34:14 +00002934 O = &O->getUnionValue();
2935 } else
2936 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002937
2938 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002939 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002940 if (WasConstQualified && !Field->isMutable())
2941 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002942
2943 if (ObjType.isVolatileQualified()) {
2944 if (Info.getLangOpts().CPlusPlus) {
2945 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002946 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002947 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002948 Info.Note(Field->getLocation(), diag::note_declared_at);
2949 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002950 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002951 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002952 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002953 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002954
2955 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002956 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002957 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002958 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2959 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2960 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002961
2962 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002963 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002964 if (WasConstQualified)
2965 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002966 }
2967 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002968}
2969
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002970namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002971struct ExtractSubobjectHandler {
2972 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002973 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002974
2975 static const AccessKinds AccessKind = AK_Read;
2976
2977 typedef bool result_type;
2978 bool failed() { return false; }
2979 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002980 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002981 return true;
2982 }
2983 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002984 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002985 return true;
2986 }
2987 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002988 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002989 return true;
2990 }
2991 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002992 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002993 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2994 return true;
2995 }
2996};
Richard Smith3229b742013-05-05 21:17:10 +00002997} // end anonymous namespace
2998
Richard Smith3da88fa2013-04-26 14:36:30 +00002999const AccessKinds ExtractSubobjectHandler::AccessKind;
3000
3001/// Extract the designated sub-object of an rvalue.
3002static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003003 const CompleteObject &Obj,
3004 const SubobjectDesignator &Sub,
3005 APValue &Result) {
3006 ExtractSubobjectHandler Handler = { Info, Result };
3007 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003008}
3009
Richard Smith3229b742013-05-05 21:17:10 +00003010namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003011struct ModifySubobjectHandler {
3012 EvalInfo &Info;
3013 APValue &NewVal;
3014 const Expr *E;
3015
3016 typedef bool result_type;
3017 static const AccessKinds AccessKind = AK_Assign;
3018
3019 bool checkConst(QualType QT) {
3020 // Assigning to a const object has undefined behavior.
3021 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003022 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003023 return false;
3024 }
3025 return true;
3026 }
3027
3028 bool failed() { return false; }
3029 bool found(APValue &Subobj, QualType SubobjType) {
3030 if (!checkConst(SubobjType))
3031 return false;
3032 // We've been given ownership of NewVal, so just swap it in.
3033 Subobj.swap(NewVal);
3034 return true;
3035 }
3036 bool found(APSInt &Value, QualType SubobjType) {
3037 if (!checkConst(SubobjType))
3038 return false;
3039 if (!NewVal.isInt()) {
3040 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003041 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003042 return false;
3043 }
3044 Value = NewVal.getInt();
3045 return true;
3046 }
3047 bool found(APFloat &Value, QualType SubobjType) {
3048 if (!checkConst(SubobjType))
3049 return false;
3050 Value = NewVal.getFloat();
3051 return true;
3052 }
3053 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3054 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3055 }
3056};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003057} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003058
Richard Smith3229b742013-05-05 21:17:10 +00003059const AccessKinds ModifySubobjectHandler::AccessKind;
3060
Richard Smith3da88fa2013-04-26 14:36:30 +00003061/// Update the designated sub-object of an rvalue to the given value.
3062static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003063 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003064 const SubobjectDesignator &Sub,
3065 APValue &NewVal) {
3066 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003067 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003068}
3069
Richard Smith84f6dcf2012-02-02 01:16:57 +00003070/// Find the position where two subobject designators diverge, or equivalently
3071/// the length of the common initial subsequence.
3072static unsigned FindDesignatorMismatch(QualType ObjType,
3073 const SubobjectDesignator &A,
3074 const SubobjectDesignator &B,
3075 bool &WasArrayIndex) {
3076 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3077 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003078 if (!ObjType.isNull() &&
3079 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003080 // Next subobject is an array element.
3081 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3082 WasArrayIndex = true;
3083 return I;
3084 }
Richard Smith66c96992012-02-18 22:04:06 +00003085 if (ObjType->isAnyComplexType())
3086 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3087 else
3088 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003089 } else {
3090 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3091 WasArrayIndex = false;
3092 return I;
3093 }
3094 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3095 // Next subobject is a field.
3096 ObjType = FD->getType();
3097 else
3098 // Next subobject is a base class.
3099 ObjType = QualType();
3100 }
3101 }
3102 WasArrayIndex = false;
3103 return I;
3104}
3105
3106/// Determine whether the given subobject designators refer to elements of the
3107/// same array object.
3108static bool AreElementsOfSameArray(QualType ObjType,
3109 const SubobjectDesignator &A,
3110 const SubobjectDesignator &B) {
3111 if (A.Entries.size() != B.Entries.size())
3112 return false;
3113
George Burgess IVa51c4072015-10-16 01:49:01 +00003114 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003115 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3116 // A is a subobject of the array element.
3117 return false;
3118
3119 // If A (and B) designates an array element, the last entry will be the array
3120 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3121 // of length 1' case, and the entire path must match.
3122 bool WasArrayIndex;
3123 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3124 return CommonLength >= A.Entries.size() - IsArray;
3125}
3126
Richard Smith3229b742013-05-05 21:17:10 +00003127/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003128static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3129 AccessKinds AK, const LValue &LVal,
3130 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003131 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003132 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003133 return CompleteObject();
3134 }
3135
Craig Topper36250ad2014-05-12 05:36:57 +00003136 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003137 if (LVal.getLValueCallIndex()) {
3138 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003139 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003140 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003141 << AK << LVal.Base.is<const ValueDecl*>();
3142 NoteLValueLocation(Info, LVal.Base);
3143 return CompleteObject();
3144 }
Richard Smith3229b742013-05-05 21:17:10 +00003145 }
3146
3147 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3148 // is not a constant expression (even if the object is non-volatile). We also
3149 // apply this rule to C++98, in order to conform to the expected 'volatile'
3150 // semantics.
3151 if (LValType.isVolatileQualified()) {
3152 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003153 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003154 << AK << LValType;
3155 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003156 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003157 return CompleteObject();
3158 }
3159
3160 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003161 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003162 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003163 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003164
3165 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3166 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3167 // In C++11, constexpr, non-volatile variables initialized with constant
3168 // expressions are constant expressions too. Inside constexpr functions,
3169 // parameters are constant expressions even if they're non-const.
3170 // In C++1y, objects local to a constant expression (those with a Frame) are
3171 // both readable and writable inside constant expressions.
3172 // In C, such things can also be folded, although they are not ICEs.
3173 const VarDecl *VD = dyn_cast<VarDecl>(D);
3174 if (VD) {
3175 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3176 VD = VDef;
3177 }
3178 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003179 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003180 return CompleteObject();
3181 }
3182
3183 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003184 if (BaseType.isVolatileQualified()) {
3185 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003186 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003187 << AK << 1 << VD;
3188 Info.Note(VD->getLocation(), diag::note_declared_at);
3189 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003190 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003191 }
3192 return CompleteObject();
3193 }
3194
3195 // Unless we're looking at a local variable or argument in a constexpr call,
3196 // the variable we're reading must be const.
3197 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003198 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003199 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3200 // OK, we can read and modify an object if we're in the process of
3201 // evaluating its initializer, because its lifetime began in this
3202 // evaluation.
3203 } else if (AK != AK_Read) {
3204 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003205 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003206 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003207 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003208 // OK, we can read this variable.
3209 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003210 // In OpenCL if a variable is in constant address space it is a const value.
3211 if (!(BaseType.isConstQualified() ||
3212 (Info.getLangOpts().OpenCL &&
3213 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003214 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003215 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003216 Info.Note(VD->getLocation(), diag::note_declared_at);
3217 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003219 }
3220 return CompleteObject();
3221 }
3222 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3223 // We support folding of const floating-point types, in order to make
3224 // static const data members of such types (supported as an extension)
3225 // more useful.
3226 if (Info.getLangOpts().CPlusPlus11) {
3227 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3228 Info.Note(VD->getLocation(), diag::note_declared_at);
3229 } else {
3230 Info.CCEDiag(E);
3231 }
George Burgess IVb5316982016-12-27 05:33:20 +00003232 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3233 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3234 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003235 } else {
3236 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003237 if (Info.checkingPotentialConstantExpression() &&
3238 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3239 // The definition of this variable could be constexpr. We can't
3240 // access it right now, but may be able to in future.
3241 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003243 Info.Note(VD->getLocation(), diag::note_declared_at);
3244 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003245 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003246 }
3247 return CompleteObject();
3248 }
3249 }
3250
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003251 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003252 return CompleteObject();
3253 } else {
3254 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3255
3256 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003257 if (const MaterializeTemporaryExpr *MTE =
3258 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3259 assert(MTE->getStorageDuration() == SD_Static &&
3260 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003261
Richard Smithe6c01442013-06-05 00:46:14 +00003262 // Per C++1y [expr.const]p2:
3263 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3264 // - a [...] glvalue of integral or enumeration type that refers to
3265 // a non-volatile const object [...]
3266 // [...]
3267 // - a [...] glvalue of literal type that refers to a non-volatile
3268 // object whose lifetime began within the evaluation of e.
3269 //
3270 // C++11 misses the 'began within the evaluation of e' check and
3271 // instead allows all temporaries, including things like:
3272 // int &&r = 1;
3273 // int x = ++r;
3274 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003275 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003276 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3277 const ValueDecl *ED = MTE->getExtendingDecl();
3278 if (!(BaseType.isConstQualified() &&
3279 BaseType->isIntegralOrEnumerationType()) &&
3280 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003281 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003282 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3283 return CompleteObject();
3284 }
3285
3286 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3287 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003288 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003289 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003290 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003291 return CompleteObject();
3292 }
3293 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003294 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003295 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003296 }
Richard Smith3229b742013-05-05 21:17:10 +00003297
3298 // Volatile temporary objects cannot be accessed in constant expressions.
3299 if (BaseType.isVolatileQualified()) {
3300 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003301 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003302 << AK << 0;
3303 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3304 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003305 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003306 }
3307 return CompleteObject();
3308 }
3309 }
3310
Richard Smith7525ff62013-05-09 07:14:00 +00003311 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003312 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003313 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003314 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3315 LVal.getLValueCallIndex(),
3316 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003317 BaseType = Info.Ctx.getCanonicalType(BaseType);
3318 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003319 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003320 }
3321
Richard Smith9defb7d2018-02-21 03:38:30 +00003322 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003323 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003324 //
3325 // FIXME: Not all local state is mutable. Allow local constant subobjects
3326 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003327 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3328 Info.EvalStatus.HasSideEffects) ||
3329 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003330 return CompleteObject();
3331
Richard Smith9defb7d2018-02-21 03:38:30 +00003332 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003333}
3334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003335/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003336/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3337/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003338///
3339/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003340/// \param Conv - The expression for which we are performing the conversion.
3341/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003342/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3343/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003344/// \param LVal - The glvalue on which we are attempting to perform this action.
3345/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003346static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003347 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003348 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003349 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003350 return false;
3351
Richard Smith3229b742013-05-05 21:17:10 +00003352 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003353 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003354 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003355 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3356 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3357 // initializer until now for such expressions. Such an expression can't be
3358 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003359 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003360 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003361 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003362 }
Richard Smith3229b742013-05-05 21:17:10 +00003363 APValue Lit;
3364 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3365 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003366 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003367 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003368 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003369 // We represent a string literal array as an lvalue pointing at the
3370 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003371 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003372 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003373 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003374 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003375 }
Richard Smith11562c52011-10-28 17:51:58 +00003376 }
3377
Richard Smith3229b742013-05-05 21:17:10 +00003378 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3379 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003380}
3381
3382/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003383static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003384 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003385 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003386 return false;
3387
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003388 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003389 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003390 return false;
3391 }
3392
Richard Smith3229b742013-05-05 21:17:10 +00003393 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003394 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3395}
3396
3397namespace {
3398struct CompoundAssignSubobjectHandler {
3399 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003400 const Expr *E;
3401 QualType PromotedLHSType;
3402 BinaryOperatorKind Opcode;
3403 const APValue &RHS;
3404
3405 static const AccessKinds AccessKind = AK_Assign;
3406
3407 typedef bool result_type;
3408
3409 bool checkConst(QualType QT) {
3410 // Assigning to a const object has undefined behavior.
3411 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003412 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003413 return false;
3414 }
3415 return true;
3416 }
3417
3418 bool failed() { return false; }
3419 bool found(APValue &Subobj, QualType SubobjType) {
3420 switch (Subobj.getKind()) {
3421 case APValue::Int:
3422 return found(Subobj.getInt(), SubobjType);
3423 case APValue::Float:
3424 return found(Subobj.getFloat(), SubobjType);
3425 case APValue::ComplexInt:
3426 case APValue::ComplexFloat:
3427 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003428 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003429 return false;
3430 case APValue::LValue:
3431 return foundPointer(Subobj, SubobjType);
3432 default:
3433 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003434 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003435 return false;
3436 }
3437 }
3438 bool found(APSInt &Value, QualType SubobjType) {
3439 if (!checkConst(SubobjType))
3440 return false;
3441
Tan S. B.9f935e82018-12-18 07:38:06 +00003442 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003443 // We don't support compound assignment on integer-cast-to-pointer
3444 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003445 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003446 return false;
3447 }
3448
Tan S. B.9f935e82018-12-18 07:38:06 +00003449 if (RHS.isInt()) {
3450 APSInt LHS =
3451 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3452 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3453 return false;
3454 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3455 return true;
3456 } else if (RHS.isFloat()) {
3457 APFloat FValue(0.0);
3458 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3459 FValue) &&
3460 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3461 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3462 Value);
3463 }
3464
3465 Info.FFDiag(E);
3466 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003467 }
3468 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003469 return checkConst(SubobjType) &&
3470 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3471 Value) &&
3472 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3473 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003474 }
3475 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3476 if (!checkConst(SubobjType))
3477 return false;
3478
3479 QualType PointeeType;
3480 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3481 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003482
3483 if (PointeeType.isNull() || !RHS.isInt() ||
3484 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003485 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003486 return false;
3487 }
3488
Richard Smithd6cc1982017-01-31 02:23:02 +00003489 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003490 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003491 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003492
3493 LValue LVal;
3494 LVal.setFrom(Info.Ctx, Subobj);
3495 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3496 return false;
3497 LVal.moveInto(Subobj);
3498 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003499 }
3500 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3501 llvm_unreachable("shouldn't encounter string elements here");
3502 }
3503};
3504} // end anonymous namespace
3505
3506const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3507
3508/// Perform a compound assignment of LVal <op>= RVal.
3509static bool handleCompoundAssignment(
3510 EvalInfo &Info, const Expr *E,
3511 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3512 BinaryOperatorKind Opcode, const APValue &RVal) {
3513 if (LVal.Designator.Invalid)
3514 return false;
3515
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003516 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003517 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003518 return false;
3519 }
3520
3521 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3522 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3523 RVal };
3524 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3525}
3526
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003527namespace {
3528struct IncDecSubobjectHandler {
3529 EvalInfo &Info;
3530 const UnaryOperator *E;
3531 AccessKinds AccessKind;
3532 APValue *Old;
3533
Richard Smith243ef902013-05-05 23:31:59 +00003534 typedef bool result_type;
3535
3536 bool checkConst(QualType QT) {
3537 // Assigning to a const object has undefined behavior.
3538 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003539 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003540 return false;
3541 }
3542 return true;
3543 }
3544
3545 bool failed() { return false; }
3546 bool found(APValue &Subobj, QualType SubobjType) {
3547 // Stash the old value. Also clear Old, so we don't clobber it later
3548 // if we're post-incrementing a complex.
3549 if (Old) {
3550 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003551 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003552 }
3553
3554 switch (Subobj.getKind()) {
3555 case APValue::Int:
3556 return found(Subobj.getInt(), SubobjType);
3557 case APValue::Float:
3558 return found(Subobj.getFloat(), SubobjType);
3559 case APValue::ComplexInt:
3560 return found(Subobj.getComplexIntReal(),
3561 SubobjType->castAs<ComplexType>()->getElementType()
3562 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3563 case APValue::ComplexFloat:
3564 return found(Subobj.getComplexFloatReal(),
3565 SubobjType->castAs<ComplexType>()->getElementType()
3566 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3567 case APValue::LValue:
3568 return foundPointer(Subobj, SubobjType);
3569 default:
3570 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003571 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003572 return false;
3573 }
3574 }
3575 bool found(APSInt &Value, QualType SubobjType) {
3576 if (!checkConst(SubobjType))
3577 return false;
3578
3579 if (!SubobjType->isIntegerType()) {
3580 // We don't support increment / decrement on integer-cast-to-pointer
3581 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003582 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003583 return false;
3584 }
3585
3586 if (Old) *Old = APValue(Value);
3587
3588 // bool arithmetic promotes to int, and the conversion back to bool
3589 // doesn't reduce mod 2^n, so special-case it.
3590 if (SubobjType->isBooleanType()) {
3591 if (AccessKind == AK_Increment)
3592 Value = 1;
3593 else
3594 Value = !Value;
3595 return true;
3596 }
3597
3598 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003599 if (AccessKind == AK_Increment) {
3600 ++Value;
3601
3602 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3603 APSInt ActualValue(Value, /*IsUnsigned*/true);
3604 return HandleOverflow(Info, E, ActualValue, SubobjType);
3605 }
3606 } else {
3607 --Value;
3608
3609 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3610 unsigned BitWidth = Value.getBitWidth();
3611 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3612 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003613 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003614 }
3615 }
3616 return true;
3617 }
3618 bool found(APFloat &Value, QualType SubobjType) {
3619 if (!checkConst(SubobjType))
3620 return false;
3621
3622 if (Old) *Old = APValue(Value);
3623
3624 APFloat One(Value.getSemantics(), 1);
3625 if (AccessKind == AK_Increment)
3626 Value.add(One, APFloat::rmNearestTiesToEven);
3627 else
3628 Value.subtract(One, APFloat::rmNearestTiesToEven);
3629 return true;
3630 }
3631 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3632 if (!checkConst(SubobjType))
3633 return false;
3634
3635 QualType PointeeType;
3636 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3637 PointeeType = PT->getPointeeType();
3638 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003639 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003640 return false;
3641 }
3642
3643 LValue LVal;
3644 LVal.setFrom(Info.Ctx, Subobj);
3645 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3646 AccessKind == AK_Increment ? 1 : -1))
3647 return false;
3648 LVal.moveInto(Subobj);
3649 return true;
3650 }
3651 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3652 llvm_unreachable("shouldn't encounter string elements here");
3653 }
3654};
3655} // end anonymous namespace
3656
3657/// Perform an increment or decrement on LVal.
3658static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3659 QualType LValType, bool IsIncrement, APValue *Old) {
3660 if (LVal.Designator.Invalid)
3661 return false;
3662
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003663 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003664 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003665 return false;
3666 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003667
3668 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3669 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3670 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3671 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3672}
3673
Richard Smithe97cbd72011-11-11 04:05:33 +00003674/// Build an lvalue for the object argument of a member function call.
3675static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3676 LValue &This) {
3677 if (Object->getType()->isPointerType())
3678 return EvaluatePointer(Object, This, Info);
3679
3680 if (Object->isGLValue())
3681 return EvaluateLValue(Object, This, Info);
3682
Richard Smithd9f663b2013-04-22 15:31:51 +00003683 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003684 return EvaluateTemporary(Object, This, Info);
3685
Faisal Valie690b7a2016-07-02 22:34:24 +00003686 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003687 return false;
3688}
3689
3690/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3691/// lvalue referring to the result.
3692///
3693/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003694/// \param LV - An lvalue referring to the base of the member pointer.
3695/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003696/// \param IncludeMember - Specifies whether the member itself is included in
3697/// the resulting LValue subobject designator. This is not possible when
3698/// creating a bound member function.
3699/// \return The field or method declaration to which the member pointer refers,
3700/// or 0 if evaluation fails.
3701static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003702 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003703 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003704 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003705 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003706 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003707 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003708 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003709
3710 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3711 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003712 if (!MemPtr.getDecl()) {
3713 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003714 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003715 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003716 }
Richard Smith253c2a32012-01-27 01:14:48 +00003717
Richard Smith027bf112011-11-17 22:56:20 +00003718 if (MemPtr.isDerivedMember()) {
3719 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003720 // The end of the derived-to-base path for the base object must match the
3721 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003722 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003723 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003724 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003725 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003726 }
Richard Smith027bf112011-11-17 22:56:20 +00003727 unsigned PathLengthToMember =
3728 LV.Designator.Entries.size() - MemPtr.Path.size();
3729 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3730 const CXXRecordDecl *LVDecl = getAsBaseClass(
3731 LV.Designator.Entries[PathLengthToMember + I]);
3732 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003733 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003734 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003735 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003736 }
Richard Smith027bf112011-11-17 22:56:20 +00003737 }
3738
3739 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003740 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003741 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003742 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003743 } else if (!MemPtr.Path.empty()) {
3744 // Extend the LValue path with the member pointer's path.
3745 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3746 MemPtr.Path.size() + IncludeMember);
3747
3748 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003749 if (const PointerType *PT = LVType->getAs<PointerType>())
3750 LVType = PT->getPointeeType();
3751 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3752 assert(RD && "member pointer access on non-class-type expression");
3753 // The first class in the path is that of the lvalue.
3754 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3755 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003756 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003757 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003758 RD = Base;
3759 }
3760 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003761 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3762 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003763 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003764 }
3765
3766 // Add the member. Note that we cannot build bound member functions here.
3767 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003768 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003769 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003770 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003771 } else if (const IndirectFieldDecl *IFD =
3772 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003773 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003774 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003775 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003776 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003777 }
Richard Smith027bf112011-11-17 22:56:20 +00003778 }
3779
3780 return MemPtr.getDecl();
3781}
3782
Richard Smith84401042013-06-03 05:03:02 +00003783static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3784 const BinaryOperator *BO,
3785 LValue &LV,
3786 bool IncludeMember = true) {
3787 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3788
3789 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003790 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003791 MemberPtr MemPtr;
3792 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3793 }
Craig Topper36250ad2014-05-12 05:36:57 +00003794 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003795 }
3796
3797 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3798 BO->getRHS(), IncludeMember);
3799}
3800
Richard Smith027bf112011-11-17 22:56:20 +00003801/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3802/// the provided lvalue, which currently refers to the base object.
3803static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3804 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003805 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003806 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003807 return false;
3808
Richard Smitha8105bc2012-01-06 16:39:00 +00003809 QualType TargetQT = E->getType();
3810 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3811 TargetQT = PT->getPointeeType();
3812
3813 // Check this cast lands within the final derived-to-base subobject path.
3814 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003815 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003816 << D.MostDerivedType << TargetQT;
3817 return false;
3818 }
3819
Richard Smith027bf112011-11-17 22:56:20 +00003820 // Check the type of the final cast. We don't need to check the path,
3821 // since a cast can only be formed if the path is unique.
3822 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003823 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3824 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003825 if (NewEntriesSize == D.MostDerivedPathLength)
3826 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3827 else
Richard Smith027bf112011-11-17 22:56:20 +00003828 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003829 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003830 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003831 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003832 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003833 }
Richard Smith027bf112011-11-17 22:56:20 +00003834
3835 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003836 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003837}
3838
Mike Stump876387b2009-10-27 22:09:17 +00003839namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003840enum EvalStmtResult {
3841 /// Evaluation failed.
3842 ESR_Failed,
3843 /// Hit a 'return' statement.
3844 ESR_Returned,
3845 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003846 ESR_Succeeded,
3847 /// Hit a 'continue' statement.
3848 ESR_Continue,
3849 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003850 ESR_Break,
3851 /// Still scanning for 'case' or 'default' statement.
3852 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003853};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003854}
Richard Smith254a73d2011-10-28 22:34:42 +00003855
Richard Smith97fcf4b2016-08-14 23:15:52 +00003856static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3857 // We don't need to evaluate the initializer for a static local.
3858 if (!VD->hasLocalStorage())
3859 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003860
Richard Smith97fcf4b2016-08-14 23:15:52 +00003861 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003862 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003863
Richard Smith97fcf4b2016-08-14 23:15:52 +00003864 const Expr *InitE = VD->getInit();
3865 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003866 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3867 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003868 Val = APValue();
3869 return false;
3870 }
Richard Smith51f03172013-06-20 03:00:05 +00003871
Richard Smith97fcf4b2016-08-14 23:15:52 +00003872 if (InitE->isValueDependent())
3873 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003874
Richard Smith97fcf4b2016-08-14 23:15:52 +00003875 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3876 // Wipe out any partially-computed value, to allow tracking that this
3877 // evaluation failed.
3878 Val = APValue();
3879 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003880 }
3881
3882 return true;
3883}
3884
Richard Smith97fcf4b2016-08-14 23:15:52 +00003885static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3886 bool OK = true;
3887
3888 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3889 OK &= EvaluateVarDecl(Info, VD);
3890
3891 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3892 for (auto *BD : DD->bindings())
3893 if (auto *VD = BD->getHoldingVar())
3894 OK &= EvaluateDecl(Info, VD);
3895
3896 return OK;
3897}
3898
3899
Richard Smith4e18ca52013-05-06 05:56:11 +00003900/// Evaluate a condition (either a variable declaration or an expression).
3901static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3902 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003903 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003904 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3905 return false;
3906 return EvaluateAsBooleanCondition(Cond, Result, Info);
3907}
3908
Richard Smith89210072016-04-04 23:29:43 +00003909namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003910/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003911/// statement should be stored.
3912struct StmtResult {
3913 /// The APValue that should be filled in with the returned value.
3914 APValue &Value;
3915 /// The location containing the result, if any (used to support RVO).
3916 const LValue *Slot;
3917};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003918
3919struct TempVersionRAII {
3920 CallStackFrame &Frame;
3921
3922 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3923 Frame.pushTempVersion();
3924 }
3925
3926 ~TempVersionRAII() {
3927 Frame.popTempVersion();
3928 }
3929};
3930
Richard Smith89210072016-04-04 23:29:43 +00003931}
Richard Smith52a980a2015-08-28 02:43:42 +00003932
3933static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003934 const Stmt *S,
3935 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003936
3937/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003938static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003939 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003940 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003941 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003942 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003943 case ESR_Break:
3944 return ESR_Succeeded;
3945 case ESR_Succeeded:
3946 case ESR_Continue:
3947 return ESR_Continue;
3948 case ESR_Failed:
3949 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003950 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003951 return ESR;
3952 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003953 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003954}
3955
Richard Smith496ddcf2013-05-12 17:32:42 +00003956/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003957static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003958 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003959 BlockScopeRAII Scope(Info);
3960
Richard Smith496ddcf2013-05-12 17:32:42 +00003961 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003962 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003963 {
3964 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003965 if (const Stmt *Init = SS->getInit()) {
3966 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3967 if (ESR != ESR_Succeeded)
3968 return ESR;
3969 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003970 if (SS->getConditionVariable() &&
3971 !EvaluateDecl(Info, SS->getConditionVariable()))
3972 return ESR_Failed;
3973 if (!EvaluateInteger(SS->getCond(), Value, Info))
3974 return ESR_Failed;
3975 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003976
3977 // Find the switch case corresponding to the value of the condition.
3978 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003979 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003980 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3981 SC = SC->getNextSwitchCase()) {
3982 if (isa<DefaultStmt>(SC)) {
3983 Found = SC;
3984 continue;
3985 }
3986
3987 const CaseStmt *CS = cast<CaseStmt>(SC);
3988 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3989 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3990 : LHS;
3991 if (LHS <= Value && Value <= RHS) {
3992 Found = SC;
3993 break;
3994 }
3995 }
3996
3997 if (!Found)
3998 return ESR_Succeeded;
3999
4000 // Search the switch body for the switch case and evaluate it from there.
4001 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4002 case ESR_Break:
4003 return ESR_Succeeded;
4004 case ESR_Succeeded:
4005 case ESR_Continue:
4006 case ESR_Failed:
4007 case ESR_Returned:
4008 return ESR;
4009 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004010 // This can only happen if the switch case is nested within a statement
4011 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004012 Info.FFDiag(Found->getBeginLoc(),
4013 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004014 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004015 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004016 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004017}
4018
Richard Smith254a73d2011-10-28 22:34:42 +00004019// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004020static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004021 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004022 if (!Info.nextStep(S))
4023 return ESR_Failed;
4024
Richard Smith496ddcf2013-05-12 17:32:42 +00004025 // If we're hunting down a 'case' or 'default' label, recurse through
4026 // substatements until we hit the label.
4027 if (Case) {
4028 // FIXME: We don't start the lifetime of objects whose initialization we
4029 // jump over. However, such objects must be of class type with a trivial
4030 // default constructor that initialize all subobjects, so must be empty,
4031 // so this almost never matters.
4032 switch (S->getStmtClass()) {
4033 case Stmt::CompoundStmtClass:
4034 // FIXME: Precompute which substatement of a compound statement we
4035 // would jump to, and go straight there rather than performing a
4036 // linear scan each time.
4037 case Stmt::LabelStmtClass:
4038 case Stmt::AttributedStmtClass:
4039 case Stmt::DoStmtClass:
4040 break;
4041
4042 case Stmt::CaseStmtClass:
4043 case Stmt::DefaultStmtClass:
4044 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004045 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004046 break;
4047
4048 case Stmt::IfStmtClass: {
4049 // FIXME: Precompute which side of an 'if' we would jump to, and go
4050 // straight there rather than scanning both sides.
4051 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004052
4053 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4054 // preceded by our switch label.
4055 BlockScopeRAII Scope(Info);
4056
Richard Smith496ddcf2013-05-12 17:32:42 +00004057 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4058 if (ESR != ESR_CaseNotFound || !IS->getElse())
4059 return ESR;
4060 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4061 }
4062
4063 case Stmt::WhileStmtClass: {
4064 EvalStmtResult ESR =
4065 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4066 if (ESR != ESR_Continue)
4067 return ESR;
4068 break;
4069 }
4070
4071 case Stmt::ForStmtClass: {
4072 const ForStmt *FS = cast<ForStmt>(S);
4073 EvalStmtResult ESR =
4074 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4075 if (ESR != ESR_Continue)
4076 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004077 if (FS->getInc()) {
4078 FullExpressionRAII IncScope(Info);
4079 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4080 return ESR_Failed;
4081 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004082 break;
4083 }
4084
4085 case Stmt::DeclStmtClass:
4086 // FIXME: If the variable has initialization that can't be jumped over,
4087 // bail out of any immediately-surrounding compound-statement too.
4088 default:
4089 return ESR_CaseNotFound;
4090 }
4091 }
4092
Richard Smith254a73d2011-10-28 22:34:42 +00004093 switch (S->getStmtClass()) {
4094 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004095 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004096 // Don't bother evaluating beyond an expression-statement which couldn't
4097 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004098 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004099 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004100 return ESR_Failed;
4101 return ESR_Succeeded;
4102 }
4103
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004104 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004105 return ESR_Failed;
4106
4107 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004108 return ESR_Succeeded;
4109
Richard Smithd9f663b2013-04-22 15:31:51 +00004110 case Stmt::DeclStmtClass: {
4111 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004112 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004113 // Each declaration initialization is its own full-expression.
4114 // FIXME: This isn't quite right; if we're performing aggregate
4115 // initialization, each braced subexpression is its own full-expression.
4116 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004117 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004118 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004119 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004120 return ESR_Succeeded;
4121 }
4122
Richard Smith357362d2011-12-13 06:39:58 +00004123 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004124 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004125 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004126 if (RetExpr &&
4127 !(Result.Slot
4128 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4129 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004130 return ESR_Failed;
4131 return ESR_Returned;
4132 }
Richard Smith254a73d2011-10-28 22:34:42 +00004133
4134 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004135 BlockScopeRAII Scope(Info);
4136
Richard Smith254a73d2011-10-28 22:34:42 +00004137 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004138 for (const auto *BI : CS->body()) {
4139 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004140 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004141 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004142 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004143 return ESR;
4144 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004145 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004146 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004147
4148 case Stmt::IfStmtClass: {
4149 const IfStmt *IS = cast<IfStmt>(S);
4150
4151 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004152 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004153 if (const Stmt *Init = IS->getInit()) {
4154 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4155 if (ESR != ESR_Succeeded)
4156 return ESR;
4157 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004158 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004159 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004160 return ESR_Failed;
4161
4162 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4163 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4164 if (ESR != ESR_Succeeded)
4165 return ESR;
4166 }
4167 return ESR_Succeeded;
4168 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004169
4170 case Stmt::WhileStmtClass: {
4171 const WhileStmt *WS = cast<WhileStmt>(S);
4172 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004173 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004174 bool Continue;
4175 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4176 Continue))
4177 return ESR_Failed;
4178 if (!Continue)
4179 break;
4180
4181 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4182 if (ESR != ESR_Continue)
4183 return ESR;
4184 }
4185 return ESR_Succeeded;
4186 }
4187
4188 case Stmt::DoStmtClass: {
4189 const DoStmt *DS = cast<DoStmt>(S);
4190 bool Continue;
4191 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004192 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004193 if (ESR != ESR_Continue)
4194 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004195 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004196
Richard Smith08d6a2c2013-07-24 07:11:57 +00004197 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004198 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4199 return ESR_Failed;
4200 } while (Continue);
4201 return ESR_Succeeded;
4202 }
4203
4204 case Stmt::ForStmtClass: {
4205 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004206 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004207 if (FS->getInit()) {
4208 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4209 if (ESR != ESR_Succeeded)
4210 return ESR;
4211 }
4212 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004213 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004214 bool Continue = true;
4215 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4216 FS->getCond(), Continue))
4217 return ESR_Failed;
4218 if (!Continue)
4219 break;
4220
4221 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4222 if (ESR != ESR_Continue)
4223 return ESR;
4224
Richard Smith08d6a2c2013-07-24 07:11:57 +00004225 if (FS->getInc()) {
4226 FullExpressionRAII IncScope(Info);
4227 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4228 return ESR_Failed;
4229 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004230 }
4231 return ESR_Succeeded;
4232 }
4233
Richard Smith896e0d72013-05-06 06:51:17 +00004234 case Stmt::CXXForRangeStmtClass: {
4235 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004236 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004237
Richard Smith8baa5002018-09-28 18:44:09 +00004238 // Evaluate the init-statement if present.
4239 if (FS->getInit()) {
4240 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4241 if (ESR != ESR_Succeeded)
4242 return ESR;
4243 }
4244
Richard Smith896e0d72013-05-06 06:51:17 +00004245 // Initialize the __range variable.
4246 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4247 if (ESR != ESR_Succeeded)
4248 return ESR;
4249
4250 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004251 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4252 if (ESR != ESR_Succeeded)
4253 return ESR;
4254 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004255 if (ESR != ESR_Succeeded)
4256 return ESR;
4257
4258 while (true) {
4259 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004260 {
4261 bool Continue = true;
4262 FullExpressionRAII CondExpr(Info);
4263 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4264 return ESR_Failed;
4265 if (!Continue)
4266 break;
4267 }
Richard Smith896e0d72013-05-06 06:51:17 +00004268
4269 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004270 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004271 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4272 if (ESR != ESR_Succeeded)
4273 return ESR;
4274
4275 // Loop body.
4276 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4277 if (ESR != ESR_Continue)
4278 return ESR;
4279
4280 // Increment: ++__begin
4281 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4282 return ESR_Failed;
4283 }
4284
4285 return ESR_Succeeded;
4286 }
4287
Richard Smith496ddcf2013-05-12 17:32:42 +00004288 case Stmt::SwitchStmtClass:
4289 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4290
Richard Smith4e18ca52013-05-06 05:56:11 +00004291 case Stmt::ContinueStmtClass:
4292 return ESR_Continue;
4293
4294 case Stmt::BreakStmtClass:
4295 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004296
4297 case Stmt::LabelStmtClass:
4298 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4299
4300 case Stmt::AttributedStmtClass:
4301 // As a general principle, C++11 attributes can be ignored without
4302 // any semantic impact.
4303 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4304 Case);
4305
4306 case Stmt::CaseStmtClass:
4307 case Stmt::DefaultStmtClass:
4308 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004309 case Stmt::CXXTryStmtClass:
4310 // Evaluate try blocks by evaluating all sub statements.
4311 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004312 }
4313}
4314
Richard Smithcc36f692011-12-22 02:22:31 +00004315/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4316/// default constructor. If so, we'll fold it whether or not it's marked as
4317/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4318/// so we need special handling.
4319static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004320 const CXXConstructorDecl *CD,
4321 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004322 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4323 return false;
4324
Richard Smith66e05fe2012-01-18 05:21:49 +00004325 // Value-initialization does not call a trivial default constructor, so such a
4326 // call is a core constant expression whether or not the constructor is
4327 // constexpr.
4328 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004329 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004330 // FIXME: If DiagDecl is an implicitly-declared special member function,
4331 // we should be much more explicit about why it's not constexpr.
4332 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4333 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4334 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004335 } else {
4336 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4337 }
4338 }
4339 return true;
4340}
4341
Richard Smith357362d2011-12-13 06:39:58 +00004342/// CheckConstexprFunction - Check that a function can be called in a constant
4343/// expression.
4344static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4345 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004346 const FunctionDecl *Definition,
4347 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004348 // Potential constant expressions can contain calls to declared, but not yet
4349 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004350 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004351 Declaration->isConstexpr())
4352 return false;
4353
James Y Knightc7d3e602018-10-05 17:49:48 +00004354 // Bail out if the function declaration itself is invalid. We will
4355 // have produced a relevant diagnostic while parsing it, so just
4356 // note the problematic sub-expression.
4357 if (Declaration->isInvalidDecl()) {
4358 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004359 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004360 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004361
Richard Smith357362d2011-12-13 06:39:58 +00004362 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004363 if (Definition && Definition->isConstexpr() &&
4364 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004365 return true;
4366
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004367 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004368 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004369
Richard Smith5179eb72016-06-28 19:03:57 +00004370 // If this function is not constexpr because it is an inherited
4371 // non-constexpr constructor, diagnose that directly.
4372 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4373 if (CD && CD->isInheritingConstructor()) {
4374 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004375 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004376 DiagDecl = CD = Inherited;
4377 }
4378
4379 // FIXME: If DiagDecl is an implicitly-declared special member function
4380 // or an inheriting constructor, we should be much more explicit about why
4381 // it's not constexpr.
4382 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004383 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004384 << CD->getInheritedConstructor().getConstructor()->getParent();
4385 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004386 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004387 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004388 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4389 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004390 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004391 }
4392 return false;
4393}
4394
Richard Smithbe6dd812014-11-19 21:27:17 +00004395/// Determine if a class has any fields that might need to be copied by a
4396/// trivial copy or move operation.
4397static bool hasFields(const CXXRecordDecl *RD) {
4398 if (!RD || RD->isEmpty())
4399 return false;
4400 for (auto *FD : RD->fields()) {
4401 if (FD->isUnnamedBitfield())
4402 continue;
4403 return true;
4404 }
4405 for (auto &Base : RD->bases())
4406 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4407 return true;
4408 return false;
4409}
4410
Richard Smithd62306a2011-11-10 06:34:14 +00004411namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004412typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004413}
4414
4415/// EvaluateArgs - Evaluate the arguments to a function call.
4416static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4417 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004418 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004419 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004420 I != E; ++I) {
4421 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4422 // If we're checking for a potential constant expression, evaluate all
4423 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004424 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004425 return false;
4426 Success = false;
4427 }
4428 }
4429 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004430}
4431
Richard Smith254a73d2011-10-28 22:34:42 +00004432/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004433static bool HandleFunctionCall(SourceLocation CallLoc,
4434 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004435 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004436 EvalInfo &Info, APValue &Result,
4437 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004438 ArgVector ArgValues(Args.size());
4439 if (!EvaluateArgs(Args, ArgValues, Info))
4440 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004441
Richard Smith253c2a32012-01-27 01:14:48 +00004442 if (!Info.CheckCallLimit(CallLoc))
4443 return false;
4444
4445 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004446
4447 // For a trivial copy or move assignment, perform an APValue copy. This is
4448 // essential for unions, where the operations performed by the assignment
4449 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004450 //
4451 // Skip this for non-union classes with no fields; in that case, the defaulted
4452 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004453 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004454 if (MD && MD->isDefaulted() &&
4455 (MD->getParent()->isUnion() ||
4456 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004457 assert(This &&
4458 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4459 LValue RHS;
4460 RHS.setFrom(Info.Ctx, ArgValues[0]);
4461 APValue RHSValue;
4462 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4463 RHS, RHSValue))
4464 return false;
4465 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4466 RHSValue))
4467 return false;
4468 This->moveInto(Result);
4469 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004470 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004471 // We're in a lambda; determine the lambda capture field maps unless we're
4472 // just constexpr checking a lambda's call operator. constexpr checking is
4473 // done before the captures have been added to the closure object (unless
4474 // we're inferring constexpr-ness), so we don't have access to them in this
4475 // case. But since we don't need the captures to constexpr check, we can
4476 // just ignore them.
4477 if (!Info.checkingPotentialConstantExpression())
4478 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4479 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004480 }
4481
Richard Smith52a980a2015-08-28 02:43:42 +00004482 StmtResult Ret = {Result, ResultSlot};
4483 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004484 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004485 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004486 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004487 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004488 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004489 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004490}
4491
Richard Smithd62306a2011-11-10 06:34:14 +00004492/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004493static bool HandleConstructorCall(const Expr *E, const LValue &This,
4494 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004495 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004496 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004497 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004498 if (!Info.CheckCallLimit(CallLoc))
4499 return false;
4500
Richard Smith3607ffe2012-02-13 03:54:03 +00004501 const CXXRecordDecl *RD = Definition->getParent();
4502 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004503 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004504 return false;
4505 }
4506
Erik Pilkington42925492017-10-04 00:18:55 +00004507 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004508 Info, {This.getLValueBase(),
4509 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004510 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004511
Richard Smith52a980a2015-08-28 02:43:42 +00004512 // FIXME: Creating an APValue just to hold a nonexistent return value is
4513 // wasteful.
4514 APValue RetVal;
4515 StmtResult Ret = {RetVal, nullptr};
4516
Richard Smith5179eb72016-06-28 19:03:57 +00004517 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004518 if (Definition->isDelegatingConstructor()) {
4519 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004520 {
4521 FullExpressionRAII InitScope(Info);
4522 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4523 return false;
4524 }
Richard Smith52a980a2015-08-28 02:43:42 +00004525 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004526 }
4527
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004528 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004529 // essential for unions (or classes with anonymous union members), where the
4530 // operations performed by the constructor cannot be represented by
4531 // ctor-initializers.
4532 //
4533 // Skip this for empty non-union classes; we should not perform an
4534 // lvalue-to-rvalue conversion on them because their copy constructor does not
4535 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004536 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004537 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004538 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004539 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004540 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004541 return handleLValueToRValueConversion(
4542 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4543 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004544 }
4545
4546 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004547 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004548 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004549 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004550
John McCalld7bca762012-05-01 00:38:49 +00004551 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004552 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4553
Richard Smith08d6a2c2013-07-24 07:11:57 +00004554 // A scope for temporaries lifetime-extended by reference members.
4555 BlockScopeRAII LifetimeExtendedScope(Info);
4556
Richard Smith253c2a32012-01-27 01:14:48 +00004557 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004558 unsigned BasesSeen = 0;
4559#ifndef NDEBUG
4560 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4561#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004562 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004563 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004564 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004565 APValue *Value = &Result;
4566
4567 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004568 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004569 if (I->isBaseInitializer()) {
4570 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004571#ifndef NDEBUG
4572 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004573 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004574 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4575 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4576 "base class initializers not in expected order");
4577 ++BaseIt;
4578#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004579 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004580 BaseType->getAsCXXRecordDecl(), &Layout))
4581 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004582 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004583 } else if ((FD = I->getMember())) {
4584 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004585 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004586 if (RD->isUnion()) {
4587 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004588 Value = &Result.getUnionValue();
4589 } else {
4590 Value = &Result.getStructField(FD->getFieldIndex());
4591 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004592 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004593 // Walk the indirect field decl's chain to find the object to initialize,
4594 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004595 auto IndirectFieldChain = IFD->chain();
4596 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004597 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004598 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4599 // Switch the union field if it differs. This happens if we had
4600 // preceding zero-initialization, and we're now initializing a union
4601 // subobject other than the first.
4602 // FIXME: In this case, the values of the other subobjects are
4603 // specified, since zero-initialization sets all padding bits to zero.
4604 if (Value->isUninit() ||
4605 (Value->isUnion() && Value->getUnionField() != FD)) {
4606 if (CD->isUnion())
4607 *Value = APValue(FD);
4608 else
4609 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004610 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004611 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004612 // Store Subobject as its parent before updating it for the last element
4613 // in the chain.
4614 if (C == IndirectFieldChain.back())
4615 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004616 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004617 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004618 if (CD->isUnion())
4619 Value = &Value->getUnionValue();
4620 else
4621 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004622 }
Richard Smithd62306a2011-11-10 06:34:14 +00004623 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004624 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004625 }
Richard Smith253c2a32012-01-27 01:14:48 +00004626
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004627 // Need to override This for implicit field initializers as in this case
4628 // This refers to innermost anonymous struct/union containing initializer,
4629 // not to currently constructed class.
4630 const Expr *Init = I->getInit();
4631 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4632 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004633 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004634 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4635 (FD && FD->isBitField() &&
4636 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004637 // If we're checking for a potential constant expression, evaluate all
4638 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004639 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004640 return false;
4641 Success = false;
4642 }
Richard Smithd62306a2011-11-10 06:34:14 +00004643 }
4644
Richard Smithd9f663b2013-04-22 15:31:51 +00004645 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004646 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004647}
4648
Richard Smith5179eb72016-06-28 19:03:57 +00004649static bool HandleConstructorCall(const Expr *E, const LValue &This,
4650 ArrayRef<const Expr*> Args,
4651 const CXXConstructorDecl *Definition,
4652 EvalInfo &Info, APValue &Result) {
4653 ArgVector ArgValues(Args.size());
4654 if (!EvaluateArgs(Args, ArgValues, Info))
4655 return false;
4656
4657 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4658 Info, Result);
4659}
4660
Eli Friedman9a156e52008-11-12 09:44:48 +00004661//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004662// Generic Evaluation
4663//===----------------------------------------------------------------------===//
4664namespace {
4665
Aaron Ballman68af21c2014-01-03 19:26:43 +00004666template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004667class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004668 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004669private:
Richard Smith52a980a2015-08-28 02:43:42 +00004670 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004672 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004673 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004674 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004675 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004676 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004677
Richard Smith17100ba2012-02-16 02:46:34 +00004678 // Check whether a conditional operator with a non-constant condition is a
4679 // potential constant expression. If neither arm is a potential constant
4680 // expression, then the conditional operator is not either.
4681 template<typename ConditionalOperator>
4682 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004683 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004684
4685 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004686 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004687 {
Richard Smith17100ba2012-02-16 02:46:34 +00004688 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004689 StmtVisitorTy::Visit(E->getFalseExpr());
4690 if (Diag.empty())
4691 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004692 }
Richard Smith17100ba2012-02-16 02:46:34 +00004693
George Burgess IV8c892b52016-05-25 22:31:54 +00004694 {
4695 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004696 Diag.clear();
4697 StmtVisitorTy::Visit(E->getTrueExpr());
4698 if (Diag.empty())
4699 return;
4700 }
4701
4702 Error(E, diag::note_constexpr_conditional_never_const);
4703 }
4704
4705
4706 template<typename ConditionalOperator>
4707 bool HandleConditionalOperator(const ConditionalOperator *E) {
4708 bool BoolResult;
4709 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004710 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004711 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004712 return false;
4713 }
4714 if (Info.noteFailure()) {
4715 StmtVisitorTy::Visit(E->getTrueExpr());
4716 StmtVisitorTy::Visit(E->getFalseExpr());
4717 }
Richard Smith17100ba2012-02-16 02:46:34 +00004718 return false;
4719 }
4720
4721 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4722 return StmtVisitorTy::Visit(EvalExpr);
4723 }
4724
Peter Collingbournee9200682011-05-13 03:29:01 +00004725protected:
4726 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004727 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004728 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4729
Richard Smith92b1ce02011-12-12 09:28:41 +00004730 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004731 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004732 }
4733
Aaron Ballman68af21c2014-01-03 19:26:43 +00004734 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004735
4736public:
4737 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4738
4739 EvalInfo &getEvalInfo() { return Info; }
4740
Richard Smithf57d8cb2011-12-09 22:58:01 +00004741 /// Report an evaluation error. This should only be called when an error is
4742 /// first discovered. When propagating an error, just return false.
4743 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004744 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 return false;
4746 }
4747 bool Error(const Expr *E) {
4748 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4749 }
4750
Aaron Ballman68af21c2014-01-03 19:26:43 +00004751 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004752 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004753 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004755 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004756 }
4757
Bill Wendling8003edc2018-11-09 00:41:36 +00004758 bool VisitConstantExpr(const ConstantExpr *E)
4759 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004760 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004761 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004762 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004763 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004764 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004765 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004766 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004767 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004768 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004769 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004770 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004771 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004772 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4773 TempVersionRAII RAII(*Info.CurrentCall);
4774 return StmtVisitorTy::Visit(E->getExpr());
4775 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004776 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004777 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004778 // The initializer may not have been parsed yet, or might be erroneous.
4779 if (!E->getExpr())
4780 return Error(E);
4781 return StmtVisitorTy::Visit(E->getExpr());
4782 }
Richard Smith5894a912011-12-19 22:12:41 +00004783 // We cannot create any objects for which cleanups are required, so there is
4784 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004785 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004786 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004787
Aaron Ballman68af21c2014-01-03 19:26:43 +00004788 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004789 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4790 return static_cast<Derived*>(this)->VisitCastExpr(E);
4791 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004792 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004793 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4794 return static_cast<Derived*>(this)->VisitCastExpr(E);
4795 }
4796
Aaron Ballman68af21c2014-01-03 19:26:43 +00004797 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004798 switch (E->getOpcode()) {
4799 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004800 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004801
4802 case BO_Comma:
4803 VisitIgnoredValue(E->getLHS());
4804 return StmtVisitorTy::Visit(E->getRHS());
4805
4806 case BO_PtrMemD:
4807 case BO_PtrMemI: {
4808 LValue Obj;
4809 if (!HandleMemberPointerAccess(Info, E, Obj))
4810 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004811 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004812 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004813 return false;
4814 return DerivedSuccess(Result, E);
4815 }
4816 }
4817 }
4818
Aaron Ballman68af21c2014-01-03 19:26:43 +00004819 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004820 // Evaluate and cache the common expression. We treat it as a temporary,
4821 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004822 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004823 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004824 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004825
Richard Smith17100ba2012-02-16 02:46:34 +00004826 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004827 }
4828
Aaron Ballman68af21c2014-01-03 19:26:43 +00004829 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004830 bool IsBcpCall = false;
4831 // If the condition (ignoring parens) is a __builtin_constant_p call,
4832 // the result is a constant expression if it can be folded without
4833 // side-effects. This is an important GNU extension. See GCC PR38377
4834 // for discussion.
4835 if (const CallExpr *CallCE =
4836 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004837 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004838 IsBcpCall = true;
4839
4840 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4841 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004842 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004843 return false;
4844
Richard Smith6d4c6582013-11-05 22:18:15 +00004845 FoldConstant Fold(Info, IsBcpCall);
4846 if (!HandleConditionalOperator(E)) {
4847 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004848 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004849 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004850
4851 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004852 }
4853
Aaron Ballman68af21c2014-01-03 19:26:43 +00004854 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004855 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004856 return DerivedSuccess(*Value, E);
4857
4858 const Expr *Source = E->getSourceExpr();
4859 if (!Source)
4860 return Error(E);
4861 if (Source == E) { // sanity checking.
4862 assert(0 && "OpaqueValueExpr recursively refers to itself");
4863 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004864 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004865 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004866 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004867
Aaron Ballman68af21c2014-01-03 19:26:43 +00004868 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004869 APValue Result;
4870 if (!handleCallExpr(E, Result, nullptr))
4871 return false;
4872 return DerivedSuccess(Result, E);
4873 }
4874
4875 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004876 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004877 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004878 QualType CalleeType = Callee->getType();
4879
Craig Topper36250ad2014-05-12 05:36:57 +00004880 const FunctionDecl *FD = nullptr;
4881 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004882 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004883 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004884
Richard Smithe97cbd72011-11-11 04:05:33 +00004885 // Extract function decl and 'this' pointer from the callee.
4886 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004887 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4889 // Explicit bound member calls, such as x.f() or p->g();
4890 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004891 return false;
4892 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004893 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004894 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004895 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4896 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004897 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4898 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004899 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004900 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004901 return Error(Callee);
4902
4903 FD = dyn_cast<FunctionDecl>(Member);
4904 if (!FD)
4905 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004906 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004907 LValue Call;
4908 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004909 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004910
Richard Smitha8105bc2012-01-06 16:39:00 +00004911 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004912 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004913 FD = dyn_cast_or_null<FunctionDecl>(
4914 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004915 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004916 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004917 // Don't call function pointers which have been cast to some other type.
4918 // Per DR (no number yet), the caller and callee can differ in noexcept.
4919 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4920 CalleeType->getPointeeType(), FD->getType())) {
4921 return Error(E);
4922 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004923
4924 // Overloaded operator calls to member functions are represented as normal
4925 // calls with '*this' as the first argument.
4926 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4927 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004928 // FIXME: When selecting an implicit conversion for an overloaded
4929 // operator delete, we sometimes try to evaluate calls to conversion
4930 // operators without a 'this' parameter!
4931 if (Args.empty())
4932 return Error(E);
4933
Nick Lewycky13073a62017-06-12 21:15:44 +00004934 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004935 return false;
4936 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004937 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004938 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004939 // Map the static invoker for the lambda back to the call operator.
4940 // Conveniently, we don't have to slice out the 'this' argument (as is
4941 // being done for the non-static case), since a static member function
4942 // doesn't have an implicit argument passed in.
4943 const CXXRecordDecl *ClosureClass = MD->getParent();
4944 assert(
4945 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4946 "Number of captures must be zero for conversion to function-ptr");
4947
4948 const CXXMethodDecl *LambdaCallOp =
4949 ClosureClass->getLambdaCallOperator();
4950
4951 // Set 'FD', the function that will be called below, to the call
4952 // operator. If the closure object represents a generic lambda, find
4953 // the corresponding specialization of the call operator.
4954
4955 if (ClosureClass->isGenericLambda()) {
4956 assert(MD->isFunctionTemplateSpecialization() &&
4957 "A generic lambda's static-invoker function must be a "
4958 "template specialization");
4959 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4960 FunctionTemplateDecl *CallOpTemplate =
4961 LambdaCallOp->getDescribedFunctionTemplate();
4962 void *InsertPos = nullptr;
4963 FunctionDecl *CorrespondingCallOpSpecialization =
4964 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4965 assert(CorrespondingCallOpSpecialization &&
4966 "We must always have a function call operator specialization "
4967 "that corresponds to our static invoker specialization");
4968 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4969 } else
4970 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004971 }
4972
Fangrui Song6907ce22018-07-30 19:24:48 +00004973
Richard Smithe97cbd72011-11-11 04:05:33 +00004974 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004975 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004976
Richard Smith47b34932012-02-01 02:39:43 +00004977 if (This && !This->checkSubobject(Info, E, CSK_This))
4978 return false;
4979
Richard Smith3607ffe2012-02-13 03:54:03 +00004980 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4981 // calls to such functions in constant expressions.
4982 if (This && !HasQualifier &&
4983 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4984 return Error(E, diag::note_constexpr_virtual_call);
4985
Craig Topper36250ad2014-05-12 05:36:57 +00004986 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004987 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004988
Nick Lewycky13073a62017-06-12 21:15:44 +00004989 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4990 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004991 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992 return false;
4993
Richard Smith52a980a2015-08-28 02:43:42 +00004994 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004995 }
4996
Aaron Ballman68af21c2014-01-03 19:26:43 +00004997 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004998 return StmtVisitorTy::Visit(E->getInitializer());
4999 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005000 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005001 if (E->getNumInits() == 0)
5002 return DerivedZeroInitialization(E);
5003 if (E->getNumInits() == 1)
5004 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005005 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005006 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005007 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005008 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005009 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005010 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005011 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005012 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005013 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005014 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005015 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005016
Richard Smithd62306a2011-11-10 06:34:14 +00005017 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005018 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005019 assert(!E->isArrow() && "missing call to bound member function?");
5020
Richard Smith2e312c82012-03-03 22:46:17 +00005021 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005022 if (!Evaluate(Val, Info, E->getBase()))
5023 return false;
5024
5025 QualType BaseTy = E->getBase()->getType();
5026
5027 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005028 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005029 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005030 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005031 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5032
Richard Smith9defb7d2018-02-21 03:38:30 +00005033 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005034 SubobjectDesignator Designator(BaseTy);
5035 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005036
Richard Smith3229b742013-05-05 21:17:10 +00005037 APValue Result;
5038 return extractSubobject(Info, E, Obj, Designator, Result) &&
5039 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005040 }
5041
Aaron Ballman68af21c2014-01-03 19:26:43 +00005042 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005043 switch (E->getCastKind()) {
5044 default:
5045 break;
5046
Richard Smitha23ab512013-05-23 00:30:41 +00005047 case CK_AtomicToNonAtomic: {
5048 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005049 // This does not need to be done in place even for class/array types:
5050 // atomic-to-non-atomic conversion implies copying the object
5051 // representation.
5052 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005053 return false;
5054 return DerivedSuccess(AtomicVal, E);
5055 }
5056
Richard Smith11562c52011-10-28 17:51:58 +00005057 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005058 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005059 return StmtVisitorTy::Visit(E->getSubExpr());
5060
5061 case CK_LValueToRValue: {
5062 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005063 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5064 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005065 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005066 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005067 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005068 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005069 return false;
5070 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005071 }
5072 }
5073
Richard Smithf57d8cb2011-12-09 22:58:01 +00005074 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005075 }
5076
Aaron Ballman68af21c2014-01-03 19:26:43 +00005077 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005078 return VisitUnaryPostIncDec(UO);
5079 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005080 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005081 return VisitUnaryPostIncDec(UO);
5082 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005083 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005084 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005085 return Error(UO);
5086
5087 LValue LVal;
5088 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5089 return false;
5090 APValue RVal;
5091 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5092 UO->isIncrementOp(), &RVal))
5093 return false;
5094 return DerivedSuccess(RVal, UO);
5095 }
5096
Aaron Ballman68af21c2014-01-03 19:26:43 +00005097 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005098 // We will have checked the full-expressions inside the statement expression
5099 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005100 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005101 return Error(E);
5102
Richard Smith08d6a2c2013-07-24 07:11:57 +00005103 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005104 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005105 if (CS->body_empty())
5106 return true;
5107
Richard Smith51f03172013-06-20 03:00:05 +00005108 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5109 BE = CS->body_end();
5110 /**/; ++BI) {
5111 if (BI + 1 == BE) {
5112 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5113 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005114 Info.FFDiag((*BI)->getBeginLoc(),
5115 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005116 return false;
5117 }
5118 return this->Visit(FinalExpr);
5119 }
5120
5121 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005122 StmtResult Result = { ReturnValue, nullptr };
5123 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005124 if (ESR != ESR_Succeeded) {
5125 // FIXME: If the statement-expression terminated due to 'return',
5126 // 'break', or 'continue', it would be nice to propagate that to
5127 // the outer statement evaluation rather than bailing out.
5128 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005129 Info.FFDiag((*BI)->getBeginLoc(),
5130 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005131 return false;
5132 }
5133 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005134
5135 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005136 }
5137
Richard Smith4a678122011-10-24 18:44:57 +00005138 /// Visit a value which is evaluated, but whose value is ignored.
5139 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005140 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005141 }
David Majnemere9807b22016-02-26 04:23:19 +00005142
5143 /// Potentially visit a MemberExpr's base expression.
5144 void VisitIgnoredBaseExpression(const Expr *E) {
5145 // While MSVC doesn't evaluate the base expression, it does diagnose the
5146 // presence of side-effecting behavior.
5147 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5148 return;
5149 VisitIgnoredValue(E);
5150 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005151};
5152
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005153} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005154
5155//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005156// Common base class for lvalue and temporary evaluation.
5157//===----------------------------------------------------------------------===//
5158namespace {
5159template<class Derived>
5160class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005161 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005162protected:
5163 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005164 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005165 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005166 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005167
5168 bool Success(APValue::LValueBase B) {
5169 Result.set(B);
5170 return true;
5171 }
5172
George Burgess IVf9013bf2017-02-10 22:52:29 +00005173 bool evaluatePointer(const Expr *E, LValue &Result) {
5174 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5175 }
5176
Richard Smith027bf112011-11-17 22:56:20 +00005177public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005178 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5179 : ExprEvaluatorBaseTy(Info), Result(Result),
5180 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005181
Richard Smith2e312c82012-03-03 22:46:17 +00005182 bool Success(const APValue &V, const Expr *E) {
5183 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005184 return true;
5185 }
Richard Smith027bf112011-11-17 22:56:20 +00005186
Richard Smith027bf112011-11-17 22:56:20 +00005187 bool VisitMemberExpr(const MemberExpr *E) {
5188 // Handle non-static data members.
5189 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005190 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005191 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005192 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005193 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005194 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005195 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005196 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005197 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005198 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005199 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005200 BaseTy = E->getBase()->getType();
5201 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005202 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005203 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005204 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005205 Result.setInvalid(E);
5206 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005207 }
Richard Smith027bf112011-11-17 22:56:20 +00005208
Richard Smith1b78b3d2012-01-25 22:15:11 +00005209 const ValueDecl *MD = E->getMemberDecl();
5210 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5211 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5212 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5213 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005214 if (!HandleLValueMember(this->Info, E, Result, FD))
5215 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005216 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005217 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5218 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005219 } else
5220 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005221
Richard Smith1b78b3d2012-01-25 22:15:11 +00005222 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005223 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005224 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005225 RefValue))
5226 return false;
5227 return Success(RefValue, E);
5228 }
5229 return true;
5230 }
5231
5232 bool VisitBinaryOperator(const BinaryOperator *E) {
5233 switch (E->getOpcode()) {
5234 default:
5235 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5236
5237 case BO_PtrMemD:
5238 case BO_PtrMemI:
5239 return HandleMemberPointerAccess(this->Info, E, Result);
5240 }
5241 }
5242
5243 bool VisitCastExpr(const CastExpr *E) {
5244 switch (E->getCastKind()) {
5245 default:
5246 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5247
5248 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005249 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005250 if (!this->Visit(E->getSubExpr()))
5251 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005252
5253 // Now figure out the necessary offset to add to the base LV to get from
5254 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005255 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5256 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005257 }
5258 }
5259};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005260}
Richard Smith027bf112011-11-17 22:56:20 +00005261
5262//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005263// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005264//
5265// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5266// function designators (in C), decl references to void objects (in C), and
5267// temporaries (if building with -Wno-address-of-temporary).
5268//
5269// LValue evaluation produces values comprising a base expression of one of the
5270// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005271// - Declarations
5272// * VarDecl
5273// * FunctionDecl
5274// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005275// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005276// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005277// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005278// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005279// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005280// * ObjCEncodeExpr
5281// * AddrLabelExpr
5282// * BlockExpr
5283// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005284// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005285// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005286// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005287// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5288// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005289// * A MaterializeTemporaryExpr that has static storage duration, with no
5290// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005291// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005292//===----------------------------------------------------------------------===//
5293namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005294class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005295 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005296public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005297 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5298 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005299
Richard Smith11562c52011-10-28 17:51:58 +00005300 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005301 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005302
Peter Collingbournee9200682011-05-13 03:29:01 +00005303 bool VisitDeclRefExpr(const DeclRefExpr *E);
5304 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005305 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005306 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5307 bool VisitMemberExpr(const MemberExpr *E);
5308 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5309 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005310 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005311 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005312 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5313 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005314 bool VisitUnaryReal(const UnaryOperator *E);
5315 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005316 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5317 return VisitUnaryPreIncDec(UO);
5318 }
5319 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5320 return VisitUnaryPreIncDec(UO);
5321 }
Richard Smith3229b742013-05-05 21:17:10 +00005322 bool VisitBinAssign(const BinaryOperator *BO);
5323 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005324
Peter Collingbournee9200682011-05-13 03:29:01 +00005325 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005326 switch (E->getCastKind()) {
5327 default:
Richard Smith027bf112011-11-17 22:56:20 +00005328 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005329
Eli Friedmance3e02a2011-10-11 00:13:24 +00005330 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005331 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005332 if (!Visit(E->getSubExpr()))
5333 return false;
5334 Result.Designator.setInvalid();
5335 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005336
Richard Smith027bf112011-11-17 22:56:20 +00005337 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005338 if (!Visit(E->getSubExpr()))
5339 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005340 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005341 }
5342 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005343};
5344} // end anonymous namespace
5345
Richard Smith11562c52011-10-28 17:51:58 +00005346/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005347/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005348/// * function designators in C, and
5349/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005350/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005351static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5352 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005353 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005354 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005355 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005356}
5357
Peter Collingbournee9200682011-05-13 03:29:01 +00005358bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005359 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005360 return Success(FD);
5361 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005362 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005363 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005364 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005365 return Error(E);
5366}
Richard Smith733237d2011-10-24 23:14:33 +00005367
Faisal Vali0528a312016-11-13 06:09:16 +00005368
Richard Smith11562c52011-10-28 17:51:58 +00005369bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005370
5371 // If we are within a lambda's call operator, check whether the 'VD' referred
5372 // to within 'E' actually represents a lambda-capture that maps to a
5373 // data-member/field within the closure object, and if so, evaluate to the
5374 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005375 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5376 isa<DeclRefExpr>(E) &&
5377 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5378 // We don't always have a complete capture-map when checking or inferring if
5379 // the function call operator meets the requirements of a constexpr function
5380 // - but we don't need to evaluate the captures to determine constexprness
5381 // (dcl.constexpr C++17).
5382 if (Info.checkingPotentialConstantExpression())
5383 return false;
5384
Faisal Vali051e3a22017-02-16 04:12:21 +00005385 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005386 // Start with 'Result' referring to the complete closure object...
5387 Result = *Info.CurrentCall->This;
5388 // ... then update it to refer to the field of the closure object
5389 // that represents the capture.
5390 if (!HandleLValueMember(Info, E, Result, FD))
5391 return false;
5392 // And if the field is of reference type, update 'Result' to refer to what
5393 // the field refers to.
5394 if (FD->getType()->isReferenceType()) {
5395 APValue RVal;
5396 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5397 RVal))
5398 return false;
5399 Result.setFrom(Info.Ctx, RVal);
5400 }
5401 return true;
5402 }
5403 }
Craig Topper36250ad2014-05-12 05:36:57 +00005404 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005405 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5406 // Only if a local variable was declared in the function currently being
5407 // evaluated, do we expect to be able to find its value in the current
5408 // frame. (Otherwise it was likely declared in an enclosing context and
5409 // could either have a valid evaluatable value (for e.g. a constexpr
5410 // variable) or be ill-formed (and trigger an appropriate evaluation
5411 // diagnostic)).
5412 if (Info.CurrentCall->Callee &&
5413 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5414 Frame = Info.CurrentCall;
5415 }
5416 }
Richard Smith3229b742013-05-05 21:17:10 +00005417
Richard Smithfec09922011-11-01 16:57:24 +00005418 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005419 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005420 Result.set({VD, Frame->Index,
5421 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005422 return true;
5423 }
Richard Smithce40ad62011-11-12 22:28:03 +00005424 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005425 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005426
Richard Smith3229b742013-05-05 21:17:10 +00005427 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005428 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005429 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005430 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005431 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005432 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005433 return false;
5434 }
Richard Smith3229b742013-05-05 21:17:10 +00005435 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005436}
5437
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005438bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5439 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005440 // Walk through the expression to find the materialized temporary itself.
5441 SmallVector<const Expr *, 2> CommaLHSs;
5442 SmallVector<SubobjectAdjustment, 2> Adjustments;
5443 const Expr *Inner = E->GetTemporaryExpr()->
5444 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005445
Richard Smith84401042013-06-03 05:03:02 +00005446 // If we passed any comma operators, evaluate their LHSs.
5447 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5448 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5449 return false;
5450
Richard Smithe6c01442013-06-05 00:46:14 +00005451 // A materialized temporary with static storage duration can appear within the
5452 // result of a constant expression evaluation, so we need to preserve its
5453 // value for use outside this evaluation.
5454 APValue *Value;
5455 if (E->getStorageDuration() == SD_Static) {
5456 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005457 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005458 Result.set(E);
5459 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005460 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5461 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005462 }
5463
Richard Smithea4ad5d2013-06-06 08:19:16 +00005464 QualType Type = Inner->getType();
5465
Richard Smith84401042013-06-03 05:03:02 +00005466 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005467 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5468 (E->getStorageDuration() == SD_Static &&
5469 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5470 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005471 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005472 }
Richard Smith84401042013-06-03 05:03:02 +00005473
5474 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005475 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5476 --I;
5477 switch (Adjustments[I].Kind) {
5478 case SubobjectAdjustment::DerivedToBaseAdjustment:
5479 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5480 Type, Result))
5481 return false;
5482 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5483 break;
5484
5485 case SubobjectAdjustment::FieldAdjustment:
5486 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5487 return false;
5488 Type = Adjustments[I].Field->getType();
5489 break;
5490
5491 case SubobjectAdjustment::MemberPointerAdjustment:
5492 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5493 Adjustments[I].Ptr.RHS))
5494 return false;
5495 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5496 break;
5497 }
5498 }
5499
5500 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005501}
5502
Peter Collingbournee9200682011-05-13 03:29:01 +00005503bool
5504LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005505 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5506 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005507 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5508 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005509 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005510}
5511
Richard Smith6e525142011-12-27 12:18:28 +00005512bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005513 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005514 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005515
Faisal Valie690b7a2016-07-02 22:34:24 +00005516 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005517 << E->getExprOperand()->getType()
5518 << E->getExprOperand()->getSourceRange();
5519 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005520}
5521
Francois Pichet0066db92012-04-16 04:08:35 +00005522bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5523 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005524}
Francois Pichet0066db92012-04-16 04:08:35 +00005525
Peter Collingbournee9200682011-05-13 03:29:01 +00005526bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005527 // Handle static data members.
5528 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005529 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005530 return VisitVarDecl(E, VD);
5531 }
5532
Richard Smith254a73d2011-10-28 22:34:42 +00005533 // Handle static member functions.
5534 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5535 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005536 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005537 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005538 }
5539 }
5540
Richard Smithd62306a2011-11-10 06:34:14 +00005541 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005542 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005543}
5544
Peter Collingbournee9200682011-05-13 03:29:01 +00005545bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005546 // FIXME: Deal with vectors as array subscript bases.
5547 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005548 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005549
Nick Lewyckyad888682017-04-27 07:27:36 +00005550 bool Success = true;
5551 if (!evaluatePointer(E->getBase(), Result)) {
5552 if (!Info.noteFailure())
5553 return false;
5554 Success = false;
5555 }
Mike Stump11289f42009-09-09 15:08:12 +00005556
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005557 APSInt Index;
5558 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005559 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005560
Nick Lewyckyad888682017-04-27 07:27:36 +00005561 return Success &&
5562 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005563}
Eli Friedman9a156e52008-11-12 09:44:48 +00005564
Peter Collingbournee9200682011-05-13 03:29:01 +00005565bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005566 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005567}
5568
Richard Smith66c96992012-02-18 22:04:06 +00005569bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5570 if (!Visit(E->getSubExpr()))
5571 return false;
5572 // __real is a no-op on scalar lvalues.
5573 if (E->getSubExpr()->getType()->isAnyComplexType())
5574 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5575 return true;
5576}
5577
5578bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5579 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5580 "lvalue __imag__ on scalar?");
5581 if (!Visit(E->getSubExpr()))
5582 return false;
5583 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5584 return true;
5585}
5586
Richard Smith243ef902013-05-05 23:31:59 +00005587bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005588 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005589 return Error(UO);
5590
5591 if (!this->Visit(UO->getSubExpr()))
5592 return false;
5593
Richard Smith243ef902013-05-05 23:31:59 +00005594 return handleIncDec(
5595 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005596 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005597}
5598
5599bool LValueExprEvaluator::VisitCompoundAssignOperator(
5600 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005601 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005602 return Error(CAO);
5603
Richard Smith3229b742013-05-05 21:17:10 +00005604 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005605
5606 // The overall lvalue result is the result of evaluating the LHS.
5607 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005608 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005609 Evaluate(RHS, this->Info, CAO->getRHS());
5610 return false;
5611 }
5612
Richard Smith3229b742013-05-05 21:17:10 +00005613 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5614 return false;
5615
Richard Smith43e77732013-05-07 04:50:00 +00005616 return handleCompoundAssignment(
5617 this->Info, CAO,
5618 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5619 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005620}
5621
5622bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005623 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005624 return Error(E);
5625
Richard Smith3229b742013-05-05 21:17:10 +00005626 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005627
5628 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005629 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005630 Evaluate(NewVal, this->Info, E->getRHS());
5631 return false;
5632 }
5633
Richard Smith3229b742013-05-05 21:17:10 +00005634 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5635 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005636
5637 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005638 NewVal);
5639}
5640
Eli Friedman9a156e52008-11-12 09:44:48 +00005641//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005642// Pointer Evaluation
5643//===----------------------------------------------------------------------===//
5644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005645/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005646/// returned by a function with the alloc_size attribute. Returns true if we
5647/// were successful. Places an unsigned number into `Result`.
5648///
5649/// This expects the given CallExpr to be a call to a function with an
5650/// alloc_size attribute.
5651static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5652 const CallExpr *Call,
5653 llvm::APInt &Result) {
5654 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5655
Joel E. Denny81508102018-03-13 14:51:22 +00005656 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5657 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005658 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5659 if (Call->getNumArgs() <= SizeArgNo)
5660 return false;
5661
5662 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005663 Expr::EvalResult ExprResult;
5664 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005665 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005666 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005667 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5668 return false;
5669 Into = Into.zextOrSelf(BitsInSizeT);
5670 return true;
5671 };
5672
5673 APSInt SizeOfElem;
5674 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5675 return false;
5676
Joel E. Denny81508102018-03-13 14:51:22 +00005677 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005678 Result = std::move(SizeOfElem);
5679 return true;
5680 }
5681
5682 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005683 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005684 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5685 return false;
5686
5687 bool Overflow;
5688 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5689 if (Overflow)
5690 return false;
5691
5692 Result = std::move(BytesAvailable);
5693 return true;
5694}
5695
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005696/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005697/// function.
5698static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5699 const LValue &LVal,
5700 llvm::APInt &Result) {
5701 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5702 "Can't get the size of a non alloc_size function");
5703 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5704 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5705 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5706}
5707
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005708/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005709/// a function with the alloc_size attribute. If it was possible to do so, this
5710/// function will return true, make Result's Base point to said function call,
5711/// and mark Result's Base as invalid.
5712static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5713 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005714 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005715 return false;
5716
5717 // Because we do no form of static analysis, we only support const variables.
5718 //
5719 // Additionally, we can't support parameters, nor can we support static
5720 // variables (in the latter case, use-before-assign isn't UB; in the former,
5721 // we have no clue what they'll be assigned to).
5722 const auto *VD =
5723 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5724 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5725 return false;
5726
5727 const Expr *Init = VD->getAnyInitializer();
5728 if (!Init)
5729 return false;
5730
5731 const Expr *E = Init->IgnoreParens();
5732 if (!tryUnwrapAllocSizeCall(E))
5733 return false;
5734
5735 // Store E instead of E unwrapped so that the type of the LValue's base is
5736 // what the user wanted.
5737 Result.setInvalid(E);
5738
5739 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005740 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005741 return true;
5742}
5743
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005744namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005745class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005746 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005747 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005748 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005749
Peter Collingbournee9200682011-05-13 03:29:01 +00005750 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005751 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005752 return true;
5753 }
George Burgess IVe3763372016-12-22 02:50:20 +00005754
George Burgess IVf9013bf2017-02-10 22:52:29 +00005755 bool evaluateLValue(const Expr *E, LValue &Result) {
5756 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5757 }
5758
5759 bool evaluatePointer(const Expr *E, LValue &Result) {
5760 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5761 }
5762
George Burgess IVe3763372016-12-22 02:50:20 +00005763 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005764public:
Mike Stump11289f42009-09-09 15:08:12 +00005765
George Burgess IVf9013bf2017-02-10 22:52:29 +00005766 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5767 : ExprEvaluatorBaseTy(info), Result(Result),
5768 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005769
Richard Smith2e312c82012-03-03 22:46:17 +00005770 bool Success(const APValue &V, const Expr *E) {
5771 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005772 return true;
5773 }
Richard Smithfddd3842011-12-30 21:15:51 +00005774 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005775 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5776 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005777 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005778 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005779
John McCall45d55e42010-05-07 21:00:08 +00005780 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005781 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005782 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005783 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005784 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005785 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5786 if (Info.noteFailure())
5787 EvaluateIgnoredValue(Info, E->getSubExpr());
5788 return Error(E);
5789 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005790 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005791 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005792 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005793 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005794 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005795 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005796 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005797 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005798 }
Richard Smithd62306a2011-11-10 06:34:14 +00005799 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005800 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005801 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005802 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005803 if (!Info.CurrentCall->This) {
5804 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005805 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005806 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005807 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005808 return false;
5809 }
Richard Smithd62306a2011-11-10 06:34:14 +00005810 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005811 // If we are inside a lambda's call operator, the 'this' expression refers
5812 // to the enclosing '*this' object (either by value or reference) which is
5813 // either copied into the closure object's field that represents the '*this'
5814 // or refers to '*this'.
5815 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5816 // Update 'Result' to refer to the data member/field of the closure object
5817 // that represents the '*this' capture.
5818 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005819 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005820 return false;
5821 // If we captured '*this' by reference, replace the field with its referent.
5822 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5823 ->isPointerType()) {
5824 APValue RVal;
5825 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5826 RVal))
5827 return false;
5828
5829 Result.setFrom(Info.Ctx, RVal);
5830 }
5831 }
Richard Smithd62306a2011-11-10 06:34:14 +00005832 return true;
5833 }
John McCallc07a0c72011-02-17 10:25:35 +00005834
Eli Friedman449fe542009-03-23 04:56:01 +00005835 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005836};
Chris Lattner05706e882008-07-11 18:11:29 +00005837} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005838
George Burgess IVf9013bf2017-02-10 22:52:29 +00005839static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5840 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005841 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005842 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005843}
5844
John McCall45d55e42010-05-07 21:00:08 +00005845bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005846 if (E->getOpcode() != BO_Add &&
5847 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005848 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005849
Chris Lattner05706e882008-07-11 18:11:29 +00005850 const Expr *PExp = E->getLHS();
5851 const Expr *IExp = E->getRHS();
5852 if (IExp->getType()->isPointerType())
5853 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005854
George Burgess IVf9013bf2017-02-10 22:52:29 +00005855 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005856 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005857 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005858
John McCall45d55e42010-05-07 21:00:08 +00005859 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005860 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005861 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005862
Richard Smith96e0c102011-11-04 02:25:55 +00005863 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005864 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005865
Ted Kremenek28831752012-08-23 20:46:57 +00005866 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005867 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005868}
Eli Friedman9a156e52008-11-12 09:44:48 +00005869
John McCall45d55e42010-05-07 21:00:08 +00005870bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005871 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005872}
Mike Stump11289f42009-09-09 15:08:12 +00005873
Richard Smith81dfef92018-07-11 00:29:05 +00005874bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5875 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005876
Eli Friedman847a2bc2009-12-27 05:43:15 +00005877 switch (E->getCastKind()) {
5878 default:
5879 break;
5880
John McCalle3027922010-08-25 11:45:40 +00005881 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005882 case CK_CPointerToObjCPointerCast:
5883 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005884 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005885 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005886 if (!Visit(SubExpr))
5887 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005888 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5889 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5890 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005891 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005892 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005893 if (SubExpr->getType()->isVoidPointerType())
5894 CCEDiag(E, diag::note_constexpr_invalid_cast)
5895 << 3 << SubExpr->getType();
5896 else
5897 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5898 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005899 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5900 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005901 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005902
Anders Carlsson18275092010-10-31 20:41:46 +00005903 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005904 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005905 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005906 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005907 if (!Result.Base && Result.Offset.isZero())
5908 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005909
Richard Smithd62306a2011-11-10 06:34:14 +00005910 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005911 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005912 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5913 castAs<PointerType>()->getPointeeType(),
5914 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005915
Richard Smith027bf112011-11-17 22:56:20 +00005916 case CK_BaseToDerived:
5917 if (!Visit(E->getSubExpr()))
5918 return false;
5919 if (!Result.Base && Result.Offset.isZero())
5920 return true;
5921 return HandleBaseToDerivedCast(Info, E, Result);
5922
Richard Smith0b0a0b62011-10-29 20:57:55 +00005923 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005924 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005925 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005926
John McCalle3027922010-08-25 11:45:40 +00005927 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005928 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5929
Richard Smith2e312c82012-03-03 22:46:17 +00005930 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005931 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005932 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005933
John McCall45d55e42010-05-07 21:00:08 +00005934 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005935 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5936 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005937 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005938 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005939 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005940 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005941 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005942 return true;
5943 } else {
5944 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005945 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005946 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005947 }
5948 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005949
5950 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005951 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005952 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005953 return false;
5954 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005955 APValue &Value = createTemporary(SubExpr, false, Result,
5956 *Info.CurrentCall);
5957 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005958 return false;
5959 }
Richard Smith96e0c102011-11-04 02:25:55 +00005960 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005961 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5962 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005963 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005964 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005965 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005966 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005967 }
Richard Smithdd785442011-10-31 20:57:44 +00005968
John McCalle3027922010-08-25 11:45:40 +00005969 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005970 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005971
5972 case CK_LValueToRValue: {
5973 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005974 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005975 return false;
5976
5977 APValue RVal;
5978 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5979 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5980 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005981 return InvalidBaseOK &&
5982 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005983 return Success(RVal, E);
5984 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005985 }
5986
Richard Smith11562c52011-10-28 17:51:58 +00005987 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005988}
Chris Lattner05706e882008-07-11 18:11:29 +00005989
Richard Smith6822bd72018-10-26 19:26:45 +00005990static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5991 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005992 // C++ [expr.alignof]p3:
5993 // When alignof is applied to a reference type, the result is the
5994 // alignment of the referenced type.
5995 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5996 T = Ref->getPointeeType();
5997
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005998 if (T.getQualifiers().hasUnaligned())
5999 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006000
6001 const bool AlignOfReturnsPreferred =
6002 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6003
6004 // __alignof is defined to return the preferred alignment.
6005 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6006 // as well.
6007 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6008 return Info.Ctx.toCharUnitsFromBits(
6009 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6010 // alignof and _Alignof are defined to return the ABI alignment.
6011 else if (ExprKind == UETT_AlignOf)
6012 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6013 else
6014 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006015}
6016
Richard Smith6822bd72018-10-26 19:26:45 +00006017static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6018 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006019 E = E->IgnoreParens();
6020
6021 // The kinds of expressions that we have special-case logic here for
6022 // should be kept up to date with the special checks for those
6023 // expressions in Sema.
6024
6025 // alignof decl is always accepted, even if it doesn't make sense: we default
6026 // to 1 in those cases.
6027 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6028 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6029 /*RefAsPointee*/true);
6030
6031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6032 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6033 /*RefAsPointee*/true);
6034
Richard Smith6822bd72018-10-26 19:26:45 +00006035 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006036}
6037
George Burgess IVe3763372016-12-22 02:50:20 +00006038// To be clear: this happily visits unsupported builtins. Better name welcomed.
6039bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6040 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6041 return true;
6042
George Burgess IVf9013bf2017-02-10 22:52:29 +00006043 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006044 return false;
6045
6046 Result.setInvalid(E);
6047 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006048 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006049 return true;
6050}
6051
Peter Collingbournee9200682011-05-13 03:29:01 +00006052bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006053 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006054 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006055
Richard Smith6328cbd2016-11-16 00:57:23 +00006056 if (unsigned BuiltinOp = E->getBuiltinCallee())
6057 return VisitBuiltinCallExpr(E, BuiltinOp);
6058
George Burgess IVe3763372016-12-22 02:50:20 +00006059 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006060}
6061
6062bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6063 unsigned BuiltinOp) {
6064 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006065 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006066 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006067 case Builtin::BI__builtin_assume_aligned: {
6068 // We need to be very careful here because: if the pointer does not have the
6069 // asserted alignment, then the behavior is undefined, and undefined
6070 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006071 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006072 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006073
Hal Finkel0dd05d42014-10-03 17:18:37 +00006074 LValue OffsetResult(Result);
6075 APSInt Alignment;
6076 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6077 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006078 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006079
6080 if (E->getNumArgs() > 2) {
6081 APSInt Offset;
6082 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6083 return false;
6084
Richard Smith642a2362017-01-30 23:30:26 +00006085 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006086 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6087 }
6088
6089 // If there is a base object, then it must have the correct alignment.
6090 if (OffsetResult.Base) {
6091 CharUnits BaseAlignment;
6092 if (const ValueDecl *VD =
6093 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6094 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6095 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006096 BaseAlignment = GetAlignOfExpr(
6097 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006098 }
6099
6100 if (BaseAlignment < Align) {
6101 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006102 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006103 CCEDiag(E->getArg(0),
6104 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006105 << (unsigned)BaseAlignment.getQuantity()
6106 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006107 return false;
6108 }
6109 }
6110
6111 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006112 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006113 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006114
Richard Smith642a2362017-01-30 23:30:26 +00006115 (OffsetResult.Base
6116 ? CCEDiag(E->getArg(0),
6117 diag::note_constexpr_baa_insufficient_alignment) << 1
6118 : CCEDiag(E->getArg(0),
6119 diag::note_constexpr_baa_value_insufficient_alignment))
6120 << (int)OffsetResult.Offset.getQuantity()
6121 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006122 return false;
6123 }
6124
6125 return true;
6126 }
Eric Fiselier26187502018-12-14 21:11:28 +00006127 case Builtin::BI__builtin_launder:
6128 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006129 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006130 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006131 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006132 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006133 if (Info.getLangOpts().CPlusPlus11)
6134 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6135 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006136 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006137 else
6138 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006139 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006140 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006141 case Builtin::BI__builtin_wcschr:
6142 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006143 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006144 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006145 if (!Visit(E->getArg(0)))
6146 return false;
6147 APSInt Desired;
6148 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6149 return false;
6150 uint64_t MaxLength = uint64_t(-1);
6151 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006152 BuiltinOp != Builtin::BIwcschr &&
6153 BuiltinOp != Builtin::BI__builtin_strchr &&
6154 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006155 APSInt N;
6156 if (!EvaluateInteger(E->getArg(2), N, Info))
6157 return false;
6158 MaxLength = N.getExtValue();
6159 }
Hubert Tong147b7432018-12-12 16:53:43 +00006160 // We cannot find the value if there are no candidates to match against.
6161 if (MaxLength == 0u)
6162 return ZeroInitialization(E);
6163 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6164 Result.Designator.Invalid)
6165 return false;
6166 QualType CharTy = Result.Designator.getType(Info.Ctx);
6167 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6168 BuiltinOp == Builtin::BI__builtin_memchr;
6169 assert(IsRawByte ||
6170 Info.Ctx.hasSameUnqualifiedType(
6171 CharTy, E->getArg(0)->getType()->getPointeeType()));
6172 // Pointers to const void may point to objects of incomplete type.
6173 if (IsRawByte && CharTy->isIncompleteType()) {
6174 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6175 return false;
6176 }
6177 // Give up on byte-oriented matching against multibyte elements.
6178 // FIXME: We can compare the bytes in the correct order.
6179 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6180 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006181 // Figure out what value we're actually looking for (after converting to
6182 // the corresponding unsigned type if necessary).
6183 uint64_t DesiredVal;
6184 bool StopAtNull = false;
6185 switch (BuiltinOp) {
6186 case Builtin::BIstrchr:
6187 case Builtin::BI__builtin_strchr:
6188 // strchr compares directly to the passed integer, and therefore
6189 // always fails if given an int that is not a char.
6190 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6191 E->getArg(1)->getType(),
6192 Desired),
6193 Desired))
6194 return ZeroInitialization(E);
6195 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006196 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006197 case Builtin::BImemchr:
6198 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006199 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006200 // memchr compares by converting both sides to unsigned char. That's also
6201 // correct for strchr if we get this far (to cope with plain char being
6202 // unsigned in the strchr case).
6203 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6204 break;
Richard Smithe9507952016-11-12 01:39:56 +00006205
Richard Smith8110c9d2016-11-29 19:45:17 +00006206 case Builtin::BIwcschr:
6207 case Builtin::BI__builtin_wcschr:
6208 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006209 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006210 case Builtin::BIwmemchr:
6211 case Builtin::BI__builtin_wmemchr:
6212 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6213 DesiredVal = Desired.getZExtValue();
6214 break;
6215 }
Richard Smithe9507952016-11-12 01:39:56 +00006216
6217 for (; MaxLength; --MaxLength) {
6218 APValue Char;
6219 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6220 !Char.isInt())
6221 return false;
6222 if (Char.getInt().getZExtValue() == DesiredVal)
6223 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006224 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006225 break;
6226 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6227 return false;
6228 }
6229 // Not found: return nullptr.
6230 return ZeroInitialization(E);
6231 }
6232
Richard Smith06f71b52018-08-04 00:57:17 +00006233 case Builtin::BImemcpy:
6234 case Builtin::BImemmove:
6235 case Builtin::BIwmemcpy:
6236 case Builtin::BIwmemmove:
6237 if (Info.getLangOpts().CPlusPlus11)
6238 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6239 << /*isConstexpr*/0 << /*isConstructor*/0
6240 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6241 else
6242 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6243 LLVM_FALLTHROUGH;
6244 case Builtin::BI__builtin_memcpy:
6245 case Builtin::BI__builtin_memmove:
6246 case Builtin::BI__builtin_wmemcpy:
6247 case Builtin::BI__builtin_wmemmove: {
6248 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6249 BuiltinOp == Builtin::BIwmemmove ||
6250 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6251 BuiltinOp == Builtin::BI__builtin_wmemmove;
6252 bool Move = BuiltinOp == Builtin::BImemmove ||
6253 BuiltinOp == Builtin::BIwmemmove ||
6254 BuiltinOp == Builtin::BI__builtin_memmove ||
6255 BuiltinOp == Builtin::BI__builtin_wmemmove;
6256
6257 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006258 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006259 return false;
6260 LValue Dest = Result;
6261
6262 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006263 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006264 return false;
6265
6266 APSInt N;
6267 if (!EvaluateInteger(E->getArg(2), N, Info))
6268 return false;
6269 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6270
6271 // If the size is zero, we treat this as always being a valid no-op.
6272 // (Even if one of the src and dest pointers is null.)
6273 if (!N)
6274 return true;
6275
Richard Smith128719c2018-09-13 22:47:33 +00006276 // Otherwise, if either of the operands is null, we can't proceed. Don't
6277 // try to determine the type of the copied objects, because there aren't
6278 // any.
6279 if (!Src.Base || !Dest.Base) {
6280 APValue Val;
6281 (!Src.Base ? Src : Dest).moveInto(Val);
6282 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6283 << Move << WChar << !!Src.Base
6284 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6285 return false;
6286 }
6287 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6288 return false;
6289
Richard Smith06f71b52018-08-04 00:57:17 +00006290 // We require that Src and Dest are both pointers to arrays of
6291 // trivially-copyable type. (For the wide version, the designator will be
6292 // invalid if the designated object is not a wchar_t.)
6293 QualType T = Dest.Designator.getType(Info.Ctx);
6294 QualType SrcT = Src.Designator.getType(Info.Ctx);
6295 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6296 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6297 return false;
6298 }
Petr Pavlued083f22018-10-04 09:25:44 +00006299 if (T->isIncompleteType()) {
6300 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6301 return false;
6302 }
Richard Smith06f71b52018-08-04 00:57:17 +00006303 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6304 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6305 return false;
6306 }
6307
6308 // Figure out how many T's we're copying.
6309 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6310 if (!WChar) {
6311 uint64_t Remainder;
6312 llvm::APInt OrigN = N;
6313 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6314 if (Remainder) {
6315 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6316 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6317 << (unsigned)TSize;
6318 return false;
6319 }
6320 }
6321
6322 // Check that the copying will remain within the arrays, just so that we
6323 // can give a more meaningful diagnostic. This implicitly also checks that
6324 // N fits into 64 bits.
6325 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6326 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6327 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6328 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6329 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6330 << N.toString(10, /*Signed*/false);
6331 return false;
6332 }
6333 uint64_t NElems = N.getZExtValue();
6334 uint64_t NBytes = NElems * TSize;
6335
6336 // Check for overlap.
6337 int Direction = 1;
6338 if (HasSameBase(Src, Dest)) {
6339 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6340 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6341 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6342 // Dest is inside the source region.
6343 if (!Move) {
6344 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6345 return false;
6346 }
6347 // For memmove and friends, copy backwards.
6348 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6349 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6350 return false;
6351 Direction = -1;
6352 } else if (!Move && SrcOffset >= DestOffset &&
6353 SrcOffset - DestOffset < NBytes) {
6354 // Src is inside the destination region for memcpy: invalid.
6355 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6356 return false;
6357 }
6358 }
6359
6360 while (true) {
6361 APValue Val;
6362 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6363 !handleAssignment(Info, E, Dest, T, Val))
6364 return false;
6365 // Do not iterate past the last element; if we're copying backwards, that
6366 // might take us off the start of the array.
6367 if (--NElems == 0)
6368 return true;
6369 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6370 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6371 return false;
6372 }
6373 }
6374
Richard Smith6cbd65d2013-07-11 02:27:57 +00006375 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006376 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006377 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006378}
Chris Lattner05706e882008-07-11 18:11:29 +00006379
6380//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006381// Member Pointer Evaluation
6382//===----------------------------------------------------------------------===//
6383
6384namespace {
6385class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006386 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006387 MemberPtr &Result;
6388
6389 bool Success(const ValueDecl *D) {
6390 Result = MemberPtr(D);
6391 return true;
6392 }
6393public:
6394
6395 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6396 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6397
Richard Smith2e312c82012-03-03 22:46:17 +00006398 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006399 Result.setFrom(V);
6400 return true;
6401 }
Richard Smithfddd3842011-12-30 21:15:51 +00006402 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006403 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006404 }
6405
6406 bool VisitCastExpr(const CastExpr *E);
6407 bool VisitUnaryAddrOf(const UnaryOperator *E);
6408};
6409} // end anonymous namespace
6410
6411static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6412 EvalInfo &Info) {
6413 assert(E->isRValue() && E->getType()->isMemberPointerType());
6414 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6415}
6416
6417bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6418 switch (E->getCastKind()) {
6419 default:
6420 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6421
6422 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006423 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006424 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006425
6426 case CK_BaseToDerivedMemberPointer: {
6427 if (!Visit(E->getSubExpr()))
6428 return false;
6429 if (E->path_empty())
6430 return true;
6431 // Base-to-derived member pointer casts store the path in derived-to-base
6432 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6433 // the wrong end of the derived->base arc, so stagger the path by one class.
6434 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6435 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6436 PathI != PathE; ++PathI) {
6437 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6438 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6439 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006440 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006441 }
6442 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6443 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006444 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006445 return true;
6446 }
6447
6448 case CK_DerivedToBaseMemberPointer:
6449 if (!Visit(E->getSubExpr()))
6450 return false;
6451 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6452 PathE = E->path_end(); PathI != PathE; ++PathI) {
6453 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6454 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6455 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006456 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006457 }
6458 return true;
6459 }
6460}
6461
6462bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6463 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6464 // member can be formed.
6465 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6466}
6467
6468//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006469// Record Evaluation
6470//===----------------------------------------------------------------------===//
6471
6472namespace {
6473 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006474 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006475 const LValue &This;
6476 APValue &Result;
6477 public:
6478
6479 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6480 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6481
Richard Smith2e312c82012-03-03 22:46:17 +00006482 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006483 Result = V;
6484 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006485 }
Richard Smithb8348f52016-05-12 22:16:28 +00006486 bool ZeroInitialization(const Expr *E) {
6487 return ZeroInitialization(E, E->getType());
6488 }
6489 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006490
Richard Smith52a980a2015-08-28 02:43:42 +00006491 bool VisitCallExpr(const CallExpr *E) {
6492 return handleCallExpr(E, Result, &This);
6493 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006494 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006495 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006496 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6497 return VisitCXXConstructExpr(E, E->getType());
6498 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006499 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006500 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006501 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006502 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006503
6504 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006505 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006506}
Richard Smithd62306a2011-11-10 06:34:14 +00006507
Richard Smithfddd3842011-12-30 21:15:51 +00006508/// Perform zero-initialization on an object of non-union class type.
6509/// C++11 [dcl.init]p5:
6510/// To zero-initialize an object or reference of type T means:
6511/// [...]
6512/// -- if T is a (possibly cv-qualified) non-union class type,
6513/// each non-static data member and each base-class subobject is
6514/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006515static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6516 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006517 const LValue &This, APValue &Result) {
6518 assert(!RD->isUnion() && "Expected non-union class type");
6519 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6520 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006521 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006522
John McCalld7bca762012-05-01 00:38:49 +00006523 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006524 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6525
6526 if (CD) {
6527 unsigned Index = 0;
6528 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006529 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006530 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6531 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006532 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6533 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006534 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006535 Result.getStructBase(Index)))
6536 return false;
6537 }
6538 }
6539
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006540 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006541 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006542 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006543 continue;
6544
6545 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006546 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006547 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006548
David Blaikie2d7c57e2012-04-30 02:36:29 +00006549 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006550 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006551 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006552 return false;
6553 }
6554
6555 return true;
6556}
6557
Richard Smithb8348f52016-05-12 22:16:28 +00006558bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6559 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006560 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006561 if (RD->isUnion()) {
6562 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6563 // object's first non-static named data member is zero-initialized
6564 RecordDecl::field_iterator I = RD->field_begin();
6565 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006566 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006567 return true;
6568 }
6569
6570 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006571 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006572 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006573 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006574 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006575 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006576 }
6577
Richard Smith5d108602012-02-17 00:44:16 +00006578 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006579 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006580 return false;
6581 }
6582
Richard Smitha8105bc2012-01-06 16:39:00 +00006583 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006584}
6585
Richard Smithe97cbd72011-11-11 04:05:33 +00006586bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6587 switch (E->getCastKind()) {
6588 default:
6589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6590
6591 case CK_ConstructorConversion:
6592 return Visit(E->getSubExpr());
6593
6594 case CK_DerivedToBase:
6595 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006596 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006597 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006598 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006599 if (!DerivedObject.isStruct())
6600 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006601
6602 // Derived-to-base rvalue conversion: just slice off the derived part.
6603 APValue *Value = &DerivedObject;
6604 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6605 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6606 PathE = E->path_end(); PathI != PathE; ++PathI) {
6607 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6608 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6609 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6610 RD = Base;
6611 }
6612 Result = *Value;
6613 return true;
6614 }
6615 }
6616}
6617
Richard Smithd62306a2011-11-10 06:34:14 +00006618bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006619 if (E->isTransparent())
6620 return Visit(E->getInit(0));
6621
Richard Smithd62306a2011-11-10 06:34:14 +00006622 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006623 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006624 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6625
6626 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006627 const FieldDecl *Field = E->getInitializedFieldInUnion();
6628 Result = APValue(Field);
6629 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006630 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006631
6632 // If the initializer list for a union does not contain any elements, the
6633 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006634 // FIXME: The element should be initialized from an initializer list.
6635 // Is this difference ever observable for initializer lists which
6636 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006637 ImplicitValueInitExpr VIE(Field->getType());
6638 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6639
Richard Smithd62306a2011-11-10 06:34:14 +00006640 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006641 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6642 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006643
6644 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6645 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6646 isa<CXXDefaultInitExpr>(InitExpr));
6647
Richard Smithb228a862012-02-15 02:18:13 +00006648 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006649 }
6650
Richard Smith872307e2016-03-08 22:17:41 +00006651 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006652 if (Result.isUninit())
6653 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6654 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006655 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006656 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006657
6658 // Initialize base classes.
6659 if (CXXRD) {
6660 for (const auto &Base : CXXRD->bases()) {
6661 assert(ElementNo < E->getNumInits() && "missing init for base class");
6662 const Expr *Init = E->getInit(ElementNo);
6663
6664 LValue Subobject = This;
6665 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6666 return false;
6667
6668 APValue &FieldVal = Result.getStructBase(ElementNo);
6669 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006670 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006671 return false;
6672 Success = false;
6673 }
6674 ++ElementNo;
6675 }
6676 }
6677
6678 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006679 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006680 // Anonymous bit-fields are not considered members of the class for
6681 // purposes of aggregate initialization.
6682 if (Field->isUnnamedBitfield())
6683 continue;
6684
6685 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006686
Richard Smith253c2a32012-01-27 01:14:48 +00006687 bool HaveInit = ElementNo < E->getNumInits();
6688
6689 // FIXME: Diagnostics here should point to the end of the initializer
6690 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006691 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006692 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006693 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006694
6695 // Perform an implicit value-initialization for members beyond the end of
6696 // the initializer list.
6697 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006698 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006699
Richard Smith852c9db2013-04-20 22:23:05 +00006700 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6701 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6702 isa<CXXDefaultInitExpr>(Init));
6703
Richard Smith49ca8aa2013-08-06 07:09:20 +00006704 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6705 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6706 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006707 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006708 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006709 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006710 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006711 }
6712 }
6713
Richard Smith253c2a32012-01-27 01:14:48 +00006714 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006715}
6716
Richard Smithb8348f52016-05-12 22:16:28 +00006717bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6718 QualType T) {
6719 // Note that E's type is not necessarily the type of our class here; we might
6720 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006721 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006722 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6723
Richard Smithfddd3842011-12-30 21:15:51 +00006724 bool ZeroInit = E->requiresZeroInitialization();
6725 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006726 // If we've already performed zero-initialization, we're already done.
6727 if (!Result.isUninit())
6728 return true;
6729
Richard Smithda3f4fd2014-03-05 23:32:50 +00006730 // We can get here in two different ways:
6731 // 1) We're performing value-initialization, and should zero-initialize
6732 // the object, or
6733 // 2) We're performing default-initialization of an object with a trivial
6734 // constexpr default constructor, in which case we should start the
6735 // lifetimes of all the base subobjects (there can be no data member
6736 // subobjects in this case) per [basic.life]p1.
6737 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006738 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006739 }
6740
Craig Topper36250ad2014-05-12 05:36:57 +00006741 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006742 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006743
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006744 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006745 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006746
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006747 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006748 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006749 if (const MaterializeTemporaryExpr *ME
6750 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6751 return Visit(ME->GetTemporaryExpr());
6752
Richard Smithb8348f52016-05-12 22:16:28 +00006753 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006754 return false;
6755
Craig Topper5fc8fc22014-08-27 06:28:36 +00006756 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006757 return HandleConstructorCall(E, This, Args,
6758 cast<CXXConstructorDecl>(Definition), Info,
6759 Result);
6760}
6761
6762bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6763 const CXXInheritedCtorInitExpr *E) {
6764 if (!Info.CurrentCall) {
6765 assert(Info.checkingPotentialConstantExpression());
6766 return false;
6767 }
6768
6769 const CXXConstructorDecl *FD = E->getConstructor();
6770 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6771 return false;
6772
6773 const FunctionDecl *Definition = nullptr;
6774 auto Body = FD->getBody(Definition);
6775
6776 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6777 return false;
6778
6779 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006780 cast<CXXConstructorDecl>(Definition), Info,
6781 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006782}
6783
Richard Smithcc1b96d2013-06-12 22:31:48 +00006784bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6785 const CXXStdInitializerListExpr *E) {
6786 const ConstantArrayType *ArrayType =
6787 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6788
6789 LValue Array;
6790 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6791 return false;
6792
6793 // Get a pointer to the first element of the array.
6794 Array.addArray(Info, E, ArrayType);
6795
6796 // FIXME: Perform the checks on the field types in SemaInit.
6797 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6798 RecordDecl::field_iterator Field = Record->field_begin();
6799 if (Field == Record->field_end())
6800 return Error(E);
6801
6802 // Start pointer.
6803 if (!Field->getType()->isPointerType() ||
6804 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6805 ArrayType->getElementType()))
6806 return Error(E);
6807
6808 // FIXME: What if the initializer_list type has base classes, etc?
6809 Result = APValue(APValue::UninitStruct(), 0, 2);
6810 Array.moveInto(Result.getStructField(0));
6811
6812 if (++Field == Record->field_end())
6813 return Error(E);
6814
6815 if (Field->getType()->isPointerType() &&
6816 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6817 ArrayType->getElementType())) {
6818 // End pointer.
6819 if (!HandleLValueArrayAdjustment(Info, E, Array,
6820 ArrayType->getElementType(),
6821 ArrayType->getSize().getZExtValue()))
6822 return false;
6823 Array.moveInto(Result.getStructField(1));
6824 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6825 // Length.
6826 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6827 else
6828 return Error(E);
6829
6830 if (++Field != Record->field_end())
6831 return Error(E);
6832
6833 return true;
6834}
6835
Faisal Valic72a08c2017-01-09 03:02:53 +00006836bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6837 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6838 if (ClosureClass->isInvalidDecl()) return false;
6839
6840 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006841
Faisal Vali051e3a22017-02-16 04:12:21 +00006842 const size_t NumFields =
6843 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006844
6845 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6846 E->capture_init_end()) &&
6847 "The number of lambda capture initializers should equal the number of "
6848 "fields within the closure type");
6849
Faisal Vali051e3a22017-02-16 04:12:21 +00006850 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6851 // Iterate through all the lambda's closure object's fields and initialize
6852 // them.
6853 auto *CaptureInitIt = E->capture_init_begin();
6854 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6855 bool Success = true;
6856 for (const auto *Field : ClosureClass->fields()) {
6857 assert(CaptureInitIt != E->capture_init_end());
6858 // Get the initializer for this field
6859 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006860
Faisal Vali051e3a22017-02-16 04:12:21 +00006861 // If there is no initializer, either this is a VLA or an error has
6862 // occurred.
6863 if (!CurFieldInit)
6864 return Error(E);
6865
6866 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6867 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6868 if (!Info.keepEvaluatingAfterFailure())
6869 return false;
6870 Success = false;
6871 }
6872 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006873 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006874 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006875}
6876
Richard Smithd62306a2011-11-10 06:34:14 +00006877static bool EvaluateRecord(const Expr *E, const LValue &This,
6878 APValue &Result, EvalInfo &Info) {
6879 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006880 "can't evaluate expression as a record rvalue");
6881 return RecordExprEvaluator(Info, This, Result).Visit(E);
6882}
6883
6884//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006885// Temporary Evaluation
6886//
6887// Temporaries are represented in the AST as rvalues, but generally behave like
6888// lvalues. The full-object of which the temporary is a subobject is implicitly
6889// materialized so that a reference can bind to it.
6890//===----------------------------------------------------------------------===//
6891namespace {
6892class TemporaryExprEvaluator
6893 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6894public:
6895 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006896 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006897
6898 /// Visit an expression which constructs the value of this temporary.
6899 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006900 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6901 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006902 }
6903
6904 bool VisitCastExpr(const CastExpr *E) {
6905 switch (E->getCastKind()) {
6906 default:
6907 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6908
6909 case CK_ConstructorConversion:
6910 return VisitConstructExpr(E->getSubExpr());
6911 }
6912 }
6913 bool VisitInitListExpr(const InitListExpr *E) {
6914 return VisitConstructExpr(E);
6915 }
6916 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6917 return VisitConstructExpr(E);
6918 }
6919 bool VisitCallExpr(const CallExpr *E) {
6920 return VisitConstructExpr(E);
6921 }
Richard Smith513955c2014-12-17 19:24:30 +00006922 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6923 return VisitConstructExpr(E);
6924 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006925 bool VisitLambdaExpr(const LambdaExpr *E) {
6926 return VisitConstructExpr(E);
6927 }
Richard Smith027bf112011-11-17 22:56:20 +00006928};
6929} // end anonymous namespace
6930
6931/// Evaluate an expression of record type as a temporary.
6932static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006933 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006934 return TemporaryExprEvaluator(Info, Result).Visit(E);
6935}
6936
6937//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006938// Vector Evaluation
6939//===----------------------------------------------------------------------===//
6940
6941namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006942 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006943 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006944 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006945 public:
Mike Stump11289f42009-09-09 15:08:12 +00006946
Richard Smith2d406342011-10-22 21:10:00 +00006947 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6948 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006949
Craig Topper9798b932015-09-29 04:30:05 +00006950 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006951 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6952 // FIXME: remove this APValue copy.
6953 Result = APValue(V.data(), V.size());
6954 return true;
6955 }
Richard Smith2e312c82012-03-03 22:46:17 +00006956 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006957 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006958 Result = V;
6959 return true;
6960 }
Richard Smithfddd3842011-12-30 21:15:51 +00006961 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006962
Richard Smith2d406342011-10-22 21:10:00 +00006963 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006964 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006965 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006966 bool VisitInitListExpr(const InitListExpr *E);
6967 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006968 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006969 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006970 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006971 };
6972} // end anonymous namespace
6973
6974static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006975 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006976 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006977}
6978
George Burgess IV533ff002015-12-11 00:23:35 +00006979bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006980 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006981 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006982
Richard Smith161f09a2011-12-06 22:44:34 +00006983 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006984 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006985
Eli Friedmanc757de22011-03-25 00:43:55 +00006986 switch (E->getCastKind()) {
6987 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006988 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006989 if (SETy->isIntegerType()) {
6990 APSInt IntResult;
6991 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006992 return false;
6993 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006994 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006995 APFloat FloatResult(0.0);
6996 if (!EvaluateFloat(SE, FloatResult, Info))
6997 return false;
6998 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006999 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007000 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007001 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007002
7003 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007004 SmallVector<APValue, 4> Elts(NElts, Val);
7005 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007006 }
Eli Friedman803acb32011-12-22 03:51:45 +00007007 case CK_BitCast: {
7008 // Evaluate the operand into an APInt we can extract from.
7009 llvm::APInt SValInt;
7010 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7011 return false;
7012 // Extract the elements
7013 QualType EltTy = VTy->getElementType();
7014 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7015 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7016 SmallVector<APValue, 4> Elts;
7017 if (EltTy->isRealFloatingType()) {
7018 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007019 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007020 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007021 FloatEltSize = 80;
7022 for (unsigned i = 0; i < NElts; i++) {
7023 llvm::APInt Elt;
7024 if (BigEndian)
7025 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7026 else
7027 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007028 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007029 }
7030 } else if (EltTy->isIntegerType()) {
7031 for (unsigned i = 0; i < NElts; i++) {
7032 llvm::APInt Elt;
7033 if (BigEndian)
7034 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7035 else
7036 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7037 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7038 }
7039 } else {
7040 return Error(E);
7041 }
7042 return Success(Elts, E);
7043 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007044 default:
Richard Smith11562c52011-10-28 17:51:58 +00007045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007046 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007047}
7048
Richard Smith2d406342011-10-22 21:10:00 +00007049bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007050VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007051 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007052 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007053 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007054
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007055 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007056 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007057
Eli Friedmanb9c71292012-01-03 23:24:20 +00007058 // The number of initializers can be less than the number of
7059 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007060 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007061 // should be initialized with zeroes.
7062 unsigned CountInits = 0, CountElts = 0;
7063 while (CountElts < NumElements) {
7064 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007065 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007066 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007067 APValue v;
7068 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7069 return Error(E);
7070 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007071 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007072 Elements.push_back(v.getVectorElt(j));
7073 CountElts += vlen;
7074 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007075 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007076 if (CountInits < NumInits) {
7077 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007078 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007079 } else // trailing integer zero.
7080 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7081 Elements.push_back(APValue(sInt));
7082 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007083 } else {
7084 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007085 if (CountInits < NumInits) {
7086 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007087 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007088 } else // trailing float zero.
7089 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7090 Elements.push_back(APValue(f));
7091 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007092 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007093 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007094 }
Richard Smith2d406342011-10-22 21:10:00 +00007095 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007096}
7097
Richard Smith2d406342011-10-22 21:10:00 +00007098bool
Richard Smithfddd3842011-12-30 21:15:51 +00007099VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007100 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007101 QualType EltTy = VT->getElementType();
7102 APValue ZeroElement;
7103 if (EltTy->isIntegerType())
7104 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7105 else
7106 ZeroElement =
7107 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7108
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007109 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007110 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007111}
7112
Richard Smith2d406342011-10-22 21:10:00 +00007113bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007114 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007115 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007116}
7117
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007118//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007119// Array Evaluation
7120//===----------------------------------------------------------------------===//
7121
7122namespace {
7123 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007124 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007125 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007126 APValue &Result;
7127 public:
7128
Richard Smithd62306a2011-11-10 06:34:14 +00007129 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7130 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007131
7132 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007133 assert((V.isArray() || V.isLValue()) &&
7134 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007135 Result = V;
7136 return true;
7137 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007138
Richard Smithfddd3842011-12-30 21:15:51 +00007139 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007140 const ConstantArrayType *CAT =
7141 Info.Ctx.getAsConstantArrayType(E->getType());
7142 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007143 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007144
7145 Result = APValue(APValue::UninitArray(), 0,
7146 CAT->getSize().getZExtValue());
7147 if (!Result.hasArrayFiller()) return true;
7148
Richard Smithfddd3842011-12-30 21:15:51 +00007149 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007150 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007151 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007152 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007153 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007154 }
7155
Richard Smith52a980a2015-08-28 02:43:42 +00007156 bool VisitCallExpr(const CallExpr *E) {
7157 return handleCallExpr(E, Result, &This);
7158 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007159 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007160 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007161 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007162 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7163 const LValue &Subobject,
7164 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007165 };
7166} // end anonymous namespace
7167
Richard Smithd62306a2011-11-10 06:34:14 +00007168static bool EvaluateArray(const Expr *E, const LValue &This,
7169 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007170 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007171 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007172}
7173
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007174// Return true iff the given array filler may depend on the element index.
7175static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7176 // For now, just whitelist non-class value-initialization and initialization
7177 // lists comprised of them.
7178 if (isa<ImplicitValueInitExpr>(FillerExpr))
7179 return false;
7180 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7181 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7182 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7183 return true;
7184 }
7185 return false;
7186 }
7187 return true;
7188}
7189
Richard Smithf3e9e432011-11-07 09:22:26 +00007190bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7191 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7192 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007193 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007194
Richard Smithca2cfbf2011-12-22 01:07:19 +00007195 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7196 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007197 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007198 LValue LV;
7199 if (!EvaluateLValue(E->getInit(0), LV, Info))
7200 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007201 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007202 LV.moveInto(Val);
7203 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007204 }
7205
Richard Smith253c2a32012-01-27 01:14:48 +00007206 bool Success = true;
7207
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007208 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7209 "zero-initialized array shouldn't have any initialized elts");
7210 APValue Filler;
7211 if (Result.isArray() && Result.hasArrayFiller())
7212 Filler = Result.getArrayFiller();
7213
Richard Smith9543c5e2013-04-22 14:44:29 +00007214 unsigned NumEltsToInit = E->getNumInits();
7215 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007216 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007217
7218 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007219 // array element.
7220 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007221 NumEltsToInit = NumElts;
7222
Nicola Zaghen3538b392018-05-15 13:30:56 +00007223 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7224 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007225
Richard Smith9543c5e2013-04-22 14:44:29 +00007226 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007227
7228 // If the array was previously zero-initialized, preserve the
7229 // zero-initialized values.
7230 if (!Filler.isUninit()) {
7231 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7232 Result.getArrayInitializedElt(I) = Filler;
7233 if (Result.hasArrayFiller())
7234 Result.getArrayFiller() = Filler;
7235 }
7236
Richard Smithd62306a2011-11-10 06:34:14 +00007237 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007238 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007239 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7240 const Expr *Init =
7241 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007242 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007243 Info, Subobject, Init) ||
7244 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007245 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007246 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007247 return false;
7248 Success = false;
7249 }
Richard Smithd62306a2011-11-10 06:34:14 +00007250 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007251
Richard Smith9543c5e2013-04-22 14:44:29 +00007252 if (!Result.hasArrayFiller())
7253 return Success;
7254
7255 // If we get here, we have a trivial filler, which we can just evaluate
7256 // once and splat over the rest of the array elements.
7257 assert(FillerExpr && "no array filler for incomplete init list");
7258 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7259 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007260}
7261
Richard Smith410306b2016-12-12 02:53:20 +00007262bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7263 if (E->getCommonExpr() &&
7264 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7265 Info, E->getCommonExpr()->getSourceExpr()))
7266 return false;
7267
7268 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7269
7270 uint64_t Elements = CAT->getSize().getZExtValue();
7271 Result = APValue(APValue::UninitArray(), Elements, Elements);
7272
7273 LValue Subobject = This;
7274 Subobject.addArray(Info, E, CAT);
7275
7276 bool Success = true;
7277 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7278 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7279 Info, Subobject, E->getSubExpr()) ||
7280 !HandleLValueArrayAdjustment(Info, E, Subobject,
7281 CAT->getElementType(), 1)) {
7282 if (!Info.noteFailure())
7283 return false;
7284 Success = false;
7285 }
7286 }
7287
7288 return Success;
7289}
7290
Richard Smith027bf112011-11-17 22:56:20 +00007291bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007292 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7293}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007294
Richard Smith9543c5e2013-04-22 14:44:29 +00007295bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7296 const LValue &Subobject,
7297 APValue *Value,
7298 QualType Type) {
7299 bool HadZeroInit = !Value->isUninit();
7300
7301 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7302 unsigned N = CAT->getSize().getZExtValue();
7303
7304 // Preserve the array filler if we had prior zero-initialization.
7305 APValue Filler =
7306 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7307 : APValue();
7308
7309 *Value = APValue(APValue::UninitArray(), N, N);
7310
7311 if (HadZeroInit)
7312 for (unsigned I = 0; I != N; ++I)
7313 Value->getArrayInitializedElt(I) = Filler;
7314
7315 // Initialize the elements.
7316 LValue ArrayElt = Subobject;
7317 ArrayElt.addArray(Info, E, CAT);
7318 for (unsigned I = 0; I != N; ++I)
7319 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7320 CAT->getElementType()) ||
7321 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7322 CAT->getElementType(), 1))
7323 return false;
7324
7325 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007326 }
Richard Smith027bf112011-11-17 22:56:20 +00007327
Richard Smith9543c5e2013-04-22 14:44:29 +00007328 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007329 return Error(E);
7330
Richard Smithb8348f52016-05-12 22:16:28 +00007331 return RecordExprEvaluator(Info, Subobject, *Value)
7332 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007333}
7334
Richard Smithf3e9e432011-11-07 09:22:26 +00007335//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007336// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007337//
7338// As a GNU extension, we support casting pointers to sufficiently-wide integer
7339// types and back in constant folding. Integer values are thus represented
7340// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007341//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007342
7343namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007344class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007345 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007346 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007347public:
Richard Smith2e312c82012-03-03 22:46:17 +00007348 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007349 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007350
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007351 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007352 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007353 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007354 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007355 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007356 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007357 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007358 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007359 return true;
7360 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007361 bool Success(const llvm::APSInt &SI, const Expr *E) {
7362 return Success(SI, E, Result);
7363 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007364
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007365 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007366 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007367 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007368 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007369 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007370 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007371 Result.getInt().setIsUnsigned(
7372 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007373 return true;
7374 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007375 bool Success(const llvm::APInt &I, const Expr *E) {
7376 return Success(I, E, Result);
7377 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007378
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007379 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007380 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007381 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007382 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007383 return true;
7384 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007385 bool Success(uint64_t Value, const Expr *E) {
7386 return Success(Value, E, Result);
7387 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007388
Ken Dyckdbc01912011-03-11 02:13:43 +00007389 bool Success(CharUnits Size, const Expr *E) {
7390 return Success(Size.getQuantity(), E);
7391 }
7392
Richard Smith2e312c82012-03-03 22:46:17 +00007393 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007394 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007395 Result = V;
7396 return true;
7397 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007398 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007399 }
Mike Stump11289f42009-09-09 15:08:12 +00007400
Richard Smithfddd3842011-12-30 21:15:51 +00007401 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007402
Peter Collingbournee9200682011-05-13 03:29:01 +00007403 //===--------------------------------------------------------------------===//
7404 // Visitor Methods
7405 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007406
Fangrui Song407659a2018-11-30 23:41:18 +00007407 bool VisitConstantExpr(const ConstantExpr *E);
7408
Chris Lattner7174bf32008-07-12 00:38:25 +00007409 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007410 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007411 }
7412 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007413 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007414 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007415
7416 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7417 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007418 if (CheckReferencedDecl(E, E->getDecl()))
7419 return true;
7420
7421 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007422 }
7423 bool VisitMemberExpr(const MemberExpr *E) {
7424 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007425 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007426 return true;
7427 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007428
7429 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007430 }
7431
Peter Collingbournee9200682011-05-13 03:29:01 +00007432 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007433 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007434 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007435 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007436 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007437
Peter Collingbournee9200682011-05-13 03:29:01 +00007438 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007439 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007440
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007441 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007442 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007443 }
Mike Stump11289f42009-09-09 15:08:12 +00007444
Ted Kremeneke65b0862012-03-06 20:05:56 +00007445 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7446 return Success(E->getValue(), E);
7447 }
Richard Smith410306b2016-12-12 02:53:20 +00007448
7449 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7450 if (Info.ArrayInitIndex == uint64_t(-1)) {
7451 // We were asked to evaluate this subexpression independent of the
7452 // enclosing ArrayInitLoopExpr. We can't do that.
7453 Info.FFDiag(E);
7454 return false;
7455 }
7456 return Success(Info.ArrayInitIndex, E);
7457 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007458
Richard Smith4ce706a2011-10-11 21:43:33 +00007459 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007460 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007461 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007462 }
7463
Douglas Gregor29c42f22012-02-24 07:38:34 +00007464 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7465 return Success(E->getValue(), E);
7466 }
7467
John Wiegley6242b6a2011-04-28 00:16:57 +00007468 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7469 return Success(E->getValue(), E);
7470 }
7471
John Wiegleyf9f65842011-04-25 06:54:41 +00007472 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7473 return Success(E->getValue(), E);
7474 }
7475
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007476 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007477 bool VisitUnaryImag(const UnaryOperator *E);
7478
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007479 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007480 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007481
Eli Friedman4e7a2412009-02-27 04:45:43 +00007482 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007483};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007484
7485class FixedPointExprEvaluator
7486 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7487 APValue &Result;
7488
7489 public:
7490 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7491 : ExprEvaluatorBaseTy(info), Result(result) {}
7492
7493 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7494 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7495 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7496 "Invalid evaluation result.");
7497 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7498 "Invalid evaluation result.");
7499 Result = APValue(SI);
7500 return true;
7501 }
7502 bool Success(const llvm::APSInt &SI, const Expr *E) {
7503 return Success(SI, E, Result);
7504 }
7505
7506 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7507 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7508 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7509 "Invalid evaluation result.");
7510 Result = APValue(APSInt(I));
7511 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7512 return true;
7513 }
7514 bool Success(const llvm::APInt &I, const Expr *E) {
7515 return Success(I, E, Result);
7516 }
7517
7518 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7519 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7520 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7521 return true;
7522 }
7523 bool Success(uint64_t Value, const Expr *E) {
7524 return Success(Value, E, Result);
7525 }
7526
7527 bool Success(CharUnits Size, const Expr *E) {
7528 return Success(Size.getQuantity(), E);
7529 }
7530
7531 bool Success(const APValue &V, const Expr *E) {
7532 if (V.isLValue() || V.isAddrLabelDiff()) {
7533 Result = V;
7534 return true;
7535 }
7536 return Success(V.getInt(), E);
7537 }
7538
7539 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7540
7541 //===--------------------------------------------------------------------===//
7542 // Visitor Methods
7543 //===--------------------------------------------------------------------===//
7544
7545 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7546 return Success(E->getValue(), E);
7547 }
7548
7549 bool VisitUnaryOperator(const UnaryOperator *E);
7550};
Chris Lattner05706e882008-07-11 18:11:29 +00007551} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007552
Richard Smith11562c52011-10-28 17:51:58 +00007553/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7554/// produce either the integer value or a pointer.
7555///
7556/// GCC has a heinous extension which folds casts between pointer types and
7557/// pointer-sized integral types. We support this by allowing the evaluation of
7558/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7559/// Some simple arithmetic on such values is supported (they are treated much
7560/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007561static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007562 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007563 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007564 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007565}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007566
Richard Smithf57d8cb2011-12-09 22:58:01 +00007567static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007568 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007569 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007570 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007571 if (!Val.isInt()) {
7572 // FIXME: It would be better to produce the diagnostic for casting
7573 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007574 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007575 return false;
7576 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007577 Result = Val.getInt();
7578 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007579}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007580
Richard Smithf57d8cb2011-12-09 22:58:01 +00007581/// Check whether the given declaration can be directly converted to an integral
7582/// rvalue. If not, no diagnostic is produced; there are other things we can
7583/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007584bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007585 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007586 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007587 // Check for signedness/width mismatches between E type and ECD value.
7588 bool SameSign = (ECD->getInitVal().isSigned()
7589 == E->getType()->isSignedIntegerOrEnumerationType());
7590 bool SameWidth = (ECD->getInitVal().getBitWidth()
7591 == Info.Ctx.getIntWidth(E->getType()));
7592 if (SameSign && SameWidth)
7593 return Success(ECD->getInitVal(), E);
7594 else {
7595 // Get rid of mismatch (otherwise Success assertions will fail)
7596 // by computing a new value matching the type of E.
7597 llvm::APSInt Val = ECD->getInitVal();
7598 if (!SameSign)
7599 Val.setIsSigned(!ECD->getInitVal().isSigned());
7600 if (!SameWidth)
7601 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7602 return Success(Val, E);
7603 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007604 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007605 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007606}
7607
Richard Smith08b682b2018-05-23 21:18:00 +00007608/// Values returned by __builtin_classify_type, chosen to match the values
7609/// produced by GCC's builtin.
7610enum class GCCTypeClass {
7611 None = -1,
7612 Void = 0,
7613 Integer = 1,
7614 // GCC reserves 2 for character types, but instead classifies them as
7615 // integers.
7616 Enum = 3,
7617 Bool = 4,
7618 Pointer = 5,
7619 // GCC reserves 6 for references, but appears to never use it (because
7620 // expressions never have reference type, presumably).
7621 PointerToDataMember = 7,
7622 RealFloat = 8,
7623 Complex = 9,
7624 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7625 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7626 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7627 // uses 12 for that purpose, same as for a class or struct. Maybe it
7628 // internally implements a pointer to member as a struct? Who knows.
7629 PointerToMemberFunction = 12, // Not a bug, see above.
7630 ClassOrStruct = 12,
7631 Union = 13,
7632 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7633 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7634 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7635 // literals.
7636};
7637
Chris Lattner86ee2862008-10-06 06:40:35 +00007638/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7639/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007640static GCCTypeClass
7641EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7642 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007643
Richard Smith08b682b2018-05-23 21:18:00 +00007644 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007645 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7646
7647 switch (CanTy->getTypeClass()) {
7648#define TYPE(ID, BASE)
7649#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7650#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7651#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7652#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007653 case Type::Auto:
7654 case Type::DeducedTemplateSpecialization:
7655 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007656
7657 case Type::Builtin:
7658 switch (BT->getKind()) {
7659#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007660#define SIGNED_TYPE(ID, SINGLETON_ID) \
7661 case BuiltinType::ID: return GCCTypeClass::Integer;
7662#define FLOATING_TYPE(ID, SINGLETON_ID) \
7663 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7664#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7665 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007666#include "clang/AST/BuiltinTypes.def"
7667 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007668 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007669
7670 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007671 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007672
Richard Smith08b682b2018-05-23 21:18:00 +00007673 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007674 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007675 case BuiltinType::WChar_U:
7676 case BuiltinType::Char8:
7677 case BuiltinType::Char16:
7678 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007679 case BuiltinType::UShort:
7680 case BuiltinType::UInt:
7681 case BuiltinType::ULong:
7682 case BuiltinType::ULongLong:
7683 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007684 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007685
Leonard Chanf921d852018-06-04 16:07:52 +00007686 case BuiltinType::UShortAccum:
7687 case BuiltinType::UAccum:
7688 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007689 case BuiltinType::UShortFract:
7690 case BuiltinType::UFract:
7691 case BuiltinType::ULongFract:
7692 case BuiltinType::SatUShortAccum:
7693 case BuiltinType::SatUAccum:
7694 case BuiltinType::SatULongAccum:
7695 case BuiltinType::SatUShortFract:
7696 case BuiltinType::SatUFract:
7697 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007698 return GCCTypeClass::None;
7699
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007700 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007701
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007702 case BuiltinType::ObjCId:
7703 case BuiltinType::ObjCClass:
7704 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007705#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7706 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007707#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007708#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7709 case BuiltinType::Id:
7710#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007711 case BuiltinType::OCLSampler:
7712 case BuiltinType::OCLEvent:
7713 case BuiltinType::OCLClkEvent:
7714 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007715 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007716 return GCCTypeClass::None;
7717
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007718 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007719 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007720 };
Richard Smith08b682b2018-05-23 21:18:00 +00007721 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007722
7723 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007724 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007725
7726 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007727 case Type::ConstantArray:
7728 case Type::VariableArray:
7729 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007730 case Type::FunctionNoProto:
7731 case Type::FunctionProto:
7732 return GCCTypeClass::Pointer;
7733
7734 case Type::MemberPointer:
7735 return CanTy->isMemberDataPointerType()
7736 ? GCCTypeClass::PointerToDataMember
7737 : GCCTypeClass::PointerToMemberFunction;
7738
7739 case Type::Complex:
7740 return GCCTypeClass::Complex;
7741
7742 case Type::Record:
7743 return CanTy->isUnionType() ? GCCTypeClass::Union
7744 : GCCTypeClass::ClassOrStruct;
7745
7746 case Type::Atomic:
7747 // GCC classifies _Atomic T the same as T.
7748 return EvaluateBuiltinClassifyType(
7749 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007750
7751 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007752 case Type::Vector:
7753 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007754 case Type::ObjCObject:
7755 case Type::ObjCInterface:
7756 case Type::ObjCObjectPointer:
7757 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007758 // GCC classifies vectors as None. We follow its lead and classify all
7759 // other types that don't fit into the regular classification the same way.
7760 return GCCTypeClass::None;
7761
7762 case Type::LValueReference:
7763 case Type::RValueReference:
7764 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007765 }
7766
Richard Smith08b682b2018-05-23 21:18:00 +00007767 llvm_unreachable("unexpected type class");
7768}
7769
7770/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7771/// as GCC.
7772static GCCTypeClass
7773EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7774 // If no argument was supplied, default to None. This isn't
7775 // ideal, however it is what gcc does.
7776 if (E->getNumArgs() == 0)
7777 return GCCTypeClass::None;
7778
7779 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7780 // being an ICE, but still folds it to a constant using the type of the first
7781 // argument.
7782 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007783}
7784
Richard Smith5fab0c92011-12-28 19:48:30 +00007785/// EvaluateBuiltinConstantPForLValue - Determine the result of
7786/// __builtin_constant_p when applied to the given lvalue.
7787///
7788/// An lvalue is only "constant" if it is a pointer or reference to the first
7789/// character of a string literal.
7790template<typename LValue>
7791static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007792 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007793 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7794}
7795
7796/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7797/// GCC as we can manage.
7798static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7799 QualType ArgType = Arg->getType();
7800
7801 // __builtin_constant_p always has one operand. The rules which gcc follows
7802 // are not precisely documented, but are as follows:
7803 //
7804 // - If the operand is of integral, floating, complex or enumeration type,
7805 // and can be folded to a known value of that type, it returns 1.
7806 // - If the operand and can be folded to a pointer to the first character
7807 // of a string literal (or such a pointer cast to an integral type), it
7808 // returns 1.
7809 //
7810 // Otherwise, it returns 0.
7811 //
7812 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7813 // its support for this does not currently work.
7814 if (ArgType->isIntegralOrEnumerationType()) {
7815 Expr::EvalResult Result;
7816 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7817 return false;
7818
7819 APValue &V = Result.Val;
7820 if (V.getKind() == APValue::Int)
7821 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007822 if (V.getKind() == APValue::LValue)
7823 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007824 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7825 return Arg->isEvaluatable(Ctx);
7826 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7827 LValue LV;
7828 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007829 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007830 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7831 : EvaluatePointer(Arg, LV, Info)) &&
7832 !Status.HasSideEffects)
7833 return EvaluateBuiltinConstantPForLValue(LV);
7834 }
7835
7836 // Anything else isn't considered to be sufficiently constant.
7837 return false;
7838}
7839
John McCall95007602010-05-10 23:27:23 +00007840/// Retrieves the "underlying object type" of the given expression,
7841/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007842static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007843 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7844 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007845 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007846 } else if (const Expr *E = B.get<const Expr*>()) {
7847 if (isa<CompoundLiteralExpr>(E))
7848 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007849 }
7850
7851 return QualType();
7852}
7853
George Burgess IV3a03fab2015-09-04 21:28:13 +00007854/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007855/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007856/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007857/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7858///
7859/// Always returns an RValue with a pointer representation.
7860static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7861 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7862
7863 auto *NoParens = E->IgnoreParens();
7864 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007865 if (Cast == nullptr)
7866 return NoParens;
7867
7868 // We only conservatively allow a few kinds of casts, because this code is
7869 // inherently a simple solution that seeks to support the common case.
7870 auto CastKind = Cast->getCastKind();
7871 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7872 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007873 return NoParens;
7874
7875 auto *SubExpr = Cast->getSubExpr();
7876 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7877 return NoParens;
7878 return ignorePointerCastsAndParens(SubExpr);
7879}
7880
George Burgess IVa51c4072015-10-16 01:49:01 +00007881/// Checks to see if the given LValue's Designator is at the end of the LValue's
7882/// record layout. e.g.
7883/// struct { struct { int a, b; } fst, snd; } obj;
7884/// obj.fst // no
7885/// obj.snd // yes
7886/// obj.fst.a // no
7887/// obj.fst.b // no
7888/// obj.snd.a // no
7889/// obj.snd.b // yes
7890///
7891/// Please note: this function is specialized for how __builtin_object_size
7892/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007893///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007894/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7895/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007896static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7897 assert(!LVal.Designator.Invalid);
7898
George Burgess IV4168d752016-06-27 19:40:41 +00007899 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7900 const RecordDecl *Parent = FD->getParent();
7901 Invalid = Parent->isInvalidDecl();
7902 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007903 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007904 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007905 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7906 };
7907
7908 auto &Base = LVal.getLValueBase();
7909 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7910 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007911 bool Invalid;
7912 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7913 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007914 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007915 for (auto *FD : IFD->chain()) {
7916 bool Invalid;
7917 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7918 return Invalid;
7919 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007920 }
7921 }
7922
George Burgess IVe3763372016-12-22 02:50:20 +00007923 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007924 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007925 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007926 // If we don't know the array bound, conservatively assume we're looking at
7927 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007928 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007929 if (BaseType->isIncompleteArrayType())
7930 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7931 else
7932 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007933 }
7934
7935 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7936 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007937 if (BaseType->isArrayType()) {
7938 // Because __builtin_object_size treats arrays as objects, we can ignore
7939 // the index iff this is the last array in the Designator.
7940 if (I + 1 == E)
7941 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007942 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7943 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007944 if (Index + 1 != CAT->getSize())
7945 return false;
7946 BaseType = CAT->getElementType();
7947 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007948 const auto *CT = BaseType->castAs<ComplexType>();
7949 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007950 if (Index != 1)
7951 return false;
7952 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007953 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007954 bool Invalid;
7955 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7956 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007957 BaseType = FD->getType();
7958 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007959 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007960 return false;
7961 }
7962 }
7963 return true;
7964}
7965
George Burgess IVe3763372016-12-22 02:50:20 +00007966/// Tests to see if the LValue has a user-specified designator (that isn't
7967/// necessarily valid). Note that this always returns 'true' if the LValue has
7968/// an unsized array as its first designator entry, because there's currently no
7969/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007970static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007971 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007972 return false;
7973
George Burgess IVe3763372016-12-22 02:50:20 +00007974 if (!LVal.Designator.Entries.empty())
7975 return LVal.Designator.isMostDerivedAnUnsizedArray();
7976
George Burgess IVa51c4072015-10-16 01:49:01 +00007977 if (!LVal.InvalidBase)
7978 return true;
7979
George Burgess IVe3763372016-12-22 02:50:20 +00007980 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7981 // the LValueBase.
7982 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7983 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007984}
7985
George Burgess IVe3763372016-12-22 02:50:20 +00007986/// Attempts to detect a user writing into a piece of memory that's impossible
7987/// to figure out the size of by just using types.
7988static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7989 const SubobjectDesignator &Designator = LVal.Designator;
7990 // Notes:
7991 // - Users can only write off of the end when we have an invalid base. Invalid
7992 // bases imply we don't know where the memory came from.
7993 // - We used to be a bit more aggressive here; we'd only be conservative if
7994 // the array at the end was flexible, or if it had 0 or 1 elements. This
7995 // broke some common standard library extensions (PR30346), but was
7996 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7997 // with some sort of whitelist. OTOH, it seems that GCC is always
7998 // conservative with the last element in structs (if it's an array), so our
7999 // current behavior is more compatible than a whitelisting approach would
8000 // be.
8001 return LVal.InvalidBase &&
8002 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8003 Designator.MostDerivedIsArrayElement &&
8004 isDesignatorAtObjectEnd(Ctx, LVal);
8005}
8006
8007/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8008/// Fails if the conversion would cause loss of precision.
8009static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8010 CharUnits &Result) {
8011 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8012 if (Int.ugt(CharUnitsMax))
8013 return false;
8014 Result = CharUnits::fromQuantity(Int.getZExtValue());
8015 return true;
8016}
8017
8018/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8019/// determine how many bytes exist from the beginning of the object to either
8020/// the end of the current subobject, or the end of the object itself, depending
8021/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008022///
George Burgess IVe3763372016-12-22 02:50:20 +00008023/// If this returns false, the value of Result is undefined.
8024static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8025 unsigned Type, const LValue &LVal,
8026 CharUnits &EndOffset) {
8027 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008028
George Burgess IV7fb7e362017-01-03 23:35:19 +00008029 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8030 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8031 return false;
8032 return HandleSizeof(Info, ExprLoc, Ty, Result);
8033 };
8034
George Burgess IVe3763372016-12-22 02:50:20 +00008035 // We want to evaluate the size of the entire object. This is a valid fallback
8036 // for when Type=1 and the designator is invalid, because we're asked for an
8037 // upper-bound.
8038 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8039 // Type=3 wants a lower bound, so we can't fall back to this.
8040 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008041 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008042
8043 llvm::APInt APEndOffset;
8044 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8045 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8046 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8047
8048 if (LVal.InvalidBase)
8049 return false;
8050
8051 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008052 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008053 }
8054
George Burgess IVe3763372016-12-22 02:50:20 +00008055 // We want to evaluate the size of a subobject.
8056 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008057
8058 // The following is a moderately common idiom in C:
8059 //
8060 // struct Foo { int a; char c[1]; };
8061 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8062 // strcpy(&F->c[0], Bar);
8063 //
George Burgess IVe3763372016-12-22 02:50:20 +00008064 // In order to not break too much legacy code, we need to support it.
8065 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8066 // If we can resolve this to an alloc_size call, we can hand that back,
8067 // because we know for certain how many bytes there are to write to.
8068 llvm::APInt APEndOffset;
8069 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8070 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8071 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8072
8073 // If we cannot determine the size of the initial allocation, then we can't
8074 // given an accurate upper-bound. However, we are still able to give
8075 // conservative lower-bounds for Type=3.
8076 if (Type == 1)
8077 return false;
8078 }
8079
8080 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008081 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008082 return false;
8083
George Burgess IVe3763372016-12-22 02:50:20 +00008084 // According to the GCC documentation, we want the size of the subobject
8085 // denoted by the pointer. But that's not quite right -- what we actually
8086 // want is the size of the immediately-enclosing array, if there is one.
8087 int64_t ElemsRemaining;
8088 if (Designator.MostDerivedIsArrayElement &&
8089 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8090 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8091 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8092 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8093 } else {
8094 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8095 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008096
George Burgess IVe3763372016-12-22 02:50:20 +00008097 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8098 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008099}
8100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008101/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008102/// returns true and stores the result in @p Size.
8103///
8104/// If @p WasError is non-null, this will report whether the failure to evaluate
8105/// is to be treated as an Error in IntExprEvaluator.
8106static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8107 EvalInfo &Info, uint64_t &Size) {
8108 // Determine the denoted object.
8109 LValue LVal;
8110 {
8111 // The operand of __builtin_object_size is never evaluated for side-effects.
8112 // If there are any, but we can determine the pointed-to object anyway, then
8113 // ignore the side-effects.
8114 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008115 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008116
8117 if (E->isGLValue()) {
8118 // It's possible for us to be given GLValues if we're called via
8119 // Expr::tryEvaluateObjectSize.
8120 APValue RVal;
8121 if (!EvaluateAsRValue(Info, E, RVal))
8122 return false;
8123 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008124 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8125 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008126 return false;
8127 }
8128
8129 // If we point to before the start of the object, there are no accessible
8130 // bytes.
8131 if (LVal.getLValueOffset().isNegative()) {
8132 Size = 0;
8133 return true;
8134 }
8135
8136 CharUnits EndOffset;
8137 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8138 return false;
8139
8140 // If we've fallen outside of the end offset, just pretend there's nothing to
8141 // write to/read from.
8142 if (EndOffset <= LVal.getLValueOffset())
8143 Size = 0;
8144 else
8145 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8146 return true;
John McCall95007602010-05-10 23:27:23 +00008147}
8148
Fangrui Song407659a2018-11-30 23:41:18 +00008149bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8150 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8151 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8152}
8153
Peter Collingbournee9200682011-05-13 03:29:01 +00008154bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008155 if (unsigned BuiltinOp = E->getBuiltinCallee())
8156 return VisitBuiltinCallExpr(E, BuiltinOp);
8157
8158 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8159}
8160
8161bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8162 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008163 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008164 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008165 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008166
8167 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008168 // The type was checked when we built the expression.
8169 unsigned Type =
8170 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8171 assert(Type <= 3 && "unexpected type");
8172
George Burgess IVe3763372016-12-22 02:50:20 +00008173 uint64_t Size;
8174 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8175 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008176
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008177 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008178 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008179
Richard Smith01ade172012-05-23 04:13:20 +00008180 // Expression had no side effects, but we couldn't statically determine the
8181 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008182 switch (Info.EvalMode) {
8183 case EvalInfo::EM_ConstantExpression:
8184 case EvalInfo::EM_PotentialConstantExpression:
8185 case EvalInfo::EM_ConstantFold:
8186 case EvalInfo::EM_EvaluateForOverflow:
8187 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008188 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008189 return Error(E);
8190 case EvalInfo::EM_ConstantExpressionUnevaluated:
8191 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008192 // Reduce it to a constant now.
8193 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008194 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008195
8196 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008197 }
8198
Tim Northover314fbfa2018-11-02 13:14:11 +00008199 case Builtin::BI__builtin_os_log_format_buffer_size: {
8200 analyze_os_log::OSLogBufferLayout Layout;
8201 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8202 return Success(Layout.size().getQuantity(), E);
8203 }
8204
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008205 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008206 case Builtin::BI__builtin_bswap32:
8207 case Builtin::BI__builtin_bswap64: {
8208 APSInt Val;
8209 if (!EvaluateInteger(E->getArg(0), Val, Info))
8210 return false;
8211
8212 return Success(Val.byteSwap(), E);
8213 }
8214
Richard Smith8889a3d2013-06-13 06:26:32 +00008215 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008216 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008217
Craig Topperf95a6d92018-08-08 22:31:12 +00008218 case Builtin::BI__builtin_clrsb:
8219 case Builtin::BI__builtin_clrsbl:
8220 case Builtin::BI__builtin_clrsbll: {
8221 APSInt Val;
8222 if (!EvaluateInteger(E->getArg(0), Val, Info))
8223 return false;
8224
8225 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8226 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008227
Richard Smith80b3c8e2013-06-13 05:04:16 +00008228 case Builtin::BI__builtin_clz:
8229 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008230 case Builtin::BI__builtin_clzll:
8231 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008232 APSInt Val;
8233 if (!EvaluateInteger(E->getArg(0), Val, Info))
8234 return false;
8235 if (!Val)
8236 return Error(E);
8237
8238 return Success(Val.countLeadingZeros(), E);
8239 }
8240
Fangrui Song407659a2018-11-30 23:41:18 +00008241 case Builtin::BI__builtin_constant_p: {
8242 auto Arg = E->getArg(0);
8243 if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8244 return Success(true, E);
8245 auto ArgTy = Arg->IgnoreImplicit()->getType();
8246 if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8247 !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8248 // We can delay calculation of __builtin_constant_p until after
8249 // inlining. Note: This diagnostic won't be shown to the user.
8250 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Bill Wendling2a81f662018-12-01 08:29:36 +00008251 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008252 }
8253 return Success(false, E);
8254 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008255
Richard Smith80b3c8e2013-06-13 05:04:16 +00008256 case Builtin::BI__builtin_ctz:
8257 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008258 case Builtin::BI__builtin_ctzll:
8259 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008260 APSInt Val;
8261 if (!EvaluateInteger(E->getArg(0), Val, Info))
8262 return false;
8263 if (!Val)
8264 return Error(E);
8265
8266 return Success(Val.countTrailingZeros(), E);
8267 }
8268
Richard Smith8889a3d2013-06-13 06:26:32 +00008269 case Builtin::BI__builtin_eh_return_data_regno: {
8270 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8271 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8272 return Success(Operand, E);
8273 }
8274
8275 case Builtin::BI__builtin_expect:
8276 return Visit(E->getArg(0));
8277
8278 case Builtin::BI__builtin_ffs:
8279 case Builtin::BI__builtin_ffsl:
8280 case Builtin::BI__builtin_ffsll: {
8281 APSInt Val;
8282 if (!EvaluateInteger(E->getArg(0), Val, Info))
8283 return false;
8284
8285 unsigned N = Val.countTrailingZeros();
8286 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8287 }
8288
8289 case Builtin::BI__builtin_fpclassify: {
8290 APFloat Val(0.0);
8291 if (!EvaluateFloat(E->getArg(5), Val, Info))
8292 return false;
8293 unsigned Arg;
8294 switch (Val.getCategory()) {
8295 case APFloat::fcNaN: Arg = 0; break;
8296 case APFloat::fcInfinity: Arg = 1; break;
8297 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8298 case APFloat::fcZero: Arg = 4; break;
8299 }
8300 return Visit(E->getArg(Arg));
8301 }
8302
8303 case Builtin::BI__builtin_isinf_sign: {
8304 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008305 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008306 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8307 }
8308
Richard Smithea3019d2013-10-15 19:07:14 +00008309 case Builtin::BI__builtin_isinf: {
8310 APFloat Val(0.0);
8311 return EvaluateFloat(E->getArg(0), Val, Info) &&
8312 Success(Val.isInfinity() ? 1 : 0, E);
8313 }
8314
8315 case Builtin::BI__builtin_isfinite: {
8316 APFloat Val(0.0);
8317 return EvaluateFloat(E->getArg(0), Val, Info) &&
8318 Success(Val.isFinite() ? 1 : 0, E);
8319 }
8320
8321 case Builtin::BI__builtin_isnan: {
8322 APFloat Val(0.0);
8323 return EvaluateFloat(E->getArg(0), Val, Info) &&
8324 Success(Val.isNaN() ? 1 : 0, E);
8325 }
8326
8327 case Builtin::BI__builtin_isnormal: {
8328 APFloat Val(0.0);
8329 return EvaluateFloat(E->getArg(0), Val, Info) &&
8330 Success(Val.isNormal() ? 1 : 0, E);
8331 }
8332
Richard Smith8889a3d2013-06-13 06:26:32 +00008333 case Builtin::BI__builtin_parity:
8334 case Builtin::BI__builtin_parityl:
8335 case Builtin::BI__builtin_parityll: {
8336 APSInt Val;
8337 if (!EvaluateInteger(E->getArg(0), Val, Info))
8338 return false;
8339
8340 return Success(Val.countPopulation() % 2, E);
8341 }
8342
Richard Smith80b3c8e2013-06-13 05:04:16 +00008343 case Builtin::BI__builtin_popcount:
8344 case Builtin::BI__builtin_popcountl:
8345 case Builtin::BI__builtin_popcountll: {
8346 APSInt Val;
8347 if (!EvaluateInteger(E->getArg(0), Val, Info))
8348 return false;
8349
8350 return Success(Val.countPopulation(), E);
8351 }
8352
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008353 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008354 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008355 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008356 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008357 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008358 << /*isConstexpr*/0 << /*isConstructor*/0
8359 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008360 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008361 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008362 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008363 case Builtin::BI__builtin_strlen:
8364 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008365 // As an extension, we support __builtin_strlen() as a constant expression,
8366 // and support folding strlen() to a constant.
8367 LValue String;
8368 if (!EvaluatePointer(E->getArg(0), String, Info))
8369 return false;
8370
Richard Smith8110c9d2016-11-29 19:45:17 +00008371 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8372
Richard Smithe6c19f22013-11-15 02:10:04 +00008373 // Fast path: if it's a string literal, search the string value.
8374 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8375 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008376 // The string literal may have embedded null characters. Find the first
8377 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008378 StringRef Str = S->getBytes();
8379 int64_t Off = String.Offset.getQuantity();
8380 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008381 S->getCharByteWidth() == 1 &&
8382 // FIXME: Add fast-path for wchar_t too.
8383 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008384 Str = Str.substr(Off);
8385
8386 StringRef::size_type Pos = Str.find(0);
8387 if (Pos != StringRef::npos)
8388 Str = Str.substr(0, Pos);
8389
8390 return Success(Str.size(), E);
8391 }
8392
8393 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008394 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008395
8396 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008397 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8398 APValue Char;
8399 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8400 !Char.isInt())
8401 return false;
8402 if (!Char.getInt())
8403 return Success(Strlen, E);
8404 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8405 return false;
8406 }
8407 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008408
Richard Smithe151bab2016-11-11 23:43:35 +00008409 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008410 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008411 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008412 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008413 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008414 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008415 // A call to strlen is not a constant expression.
8416 if (Info.getLangOpts().CPlusPlus11)
8417 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8418 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008419 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008420 else
8421 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008422 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008423 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008424 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008425 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008426 case Builtin::BI__builtin_wcsncmp:
8427 case Builtin::BI__builtin_memcmp:
8428 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008429 LValue String1, String2;
8430 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8431 !EvaluatePointer(E->getArg(1), String2, Info))
8432 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008433
Richard Smithe151bab2016-11-11 23:43:35 +00008434 uint64_t MaxLength = uint64_t(-1);
8435 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008436 BuiltinOp != Builtin::BIwcscmp &&
8437 BuiltinOp != Builtin::BI__builtin_strcmp &&
8438 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008439 APSInt N;
8440 if (!EvaluateInteger(E->getArg(2), N, Info))
8441 return false;
8442 MaxLength = N.getExtValue();
8443 }
Hubert Tong147b7432018-12-12 16:53:43 +00008444
8445 // Empty substrings compare equal by definition.
8446 if (MaxLength == 0u)
8447 return Success(0, E);
8448
8449 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8450 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8451 String1.Designator.Invalid || String2.Designator.Invalid)
8452 return false;
8453
8454 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8455 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8456
8457 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
8458 BuiltinOp == Builtin::BI__builtin_memcmp;
8459
8460 assert(IsRawByte ||
8461 (Info.Ctx.hasSameUnqualifiedType(
8462 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8463 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8464
8465 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8466 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8467 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8468 Char1.isInt() && Char2.isInt();
8469 };
8470 const auto &AdvanceElems = [&] {
8471 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8472 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8473 };
8474
8475 if (IsRawByte) {
8476 uint64_t BytesRemaining = MaxLength;
8477 // Pointers to const void may point to objects of incomplete type.
8478 if (CharTy1->isIncompleteType()) {
8479 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8480 return false;
8481 }
8482 if (CharTy2->isIncompleteType()) {
8483 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8484 return false;
8485 }
8486 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8487 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8488 // Give up on comparing between elements with disparate widths.
8489 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8490 return false;
8491 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8492 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8493 "following loop considers at least one element");
8494 while (true) {
8495 APValue Char1, Char2;
8496 if (!ReadCurElems(Char1, Char2))
8497 return false;
8498 // We have compatible in-memory widths, but a possible type and
8499 // (for `bool`) internal representation mismatch.
8500 // Assuming two's complement representation, including 0 for `false` and
8501 // 1 for `true`, we can check an appropriate number of elements for
8502 // equality even if they are not byte-sized.
8503 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8504 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8505 if (Char1InMem.ne(Char2InMem)) {
8506 // If the elements are byte-sized, then we can produce a three-way
8507 // comparison result in a straightforward manner.
8508 if (BytesPerElement == 1u) {
8509 // memcmp always compares unsigned chars.
8510 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8511 }
8512 // The result is byte-order sensitive, and we have multibyte elements.
8513 // FIXME: We can compare the remaining bytes in the correct order.
8514 return false;
8515 }
8516 if (!AdvanceElems())
8517 return false;
8518 if (BytesRemaining <= BytesPerElement)
8519 break;
8520 BytesRemaining -= BytesPerElement;
8521 }
8522 // Enough elements are equal to account for the memcmp limit.
8523 return Success(0, E);
8524 }
8525
Richard Smithe151bab2016-11-11 23:43:35 +00008526 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008527 BuiltinOp != Builtin::BIwmemcmp &&
8528 BuiltinOp != Builtin::BI__builtin_memcmp &&
8529 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008530 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8531 BuiltinOp == Builtin::BIwcsncmp ||
8532 BuiltinOp == Builtin::BIwmemcmp ||
8533 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8534 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8535 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008536
Richard Smithe151bab2016-11-11 23:43:35 +00008537 for (; MaxLength; --MaxLength) {
8538 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00008539 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00008540 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008541 if (Char1.getInt() != Char2.getInt()) {
8542 if (IsWide) // wmemcmp compares with wchar_t signedness.
8543 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8544 // memcmp always compares unsigned chars.
8545 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8546 }
Richard Smithe151bab2016-11-11 23:43:35 +00008547 if (StopAtNull && !Char1.getInt())
8548 return Success(0, E);
8549 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00008550 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00008551 return false;
8552 }
8553 // We hit the strncmp / memcmp limit.
8554 return Success(0, E);
8555 }
8556
Richard Smith01ba47d2012-04-13 00:45:38 +00008557 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008558 case Builtin::BI__atomic_is_lock_free:
8559 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008560 APSInt SizeVal;
8561 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8562 return false;
8563
8564 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8565 // of two less than the maximum inline atomic width, we know it is
8566 // lock-free. If the size isn't a power of two, or greater than the
8567 // maximum alignment where we promote atomics, we know it is not lock-free
8568 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8569 // the answer can only be determined at runtime; for example, 16-byte
8570 // atomics have lock-free implementations on some, but not all,
8571 // x86-64 processors.
8572
8573 // Check power-of-two.
8574 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008575 if (Size.isPowerOfTwo()) {
8576 // Check against inlining width.
8577 unsigned InlineWidthBits =
8578 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8579 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8580 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8581 Size == CharUnits::One() ||
8582 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8583 Expr::NPC_NeverValueDependent))
8584 // OK, we will inline appropriately-aligned operations of this size,
8585 // and _Atomic(T) is appropriately-aligned.
8586 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008587
Richard Smith01ba47d2012-04-13 00:45:38 +00008588 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8589 castAs<PointerType>()->getPointeeType();
8590 if (!PointeeType->isIncompleteType() &&
8591 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8592 // OK, we will inline operations on this object.
8593 return Success(1, E);
8594 }
8595 }
8596 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008597
Richard Smith01ba47d2012-04-13 00:45:38 +00008598 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8599 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008600 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008601 case Builtin::BIomp_is_initial_device:
8602 // We can decide statically which value the runtime would return if called.
8603 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008604 case Builtin::BI__builtin_add_overflow:
8605 case Builtin::BI__builtin_sub_overflow:
8606 case Builtin::BI__builtin_mul_overflow:
8607 case Builtin::BI__builtin_sadd_overflow:
8608 case Builtin::BI__builtin_uadd_overflow:
8609 case Builtin::BI__builtin_uaddl_overflow:
8610 case Builtin::BI__builtin_uaddll_overflow:
8611 case Builtin::BI__builtin_usub_overflow:
8612 case Builtin::BI__builtin_usubl_overflow:
8613 case Builtin::BI__builtin_usubll_overflow:
8614 case Builtin::BI__builtin_umul_overflow:
8615 case Builtin::BI__builtin_umull_overflow:
8616 case Builtin::BI__builtin_umulll_overflow:
8617 case Builtin::BI__builtin_saddl_overflow:
8618 case Builtin::BI__builtin_saddll_overflow:
8619 case Builtin::BI__builtin_ssub_overflow:
8620 case Builtin::BI__builtin_ssubl_overflow:
8621 case Builtin::BI__builtin_ssubll_overflow:
8622 case Builtin::BI__builtin_smul_overflow:
8623 case Builtin::BI__builtin_smull_overflow:
8624 case Builtin::BI__builtin_smulll_overflow: {
8625 LValue ResultLValue;
8626 APSInt LHS, RHS;
8627
8628 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8629 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8630 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8631 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8632 return false;
8633
8634 APSInt Result;
8635 bool DidOverflow = false;
8636
8637 // If the types don't have to match, enlarge all 3 to the largest of them.
8638 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8639 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8640 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8641 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8642 ResultType->isSignedIntegerOrEnumerationType();
8643 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8644 ResultType->isSignedIntegerOrEnumerationType();
8645 uint64_t LHSSize = LHS.getBitWidth();
8646 uint64_t RHSSize = RHS.getBitWidth();
8647 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8648 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8649
8650 // Add an additional bit if the signedness isn't uniformly agreed to. We
8651 // could do this ONLY if there is a signed and an unsigned that both have
8652 // MaxBits, but the code to check that is pretty nasty. The issue will be
8653 // caught in the shrink-to-result later anyway.
8654 if (IsSigned && !AllSigned)
8655 ++MaxBits;
8656
8657 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8658 !IsSigned);
8659 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8660 !IsSigned);
8661 Result = APSInt(MaxBits, !IsSigned);
8662 }
8663
8664 // Find largest int.
8665 switch (BuiltinOp) {
8666 default:
8667 llvm_unreachable("Invalid value for BuiltinOp");
8668 case Builtin::BI__builtin_add_overflow:
8669 case Builtin::BI__builtin_sadd_overflow:
8670 case Builtin::BI__builtin_saddl_overflow:
8671 case Builtin::BI__builtin_saddll_overflow:
8672 case Builtin::BI__builtin_uadd_overflow:
8673 case Builtin::BI__builtin_uaddl_overflow:
8674 case Builtin::BI__builtin_uaddll_overflow:
8675 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8676 : LHS.uadd_ov(RHS, DidOverflow);
8677 break;
8678 case Builtin::BI__builtin_sub_overflow:
8679 case Builtin::BI__builtin_ssub_overflow:
8680 case Builtin::BI__builtin_ssubl_overflow:
8681 case Builtin::BI__builtin_ssubll_overflow:
8682 case Builtin::BI__builtin_usub_overflow:
8683 case Builtin::BI__builtin_usubl_overflow:
8684 case Builtin::BI__builtin_usubll_overflow:
8685 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8686 : LHS.usub_ov(RHS, DidOverflow);
8687 break;
8688 case Builtin::BI__builtin_mul_overflow:
8689 case Builtin::BI__builtin_smul_overflow:
8690 case Builtin::BI__builtin_smull_overflow:
8691 case Builtin::BI__builtin_smulll_overflow:
8692 case Builtin::BI__builtin_umul_overflow:
8693 case Builtin::BI__builtin_umull_overflow:
8694 case Builtin::BI__builtin_umulll_overflow:
8695 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8696 : LHS.umul_ov(RHS, DidOverflow);
8697 break;
8698 }
8699
8700 // In the case where multiple sizes are allowed, truncate and see if
8701 // the values are the same.
8702 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8703 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8704 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8705 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8706 // since it will give us the behavior of a TruncOrSelf in the case where
8707 // its parameter <= its size. We previously set Result to be at least the
8708 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8709 // will work exactly like TruncOrSelf.
8710 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8711 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8712
8713 if (!APSInt::isSameValue(Temp, Result))
8714 DidOverflow = true;
8715 Result = Temp;
8716 }
8717
8718 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008719 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8720 return false;
Erich Keane00958272018-06-13 20:43:27 +00008721 return Success(DidOverflow, E);
8722 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008723 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008724}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008726/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008727/// object referred to by the lvalue.
8728static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8729 const LValue &LV) {
8730 // A null pointer can be viewed as being "past the end" but we don't
8731 // choose to look at it that way here.
8732 if (!LV.getLValueBase())
8733 return false;
8734
8735 // If the designator is valid and refers to a subobject, we're not pointing
8736 // past the end.
8737 if (!LV.getLValueDesignator().Invalid &&
8738 !LV.getLValueDesignator().isOnePastTheEnd())
8739 return false;
8740
David Majnemerc378ca52015-08-29 08:32:55 +00008741 // A pointer to an incomplete type might be past-the-end if the type's size is
8742 // zero. We cannot tell because the type is incomplete.
8743 QualType Ty = getType(LV.getLValueBase());
8744 if (Ty->isIncompleteType())
8745 return true;
8746
Richard Smithd20f1e62014-10-21 23:01:04 +00008747 // We're a past-the-end pointer if we point to the byte after the object,
8748 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008749 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008750 return LV.getLValueOffset() == Size;
8751}
8752
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008753namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008755/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008756///
8757/// We use a data recursive algorithm for binary operators so that we are able
8758/// to handle extreme cases of chained binary operators without causing stack
8759/// overflow.
8760class DataRecursiveIntBinOpEvaluator {
8761 struct EvalResult {
8762 APValue Val;
8763 bool Failed;
8764
8765 EvalResult() : Failed(false) { }
8766
8767 void swap(EvalResult &RHS) {
8768 Val.swap(RHS.Val);
8769 Failed = RHS.Failed;
8770 RHS.Failed = false;
8771 }
8772 };
8773
8774 struct Job {
8775 const Expr *E;
8776 EvalResult LHSResult; // meaningful only for binary operator expression.
8777 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008778
David Blaikie73726062015-08-12 23:09:24 +00008779 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008780 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008781
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008782 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008783 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008784 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008785
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008786 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008787 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008788 };
8789
8790 SmallVector<Job, 16> Queue;
8791
8792 IntExprEvaluator &IntEval;
8793 EvalInfo &Info;
8794 APValue &FinalResult;
8795
8796public:
8797 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8798 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008800 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008801 /// data recursively.
8802 /// We handle binary operators that are comma, logical, or that have operands
8803 /// with integral or enumeration type.
8804 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008805 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8806 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008807 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008808 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008809 }
8810
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008811 bool Traverse(const BinaryOperator *E) {
8812 enqueue(E);
8813 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008814 while (!Queue.empty())
8815 process(PrevResult);
8816
8817 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008818
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008819 FinalResult.swap(PrevResult.Val);
8820 return true;
8821 }
8822
8823private:
8824 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8825 return IntEval.Success(Value, E, Result);
8826 }
8827 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8828 return IntEval.Success(Value, E, Result);
8829 }
8830 bool Error(const Expr *E) {
8831 return IntEval.Error(E);
8832 }
8833 bool Error(const Expr *E, diag::kind D) {
8834 return IntEval.Error(E, D);
8835 }
8836
8837 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8838 return Info.CCEDiag(E, D);
8839 }
8840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008841 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008842 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008843 bool &SuppressRHSDiags);
8844
8845 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8846 const BinaryOperator *E, APValue &Result);
8847
8848 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8849 Result.Failed = !Evaluate(Result.Val, Info, E);
8850 if (Result.Failed)
8851 Result.Val = APValue();
8852 }
8853
Richard Trieuba4d0872012-03-21 23:30:30 +00008854 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008855
8856 void enqueue(const Expr *E) {
8857 E = E->IgnoreParens();
8858 Queue.resize(Queue.size()+1);
8859 Queue.back().E = E;
8860 Queue.back().Kind = Job::AnyExprKind;
8861 }
8862};
8863
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008864}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008865
8866bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008867 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008868 bool &SuppressRHSDiags) {
8869 if (E->getOpcode() == BO_Comma) {
8870 // Ignore LHS but note if we could not evaluate it.
8871 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008872 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008873 return true;
8874 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008875
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008876 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008877 bool LHSAsBool;
8878 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008879 // We were able to evaluate the LHS, see if we can get away with not
8880 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008881 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8882 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008883 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008884 }
8885 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008886 LHSResult.Failed = true;
8887
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008888 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008889 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008890 if (!Info.noteSideEffect())
8891 return false;
8892
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008893 // We can't evaluate the LHS; however, sometimes the result
8894 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8895 // Don't ignore RHS and suppress diagnostics from this arm.
8896 SuppressRHSDiags = true;
8897 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008898
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008899 return true;
8900 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008901
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008902 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8903 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008904
George Burgess IVa145e252016-05-25 22:38:36 +00008905 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008906 return false; // Ignore RHS;
8907
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008908 return true;
8909}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008910
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008911static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8912 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008913 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8914 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8915 // offsets.
8916 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8917 CharUnits &Offset = LVal.getLValueOffset();
8918 uint64_t Offset64 = Offset.getQuantity();
8919 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8920 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8921 : Offset64 + Index64);
8922}
8923
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008924bool DataRecursiveIntBinOpEvaluator::
8925 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8926 const BinaryOperator *E, APValue &Result) {
8927 if (E->getOpcode() == BO_Comma) {
8928 if (RHSResult.Failed)
8929 return false;
8930 Result = RHSResult.Val;
8931 return true;
8932 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008933
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008934 if (E->isLogicalOp()) {
8935 bool lhsResult, rhsResult;
8936 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8937 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008938
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008939 if (LHSIsOK) {
8940 if (RHSIsOK) {
8941 if (E->getOpcode() == BO_LOr)
8942 return Success(lhsResult || rhsResult, E, Result);
8943 else
8944 return Success(lhsResult && rhsResult, E, Result);
8945 }
8946 } else {
8947 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008948 // We can't evaluate the LHS; however, sometimes the result
8949 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8950 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008951 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008952 }
8953 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008954
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008955 return false;
8956 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008957
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008958 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8959 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008960
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008961 if (LHSResult.Failed || RHSResult.Failed)
8962 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008963
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008964 const APValue &LHSVal = LHSResult.Val;
8965 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008966
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008967 // Handle cases like (unsigned long)&a + 4.
8968 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8969 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008970 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008971 return true;
8972 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008973
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008974 // Handle cases like 4 + (unsigned long)&a
8975 if (E->getOpcode() == BO_Add &&
8976 RHSVal.isLValue() && LHSVal.isInt()) {
8977 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008978 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008979 return true;
8980 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008981
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008982 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8983 // Handle (intptr_t)&&A - (intptr_t)&&B.
8984 if (!LHSVal.getLValueOffset().isZero() ||
8985 !RHSVal.getLValueOffset().isZero())
8986 return false;
8987 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8988 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8989 if (!LHSExpr || !RHSExpr)
8990 return false;
8991 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8992 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8993 if (!LHSAddrExpr || !RHSAddrExpr)
8994 return false;
8995 // Make sure both labels come from the same function.
8996 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8997 RHSAddrExpr->getLabel()->getDeclContext())
8998 return false;
8999 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9000 return true;
9001 }
Richard Smith43e77732013-05-07 04:50:00 +00009002
9003 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009004 if (!LHSVal.isInt() || !RHSVal.isInt())
9005 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009006
9007 // Set up the width and signedness manually, in case it can't be deduced
9008 // from the operation we're performing.
9009 // FIXME: Don't do this in the cases where we can deduce it.
9010 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9011 E->getType()->isUnsignedIntegerOrEnumerationType());
9012 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9013 RHSVal.getInt(), Value))
9014 return false;
9015 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009016}
9017
Richard Trieuba4d0872012-03-21 23:30:30 +00009018void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009019 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009020
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009021 switch (job.Kind) {
9022 case Job::AnyExprKind: {
9023 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9024 if (shouldEnqueue(Bop)) {
9025 job.Kind = Job::BinOpKind;
9026 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009027 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009028 }
9029 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009030
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009031 EvaluateExpr(job.E, Result);
9032 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009033 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009034 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009035
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009036 case Job::BinOpKind: {
9037 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009038 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009039 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009040 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009041 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009042 }
9043 if (SuppressRHSDiags)
9044 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009045 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009046 job.Kind = Job::BinOpVisitedLHSKind;
9047 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009048 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009049 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009050
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009051 case Job::BinOpVisitedLHSKind: {
9052 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9053 EvalResult RHS;
9054 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009055 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009056 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009057 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009058 }
9059 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009060
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009061 llvm_unreachable("Invalid Job::Kind!");
9062}
9063
George Burgess IV8c892b52016-05-25 22:31:54 +00009064namespace {
9065/// Used when we determine that we should fail, but can keep evaluating prior to
9066/// noting that we had a failure.
9067class DelayedNoteFailureRAII {
9068 EvalInfo &Info;
9069 bool NoteFailure;
9070
9071public:
9072 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9073 : Info(Info), NoteFailure(NoteFailure) {}
9074 ~DelayedNoteFailureRAII() {
9075 if (NoteFailure) {
9076 bool ContinueAfterFailure = Info.noteFailure();
9077 (void)ContinueAfterFailure;
9078 assert(ContinueAfterFailure &&
9079 "Shouldn't have kept evaluating on failure.");
9080 }
9081 }
9082};
9083}
9084
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009085template <class SuccessCB, class AfterCB>
9086static bool
9087EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9088 SuccessCB &&Success, AfterCB &&DoAfter) {
9089 assert(E->isComparisonOp() && "expected comparison operator");
9090 assert((E->getOpcode() == BO_Cmp ||
9091 E->getType()->isIntegralOrEnumerationType()) &&
9092 "unsupported binary expression evaluation");
9093 auto Error = [&](const Expr *E) {
9094 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9095 return false;
9096 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009097
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009098 using CCR = ComparisonCategoryResult;
9099 bool IsRelational = E->isRelationalOp();
9100 bool IsEquality = E->isEqualityOp();
9101 if (E->getOpcode() == BO_Cmp) {
9102 const ComparisonCategoryInfo &CmpInfo =
9103 Info.Ctx.CompCategories.getInfoForType(E->getType());
9104 IsRelational = CmpInfo.isOrdered();
9105 IsEquality = CmpInfo.isEquality();
9106 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009107
Anders Carlssonacc79812008-11-16 07:17:21 +00009108 QualType LHSTy = E->getLHS()->getType();
9109 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009110
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009111 if (LHSTy->isIntegralOrEnumerationType() &&
9112 RHSTy->isIntegralOrEnumerationType()) {
9113 APSInt LHS, RHS;
9114 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9115 if (!LHSOK && !Info.noteFailure())
9116 return false;
9117 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9118 return false;
9119 if (LHS < RHS)
9120 return Success(CCR::Less, E);
9121 if (LHS > RHS)
9122 return Success(CCR::Greater, E);
9123 return Success(CCR::Equal, E);
9124 }
9125
Chandler Carruthb29a7432014-10-11 11:03:30 +00009126 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009127 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009128 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009129 if (E->isAssignmentOp()) {
9130 LValue LV;
9131 EvaluateLValue(E->getLHS(), LV, Info);
9132 LHSOK = false;
9133 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009134 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9135 if (LHSOK) {
9136 LHS.makeComplexFloat();
9137 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9138 }
9139 } else {
9140 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9141 }
George Burgess IVa145e252016-05-25 22:38:36 +00009142 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009143 return false;
9144
Chandler Carruthb29a7432014-10-11 11:03:30 +00009145 if (E->getRHS()->getType()->isRealFloatingType()) {
9146 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9147 return false;
9148 RHS.makeComplexFloat();
9149 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9150 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009151 return false;
9152
9153 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009154 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009155 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009156 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009157 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009158 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9159 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009160 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009161 assert(IsEquality && "invalid complex comparison");
9162 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9163 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9164 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009165 }
9166 }
Mike Stump11289f42009-09-09 15:08:12 +00009167
Anders Carlssonacc79812008-11-16 07:17:21 +00009168 if (LHSTy->isRealFloatingType() &&
9169 RHSTy->isRealFloatingType()) {
9170 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009171
Richard Smith253c2a32012-01-27 01:14:48 +00009172 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009173 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009174 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009175
Richard Smith253c2a32012-01-27 01:14:48 +00009176 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009177 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009178
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009179 assert(E->isComparisonOp() && "Invalid binary operator!");
9180 auto GetCmpRes = [&]() {
9181 switch (LHS.compare(RHS)) {
9182 case APFloat::cmpEqual:
9183 return CCR::Equal;
9184 case APFloat::cmpLessThan:
9185 return CCR::Less;
9186 case APFloat::cmpGreaterThan:
9187 return CCR::Greater;
9188 case APFloat::cmpUnordered:
9189 return CCR::Unordered;
9190 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009191 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009192 };
9193 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009194 }
Mike Stump11289f42009-09-09 15:08:12 +00009195
Eli Friedmana38da572009-04-28 19:17:36 +00009196 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009197 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009198
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009199 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9200 if (!LHSOK && !Info.noteFailure())
9201 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009202
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009203 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9204 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009205
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009206 // Reject differing bases from the normal codepath; we special-case
9207 // comparisons to null.
9208 if (!HasSameBase(LHSValue, RHSValue)) {
9209 // Inequalities and subtractions between unrelated pointers have
9210 // unspecified or undefined behavior.
9211 if (!IsEquality)
9212 return Error(E);
9213 // A constant address may compare equal to the address of a symbol.
9214 // The one exception is that address of an object cannot compare equal
9215 // to a null pointer constant.
9216 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9217 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9218 return Error(E);
9219 // It's implementation-defined whether distinct literals will have
9220 // distinct addresses. In clang, the result of such a comparison is
9221 // unspecified, so it is not a constant expression. However, we do know
9222 // that the address of a literal will be non-null.
9223 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9224 LHSValue.Base && RHSValue.Base)
9225 return Error(E);
9226 // We can't tell whether weak symbols will end up pointing to the same
9227 // object.
9228 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9229 return Error(E);
9230 // We can't compare the address of the start of one object with the
9231 // past-the-end address of another object, per C++ DR1652.
9232 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9233 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9234 (RHSValue.Base && RHSValue.Offset.isZero() &&
9235 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9236 return Error(E);
9237 // We can't tell whether an object is at the same address as another
9238 // zero sized object.
9239 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9240 (LHSValue.Base && isZeroSized(RHSValue)))
9241 return Error(E);
9242 return Success(CCR::Nonequal, E);
9243 }
Eli Friedman64004332009-03-23 04:38:34 +00009244
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009245 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9246 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009247
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009248 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9249 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009250
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009251 // C++11 [expr.rel]p3:
9252 // Pointers to void (after pointer conversions) can be compared, with a
9253 // result defined as follows: If both pointers represent the same
9254 // address or are both the null pointer value, the result is true if the
9255 // operator is <= or >= and false otherwise; otherwise the result is
9256 // unspecified.
9257 // We interpret this as applying to pointers to *cv* void.
9258 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9259 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009260
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009261 // C++11 [expr.rel]p2:
9262 // - If two pointers point to non-static data members of the same object,
9263 // or to subobjects or array elements fo such members, recursively, the
9264 // pointer to the later declared member compares greater provided the
9265 // two members have the same access control and provided their class is
9266 // not a union.
9267 // [...]
9268 // - Otherwise pointer comparisons are unspecified.
9269 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9270 bool WasArrayIndex;
9271 unsigned Mismatch = FindDesignatorMismatch(
9272 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9273 // At the point where the designators diverge, the comparison has a
9274 // specified value if:
9275 // - we are comparing array indices
9276 // - we are comparing fields of a union, or fields with the same access
9277 // Otherwise, the result is unspecified and thus the comparison is not a
9278 // constant expression.
9279 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9280 Mismatch < RHSDesignator.Entries.size()) {
9281 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9282 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9283 if (!LF && !RF)
9284 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9285 else if (!LF)
9286 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009287 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9288 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009289 else if (!RF)
9290 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009291 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9292 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009293 else if (!LF->getParent()->isUnion() &&
9294 LF->getAccess() != RF->getAccess())
9295 Info.CCEDiag(E,
9296 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009297 << LF << LF->getAccess() << RF << RF->getAccess()
9298 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009299 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009300 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009301
9302 // The comparison here must be unsigned, and performed with the same
9303 // width as the pointer.
9304 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9305 uint64_t CompareLHS = LHSOffset.getQuantity();
9306 uint64_t CompareRHS = RHSOffset.getQuantity();
9307 assert(PtrSize <= 64 && "Unexpected pointer width");
9308 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9309 CompareLHS &= Mask;
9310 CompareRHS &= Mask;
9311
9312 // If there is a base and this is a relational operator, we can only
9313 // compare pointers within the object in question; otherwise, the result
9314 // depends on where the object is located in memory.
9315 if (!LHSValue.Base.isNull() && IsRelational) {
9316 QualType BaseTy = getType(LHSValue.Base);
9317 if (BaseTy->isIncompleteType())
9318 return Error(E);
9319 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9320 uint64_t OffsetLimit = Size.getQuantity();
9321 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9322 return Error(E);
9323 }
9324
9325 if (CompareLHS < CompareRHS)
9326 return Success(CCR::Less, E);
9327 if (CompareLHS > CompareRHS)
9328 return Success(CCR::Greater, E);
9329 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009330 }
Richard Smith7bb00672012-02-01 01:42:44 +00009331
9332 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009333 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009334 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9335
9336 MemberPtr LHSValue, RHSValue;
9337
9338 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009339 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009340 return false;
9341
9342 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9343 return false;
9344
9345 // C++11 [expr.eq]p2:
9346 // If both operands are null, they compare equal. Otherwise if only one is
9347 // null, they compare unequal.
9348 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9349 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009350 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009351 }
9352
9353 // Otherwise if either is a pointer to a virtual member function, the
9354 // result is unspecified.
9355 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9356 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009357 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009358 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9359 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009360 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009361
9362 // Otherwise they compare equal if and only if they would refer to the
9363 // same member of the same most derived object or the same subobject if
9364 // they were dereferenced with a hypothetical object of the associated
9365 // class type.
9366 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009367 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009368 }
9369
Richard Smithab44d9b2012-02-14 22:35:28 +00009370 if (LHSTy->isNullPtrType()) {
9371 assert(E->isComparisonOp() && "unexpected nullptr operation");
9372 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9373 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9374 // are compared, the result is true of the operator is <=, >= or ==, and
9375 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009376 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009377 }
9378
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009379 return DoAfter();
9380}
9381
9382bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9383 if (!CheckLiteralType(Info, E))
9384 return false;
9385
9386 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9387 const BinaryOperator *E) {
9388 // Evaluation succeeded. Lookup the information for the comparison category
9389 // type and fetch the VarDecl for the result.
9390 const ComparisonCategoryInfo &CmpInfo =
9391 Info.Ctx.CompCategories.getInfoForType(E->getType());
9392 const VarDecl *VD =
9393 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9394 // Check and evaluate the result as a constant expression.
9395 LValue LV;
9396 LV.set(VD);
9397 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9398 return false;
9399 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9400 };
9401 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9402 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9403 });
9404}
9405
9406bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9407 // We don't call noteFailure immediately because the assignment happens after
9408 // we evaluate LHS and RHS.
9409 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9410 return Error(E);
9411
9412 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9413 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9414 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9415
9416 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9417 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009418 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009419
9420 if (E->isComparisonOp()) {
9421 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9422 // comparisons and then translating the result.
9423 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9424 const BinaryOperator *E) {
9425 using CCR = ComparisonCategoryResult;
9426 bool IsEqual = ResKind == CCR::Equal,
9427 IsLess = ResKind == CCR::Less,
9428 IsGreater = ResKind == CCR::Greater;
9429 auto Op = E->getOpcode();
9430 switch (Op) {
9431 default:
9432 llvm_unreachable("unsupported binary operator");
9433 case BO_EQ:
9434 case BO_NE:
9435 return Success(IsEqual == (Op == BO_EQ), E);
9436 case BO_LT: return Success(IsLess, E);
9437 case BO_GT: return Success(IsGreater, E);
9438 case BO_LE: return Success(IsEqual || IsLess, E);
9439 case BO_GE: return Success(IsEqual || IsGreater, E);
9440 }
9441 };
9442 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9443 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9444 });
9445 }
9446
9447 QualType LHSTy = E->getLHS()->getType();
9448 QualType RHSTy = E->getRHS()->getType();
9449
9450 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9451 E->getOpcode() == BO_Sub) {
9452 LValue LHSValue, RHSValue;
9453
9454 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9455 if (!LHSOK && !Info.noteFailure())
9456 return false;
9457
9458 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9459 return false;
9460
9461 // Reject differing bases from the normal codepath; we special-case
9462 // comparisons to null.
9463 if (!HasSameBase(LHSValue, RHSValue)) {
9464 // Handle &&A - &&B.
9465 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9466 return Error(E);
9467 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9468 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9469 if (!LHSExpr || !RHSExpr)
9470 return Error(E);
9471 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9472 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9473 if (!LHSAddrExpr || !RHSAddrExpr)
9474 return Error(E);
9475 // Make sure both labels come from the same function.
9476 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9477 RHSAddrExpr->getLabel()->getDeclContext())
9478 return Error(E);
9479 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9480 }
9481 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9482 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9483
9484 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9485 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9486
9487 // C++11 [expr.add]p6:
9488 // Unless both pointers point to elements of the same array object, or
9489 // one past the last element of the array object, the behavior is
9490 // undefined.
9491 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9492 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9493 RHSDesignator))
9494 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9495
9496 QualType Type = E->getLHS()->getType();
9497 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9498
9499 CharUnits ElementSize;
9500 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9501 return false;
9502
9503 // As an extension, a type may have zero size (empty struct or union in
9504 // C, array of zero length). Pointer subtraction in such cases has
9505 // undefined behavior, so is not constant.
9506 if (ElementSize.isZero()) {
9507 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9508 << ElementType;
9509 return false;
9510 }
9511
9512 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9513 // and produce incorrect results when it overflows. Such behavior
9514 // appears to be non-conforming, but is common, so perhaps we should
9515 // assume the standard intended for such cases to be undefined behavior
9516 // and check for them.
9517
9518 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9519 // overflow in the final conversion to ptrdiff_t.
9520 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9521 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9522 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9523 false);
9524 APSInt TrueResult = (LHS - RHS) / ElemSize;
9525 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9526
9527 if (Result.extend(65) != TrueResult &&
9528 !HandleOverflow(Info, E, TrueResult, E->getType()))
9529 return false;
9530 return Success(Result, E);
9531 }
9532
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009534}
9535
Peter Collingbournee190dee2011-03-11 19:24:49 +00009536/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9537/// a result as the expression's type.
9538bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9539 const UnaryExprOrTypeTraitExpr *E) {
9540 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009541 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009542 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009543 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009544 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9545 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009546 else
Richard Smith6822bd72018-10-26 19:26:45 +00009547 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9548 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009549 }
Eli Friedman64004332009-03-23 04:38:34 +00009550
Peter Collingbournee190dee2011-03-11 19:24:49 +00009551 case UETT_VecStep: {
9552 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009553
Peter Collingbournee190dee2011-03-11 19:24:49 +00009554 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009555 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009556
Peter Collingbournee190dee2011-03-11 19:24:49 +00009557 // The vec_step built-in functions that take a 3-component
9558 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9559 if (n == 3)
9560 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009561
Peter Collingbournee190dee2011-03-11 19:24:49 +00009562 return Success(n, E);
9563 } else
9564 return Success(1, E);
9565 }
9566
9567 case UETT_SizeOf: {
9568 QualType SrcTy = E->getTypeOfArgument();
9569 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9570 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009571 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9572 SrcTy = Ref->getPointeeType();
9573
Richard Smithd62306a2011-11-10 06:34:14 +00009574 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009575 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009576 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009577 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009578 }
Alexey Bataev00396512015-07-02 03:40:19 +00009579 case UETT_OpenMPRequiredSimdAlign:
9580 assert(E->isArgumentType());
9581 return Success(
9582 Info.Ctx.toCharUnitsFromBits(
9583 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9584 .getQuantity(),
9585 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009586 }
9587
9588 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009589}
9590
Peter Collingbournee9200682011-05-13 03:29:01 +00009591bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009592 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009593 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009594 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009595 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009596 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009597 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009598 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009599 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009600 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009601 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009602 APSInt IdxResult;
9603 if (!EvaluateInteger(Idx, IdxResult, Info))
9604 return false;
9605 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9606 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009607 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009608 CurrentType = AT->getElementType();
9609 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9610 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009611 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009612 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009613
James Y Knight7281c352015-12-29 22:31:18 +00009614 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009615 FieldDecl *MemberDecl = ON.getField();
9616 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009617 if (!RT)
9618 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009619 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009620 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009621 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009622 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009623 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009624 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009625 CurrentType = MemberDecl->getType().getNonReferenceType();
9626 break;
9627 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009628
James Y Knight7281c352015-12-29 22:31:18 +00009629 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009630 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009631
James Y Knight7281c352015-12-29 22:31:18 +00009632 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009633 CXXBaseSpecifier *BaseSpec = ON.getBase();
9634 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009635 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009636
9637 // Find the layout of the class whose base we are looking into.
9638 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009639 if (!RT)
9640 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009641 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009642 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009643 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9644
9645 // Find the base class itself.
9646 CurrentType = BaseSpec->getType();
9647 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9648 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009649 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009650
Douglas Gregord1702062010-04-29 00:18:15 +00009651 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009652 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009653 break;
9654 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009655 }
9656 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009657 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009658}
9659
Chris Lattnere13042c2008-07-11 19:10:17 +00009660bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009661 switch (E->getOpcode()) {
9662 default:
9663 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9664 // See C99 6.6p3.
9665 return Error(E);
9666 case UO_Extension:
9667 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9668 // If so, we could clear the diagnostic ID.
9669 return Visit(E->getSubExpr());
9670 case UO_Plus:
9671 // The result is just the value.
9672 return Visit(E->getSubExpr());
9673 case UO_Minus: {
9674 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009675 return false;
9676 if (!Result.isInt()) return Error(E);
9677 const APSInt &Value = Result.getInt();
9678 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9679 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9680 E->getType()))
9681 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009682 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009683 }
9684 case UO_Not: {
9685 if (!Visit(E->getSubExpr()))
9686 return false;
9687 if (!Result.isInt()) return Error(E);
9688 return Success(~Result.getInt(), E);
9689 }
9690 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009691 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009692 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009693 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009694 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009695 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009696 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009697}
Mike Stump11289f42009-09-09 15:08:12 +00009698
Chris Lattner477c4be2008-07-12 01:15:53 +00009699/// HandleCast - This is used to evaluate implicit or explicit casts where the
9700/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009701bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9702 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009703 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009704 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009705
Eli Friedmanc757de22011-03-25 00:43:55 +00009706 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009707 case CK_BaseToDerived:
9708 case CK_DerivedToBase:
9709 case CK_UncheckedDerivedToBase:
9710 case CK_Dynamic:
9711 case CK_ToUnion:
9712 case CK_ArrayToPointerDecay:
9713 case CK_FunctionToPointerDecay:
9714 case CK_NullToPointer:
9715 case CK_NullToMemberPointer:
9716 case CK_BaseToDerivedMemberPointer:
9717 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009718 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009719 case CK_ConstructorConversion:
9720 case CK_IntegralToPointer:
9721 case CK_ToVoid:
9722 case CK_VectorSplat:
9723 case CK_IntegralToFloating:
9724 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009725 case CK_CPointerToObjCPointerCast:
9726 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009727 case CK_AnyPointerToBlockPointerCast:
9728 case CK_ObjCObjectLValueCast:
9729 case CK_FloatingRealToComplex:
9730 case CK_FloatingComplexToReal:
9731 case CK_FloatingComplexCast:
9732 case CK_FloatingComplexToIntegralComplex:
9733 case CK_IntegralRealToComplex:
9734 case CK_IntegralComplexCast:
9735 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009736 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009737 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009738 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009739 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009740 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009741 case CK_FixedPointCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009742 llvm_unreachable("invalid cast kind for integral value");
9743
Eli Friedman9faf2f92011-03-25 19:07:11 +00009744 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009745 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009746 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009747 case CK_ARCProduceObject:
9748 case CK_ARCConsumeObject:
9749 case CK_ARCReclaimReturnedObject:
9750 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009751 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009752 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009753
Richard Smith4ef685b2012-01-17 21:17:26 +00009754 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009755 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009756 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009757 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009758 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009759
9760 case CK_MemberPointerToBoolean:
9761 case CK_PointerToBoolean:
9762 case CK_IntegralToBoolean:
9763 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009764 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009765 case CK_FloatingComplexToBoolean:
9766 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009767 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009768 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009769 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009770 uint64_t IntResult = BoolResult;
9771 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9772 IntResult = (uint64_t)-1;
9773 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009774 }
9775
Leonard Chanb4ba4672018-10-23 17:55:35 +00009776 case CK_FixedPointToBoolean: {
9777 // Unsigned padding does not affect this.
9778 APValue Val;
9779 if (!Evaluate(Val, Info, SubExpr))
9780 return false;
9781 return Success(Val.getInt().getBoolValue(), E);
9782 }
9783
Eli Friedmanc757de22011-03-25 00:43:55 +00009784 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009785 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009786 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009787
Eli Friedman742421e2009-02-20 01:15:07 +00009788 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009789 // Allow casts of address-of-label differences if they are no-ops
9790 // or narrowing. (The narrowing case isn't actually guaranteed to
9791 // be constant-evaluatable except in some narrow cases which are hard
9792 // to detect here. We let it through on the assumption the user knows
9793 // what they are doing.)
9794 if (Result.isAddrLabelDiff())
9795 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009796 // Only allow casts of lvalues if they are lossless.
9797 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9798 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009799
Richard Smith911e1422012-01-30 22:27:01 +00009800 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9801 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009802 }
Mike Stump11289f42009-09-09 15:08:12 +00009803
Eli Friedmanc757de22011-03-25 00:43:55 +00009804 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009805 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9806
John McCall45d55e42010-05-07 21:00:08 +00009807 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009808 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009809 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009810
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009811 if (LV.getLValueBase()) {
9812 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009813 // FIXME: Allow a larger integer size than the pointer size, and allow
9814 // narrowing back down to pointer width in subsequent integral casts.
9815 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009816 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009817 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009818
Richard Smithcf74da72011-11-16 07:18:12 +00009819 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009820 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009821 return true;
9822 }
9823
Yaxun Liu402804b2016-12-15 08:09:08 +00009824 uint64_t V;
9825 if (LV.isNullPointer())
9826 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9827 else
9828 V = LV.getLValueOffset().getQuantity();
9829
9830 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009831 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009832 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009833
Eli Friedmanc757de22011-03-25 00:43:55 +00009834 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009835 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009836 if (!EvaluateComplex(SubExpr, C, Info))
9837 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009838 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009839 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009840
Eli Friedmanc757de22011-03-25 00:43:55 +00009841 case CK_FloatingToIntegral: {
9842 APFloat F(0.0);
9843 if (!EvaluateFloat(SubExpr, F, Info))
9844 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009845
Richard Smith357362d2011-12-13 06:39:58 +00009846 APSInt Value;
9847 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9848 return false;
9849 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009850 }
9851 }
Mike Stump11289f42009-09-09 15:08:12 +00009852
Eli Friedmanc757de22011-03-25 00:43:55 +00009853 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009854}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009855
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009856bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9857 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009858 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009859 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9860 return false;
9861 if (!LV.isComplexInt())
9862 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009863 return Success(LV.getComplexIntReal(), E);
9864 }
9865
9866 return Visit(E->getSubExpr());
9867}
9868
Eli Friedman4e7a2412009-02-27 04:45:43 +00009869bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009870 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009871 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009872 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9873 return false;
9874 if (!LV.isComplexInt())
9875 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009876 return Success(LV.getComplexIntImag(), E);
9877 }
9878
Richard Smith4a678122011-10-24 18:44:57 +00009879 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009880 return Success(0, E);
9881}
9882
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009883bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9884 return Success(E->getPackLength(), E);
9885}
9886
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009887bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9888 return Success(E->getValue(), E);
9889}
9890
Leonard Chandb01c3a2018-06-20 17:19:40 +00009891bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9892 switch (E->getOpcode()) {
9893 default:
9894 // Invalid unary operators
9895 return Error(E);
9896 case UO_Plus:
9897 // The result is just the value.
9898 return Visit(E->getSubExpr());
9899 case UO_Minus: {
9900 if (!Visit(E->getSubExpr())) return false;
9901 if (!Result.isInt()) return Error(E);
9902 const APSInt &Value = Result.getInt();
9903 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9904 SmallString<64> S;
9905 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009906 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009907 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9908 if (Info.noteUndefinedBehavior()) return false;
9909 }
9910 return Success(-Value, E);
9911 }
9912 case UO_LNot: {
9913 bool bres;
9914 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9915 return false;
9916 return Success(!bres, E);
9917 }
9918 }
9919}
9920
Chris Lattner05706e882008-07-11 18:11:29 +00009921//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009922// Float Evaluation
9923//===----------------------------------------------------------------------===//
9924
9925namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009926class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009927 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009928 APFloat &Result;
9929public:
9930 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009931 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009932
Richard Smith2e312c82012-03-03 22:46:17 +00009933 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009934 Result = V.getFloat();
9935 return true;
9936 }
Eli Friedman24c01542008-08-22 00:06:13 +00009937
Richard Smithfddd3842011-12-30 21:15:51 +00009938 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009939 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9940 return true;
9941 }
9942
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009943 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009944
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009945 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009946 bool VisitBinaryOperator(const BinaryOperator *E);
9947 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009948 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009949
John McCallb1fb0d32010-05-07 22:08:54 +00009950 bool VisitUnaryReal(const UnaryOperator *E);
9951 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009952
Richard Smithfddd3842011-12-30 21:15:51 +00009953 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009954};
9955} // end anonymous namespace
9956
9957static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009958 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009959 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009960}
9961
Jay Foad39c79802011-01-12 09:06:06 +00009962static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009963 QualType ResultTy,
9964 const Expr *Arg,
9965 bool SNaN,
9966 llvm::APFloat &Result) {
9967 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9968 if (!S) return false;
9969
9970 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9971
9972 llvm::APInt fill;
9973
9974 // Treat empty strings as if they were zero.
9975 if (S->getString().empty())
9976 fill = llvm::APInt(32, 0);
9977 else if (S->getString().getAsInteger(0, fill))
9978 return false;
9979
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009980 if (Context.getTargetInfo().isNan2008()) {
9981 if (SNaN)
9982 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9983 else
9984 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9985 } else {
9986 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9987 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9988 // a different encoding to what became a standard in 2008, and for pre-
9989 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9990 // sNaN. This is now known as "legacy NaN" encoding.
9991 if (SNaN)
9992 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9993 else
9994 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9995 }
9996
John McCall16291492010-02-28 13:00:19 +00009997 return true;
9998}
9999
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010000bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010001 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010002 default:
10003 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10004
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010005 case Builtin::BI__builtin_huge_val:
10006 case Builtin::BI__builtin_huge_valf:
10007 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010008 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010009 case Builtin::BI__builtin_inf:
10010 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010011 case Builtin::BI__builtin_infl:
10012 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010013 const llvm::fltSemantics &Sem =
10014 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010015 Result = llvm::APFloat::getInf(Sem);
10016 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010017 }
Mike Stump11289f42009-09-09 15:08:12 +000010018
John McCall16291492010-02-28 13:00:19 +000010019 case Builtin::BI__builtin_nans:
10020 case Builtin::BI__builtin_nansf:
10021 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010022 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010023 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10024 true, Result))
10025 return Error(E);
10026 return true;
John McCall16291492010-02-28 13:00:19 +000010027
Chris Lattner0b7282e2008-10-06 06:31:58 +000010028 case Builtin::BI__builtin_nan:
10029 case Builtin::BI__builtin_nanf:
10030 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010031 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010032 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010033 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010034 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10035 false, Result))
10036 return Error(E);
10037 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010038
10039 case Builtin::BI__builtin_fabs:
10040 case Builtin::BI__builtin_fabsf:
10041 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010042 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010043 if (!EvaluateFloat(E->getArg(0), Result, Info))
10044 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010045
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010046 if (Result.isNegative())
10047 Result.changeSign();
10048 return true;
10049
Richard Smith8889a3d2013-06-13 06:26:32 +000010050 // FIXME: Builtin::BI__builtin_powi
10051 // FIXME: Builtin::BI__builtin_powif
10052 // FIXME: Builtin::BI__builtin_powil
10053
Mike Stump11289f42009-09-09 15:08:12 +000010054 case Builtin::BI__builtin_copysign:
10055 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010056 case Builtin::BI__builtin_copysignl:
10057 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010058 APFloat RHS(0.);
10059 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10060 !EvaluateFloat(E->getArg(1), RHS, Info))
10061 return false;
10062 Result.copySign(RHS);
10063 return true;
10064 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010065 }
10066}
10067
John McCallb1fb0d32010-05-07 22:08:54 +000010068bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010069 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10070 ComplexValue CV;
10071 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10072 return false;
10073 Result = CV.FloatReal;
10074 return true;
10075 }
10076
10077 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010078}
10079
10080bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010081 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10082 ComplexValue CV;
10083 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10084 return false;
10085 Result = CV.FloatImag;
10086 return true;
10087 }
10088
Richard Smith4a678122011-10-24 18:44:57 +000010089 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010090 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10091 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010092 return true;
10093}
10094
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010095bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010096 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010097 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010098 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010099 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010100 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010101 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10102 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010103 Result.changeSign();
10104 return true;
10105 }
10106}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010107
Eli Friedman24c01542008-08-22 00:06:13 +000010108bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010109 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10110 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010111
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010112 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010113 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010114 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010115 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010116 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10117 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010118}
10119
10120bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10121 Result = E->getValue();
10122 return true;
10123}
10124
Peter Collingbournee9200682011-05-13 03:29:01 +000010125bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10126 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010127
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010128 switch (E->getCastKind()) {
10129 default:
Richard Smith11562c52011-10-28 17:51:58 +000010130 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010131
10132 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010133 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010134 return EvaluateInteger(SubExpr, IntResult, Info) &&
10135 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10136 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010137 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010138
10139 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010140 if (!Visit(SubExpr))
10141 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010142 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10143 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010144 }
John McCalld7646252010-11-14 08:17:51 +000010145
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010146 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010147 ComplexValue V;
10148 if (!EvaluateComplex(SubExpr, V, Info))
10149 return false;
10150 Result = V.getComplexFloatReal();
10151 return true;
10152 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010153 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010154}
10155
Eli Friedman24c01542008-08-22 00:06:13 +000010156//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010157// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010158//===----------------------------------------------------------------------===//
10159
10160namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010161class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010162 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010163 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010164
Anders Carlsson537969c2008-11-16 20:27:53 +000010165public:
John McCall93d91dc2010-05-07 17:22:02 +000010166 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010167 : ExprEvaluatorBaseTy(info), Result(Result) {}
10168
Richard Smith2e312c82012-03-03 22:46:17 +000010169 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010170 Result.setFrom(V);
10171 return true;
10172 }
Mike Stump11289f42009-09-09 15:08:12 +000010173
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010174 bool ZeroInitialization(const Expr *E);
10175
Anders Carlsson537969c2008-11-16 20:27:53 +000010176 //===--------------------------------------------------------------------===//
10177 // Visitor Methods
10178 //===--------------------------------------------------------------------===//
10179
Peter Collingbournee9200682011-05-13 03:29:01 +000010180 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010181 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010182 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010183 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010184 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010185};
10186} // end anonymous namespace
10187
John McCall93d91dc2010-05-07 17:22:02 +000010188static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10189 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010190 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010191 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010192}
10193
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010194bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010195 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010196 if (ElemTy->isRealFloatingType()) {
10197 Result.makeComplexFloat();
10198 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10199 Result.FloatReal = Zero;
10200 Result.FloatImag = Zero;
10201 } else {
10202 Result.makeComplexInt();
10203 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10204 Result.IntReal = Zero;
10205 Result.IntImag = Zero;
10206 }
10207 return true;
10208}
10209
Peter Collingbournee9200682011-05-13 03:29:01 +000010210bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10211 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010212
10213 if (SubExpr->getType()->isRealFloatingType()) {
10214 Result.makeComplexFloat();
10215 APFloat &Imag = Result.FloatImag;
10216 if (!EvaluateFloat(SubExpr, Imag, Info))
10217 return false;
10218
10219 Result.FloatReal = APFloat(Imag.getSemantics());
10220 return true;
10221 } else {
10222 assert(SubExpr->getType()->isIntegerType() &&
10223 "Unexpected imaginary literal.");
10224
10225 Result.makeComplexInt();
10226 APSInt &Imag = Result.IntImag;
10227 if (!EvaluateInteger(SubExpr, Imag, Info))
10228 return false;
10229
10230 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10231 return true;
10232 }
10233}
10234
Peter Collingbournee9200682011-05-13 03:29:01 +000010235bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010236
John McCallfcef3cf2010-12-14 17:51:41 +000010237 switch (E->getCastKind()) {
10238 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010239 case CK_BaseToDerived:
10240 case CK_DerivedToBase:
10241 case CK_UncheckedDerivedToBase:
10242 case CK_Dynamic:
10243 case CK_ToUnion:
10244 case CK_ArrayToPointerDecay:
10245 case CK_FunctionToPointerDecay:
10246 case CK_NullToPointer:
10247 case CK_NullToMemberPointer:
10248 case CK_BaseToDerivedMemberPointer:
10249 case CK_DerivedToBaseMemberPointer:
10250 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010251 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010252 case CK_ConstructorConversion:
10253 case CK_IntegralToPointer:
10254 case CK_PointerToIntegral:
10255 case CK_PointerToBoolean:
10256 case CK_ToVoid:
10257 case CK_VectorSplat:
10258 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010259 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010260 case CK_IntegralToBoolean:
10261 case CK_IntegralToFloating:
10262 case CK_FloatingToIntegral:
10263 case CK_FloatingToBoolean:
10264 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010265 case CK_CPointerToObjCPointerCast:
10266 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010267 case CK_AnyPointerToBlockPointerCast:
10268 case CK_ObjCObjectLValueCast:
10269 case CK_FloatingComplexToReal:
10270 case CK_FloatingComplexToBoolean:
10271 case CK_IntegralComplexToReal:
10272 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010273 case CK_ARCProduceObject:
10274 case CK_ARCConsumeObject:
10275 case CK_ARCReclaimReturnedObject:
10276 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010277 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010278 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010279 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010280 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010281 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010282 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010283 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010284 case CK_FixedPointToBoolean:
John McCallfcef3cf2010-12-14 17:51:41 +000010285 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010286
John McCallfcef3cf2010-12-14 17:51:41 +000010287 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010288 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010289 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010291
10292 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010293 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010294 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010295 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010296
10297 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010298 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010299 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010300 return false;
10301
John McCallfcef3cf2010-12-14 17:51:41 +000010302 Result.makeComplexFloat();
10303 Result.FloatImag = APFloat(Real.getSemantics());
10304 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010305 }
10306
John McCallfcef3cf2010-12-14 17:51:41 +000010307 case CK_FloatingComplexCast: {
10308 if (!Visit(E->getSubExpr()))
10309 return false;
10310
10311 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10312 QualType From
10313 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10314
Richard Smith357362d2011-12-13 06:39:58 +000010315 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10316 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010317 }
10318
10319 case CK_FloatingComplexToIntegralComplex: {
10320 if (!Visit(E->getSubExpr()))
10321 return false;
10322
10323 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10324 QualType From
10325 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10326 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010327 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10328 To, Result.IntReal) &&
10329 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10330 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010331 }
10332
10333 case CK_IntegralRealToComplex: {
10334 APSInt &Real = Result.IntReal;
10335 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10336 return false;
10337
10338 Result.makeComplexInt();
10339 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10340 return true;
10341 }
10342
10343 case CK_IntegralComplexCast: {
10344 if (!Visit(E->getSubExpr()))
10345 return false;
10346
10347 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10348 QualType From
10349 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10350
Richard Smith911e1422012-01-30 22:27:01 +000010351 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10352 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010353 return true;
10354 }
10355
10356 case CK_IntegralComplexToFloatingComplex: {
10357 if (!Visit(E->getSubExpr()))
10358 return false;
10359
Ted Kremenek28831752012-08-23 20:46:57 +000010360 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010361 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010362 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010363 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010364 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10365 To, Result.FloatReal) &&
10366 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10367 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010368 }
10369 }
10370
10371 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010372}
10373
John McCall93d91dc2010-05-07 17:22:02 +000010374bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010375 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010376 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10377
Chandler Carrutha216cad2014-10-11 00:57:18 +000010378 // Track whether the LHS or RHS is real at the type system level. When this is
10379 // the case we can simplify our evaluation strategy.
10380 bool LHSReal = false, RHSReal = false;
10381
10382 bool LHSOK;
10383 if (E->getLHS()->getType()->isRealFloatingType()) {
10384 LHSReal = true;
10385 APFloat &Real = Result.FloatReal;
10386 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10387 if (LHSOK) {
10388 Result.makeComplexFloat();
10389 Result.FloatImag = APFloat(Real.getSemantics());
10390 }
10391 } else {
10392 LHSOK = Visit(E->getLHS());
10393 }
George Burgess IVa145e252016-05-25 22:38:36 +000010394 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010395 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010396
John McCall93d91dc2010-05-07 17:22:02 +000010397 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010398 if (E->getRHS()->getType()->isRealFloatingType()) {
10399 RHSReal = true;
10400 APFloat &Real = RHS.FloatReal;
10401 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10402 return false;
10403 RHS.makeComplexFloat();
10404 RHS.FloatImag = APFloat(Real.getSemantics());
10405 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010406 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010407
Chandler Carrutha216cad2014-10-11 00:57:18 +000010408 assert(!(LHSReal && RHSReal) &&
10409 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010410 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010411 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010412 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010413 if (Result.isComplexFloat()) {
10414 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10415 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010416 if (LHSReal)
10417 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10418 else if (!RHSReal)
10419 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10420 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010421 } else {
10422 Result.getComplexIntReal() += RHS.getComplexIntReal();
10423 Result.getComplexIntImag() += RHS.getComplexIntImag();
10424 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010425 break;
John McCalle3027922010-08-25 11:45:40 +000010426 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010427 if (Result.isComplexFloat()) {
10428 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10429 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010430 if (LHSReal) {
10431 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10432 Result.getComplexFloatImag().changeSign();
10433 } else if (!RHSReal) {
10434 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10435 APFloat::rmNearestTiesToEven);
10436 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010437 } else {
10438 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10439 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10440 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010441 break;
John McCalle3027922010-08-25 11:45:40 +000010442 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010443 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010444 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010445 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010446 // following naming scheme:
10447 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010448 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010449 APFloat &A = LHS.getComplexFloatReal();
10450 APFloat &B = LHS.getComplexFloatImag();
10451 APFloat &C = RHS.getComplexFloatReal();
10452 APFloat &D = RHS.getComplexFloatImag();
10453 APFloat &ResR = Result.getComplexFloatReal();
10454 APFloat &ResI = Result.getComplexFloatImag();
10455 if (LHSReal) {
10456 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10457 ResR = A * C;
10458 ResI = A * D;
10459 } else if (RHSReal) {
10460 ResR = C * A;
10461 ResI = C * B;
10462 } else {
10463 // In the fully general case, we need to handle NaNs and infinities
10464 // robustly.
10465 APFloat AC = A * C;
10466 APFloat BD = B * D;
10467 APFloat AD = A * D;
10468 APFloat BC = B * C;
10469 ResR = AC - BD;
10470 ResI = AD + BC;
10471 if (ResR.isNaN() && ResI.isNaN()) {
10472 bool Recalc = false;
10473 if (A.isInfinity() || B.isInfinity()) {
10474 A = APFloat::copySign(
10475 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10476 B = APFloat::copySign(
10477 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10478 if (C.isNaN())
10479 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10480 if (D.isNaN())
10481 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10482 Recalc = true;
10483 }
10484 if (C.isInfinity() || D.isInfinity()) {
10485 C = APFloat::copySign(
10486 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10487 D = APFloat::copySign(
10488 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10489 if (A.isNaN())
10490 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10491 if (B.isNaN())
10492 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10493 Recalc = true;
10494 }
10495 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10496 AD.isInfinity() || BC.isInfinity())) {
10497 if (A.isNaN())
10498 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10499 if (B.isNaN())
10500 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10501 if (C.isNaN())
10502 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10503 if (D.isNaN())
10504 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10505 Recalc = true;
10506 }
10507 if (Recalc) {
10508 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10509 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10510 }
10511 }
10512 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010513 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010514 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010515 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010516 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10517 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010518 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010519 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10520 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10521 }
10522 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010523 case BO_Div:
10524 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010525 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010526 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010527 // following naming scheme:
10528 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010529 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010530 APFloat &A = LHS.getComplexFloatReal();
10531 APFloat &B = LHS.getComplexFloatImag();
10532 APFloat &C = RHS.getComplexFloatReal();
10533 APFloat &D = RHS.getComplexFloatImag();
10534 APFloat &ResR = Result.getComplexFloatReal();
10535 APFloat &ResI = Result.getComplexFloatImag();
10536 if (RHSReal) {
10537 ResR = A / C;
10538 ResI = B / C;
10539 } else {
10540 if (LHSReal) {
10541 // No real optimizations we can do here, stub out with zero.
10542 B = APFloat::getZero(A.getSemantics());
10543 }
10544 int DenomLogB = 0;
10545 APFloat MaxCD = maxnum(abs(C), abs(D));
10546 if (MaxCD.isFinite()) {
10547 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010548 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10549 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010550 }
10551 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010552 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10553 APFloat::rmNearestTiesToEven);
10554 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10555 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010556 if (ResR.isNaN() && ResI.isNaN()) {
10557 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10558 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10559 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10560 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10561 D.isFinite()) {
10562 A = APFloat::copySign(
10563 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10564 B = APFloat::copySign(
10565 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10566 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10567 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10568 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10569 C = APFloat::copySign(
10570 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10571 D = APFloat::copySign(
10572 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10573 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10574 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10575 }
10576 }
10577 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010578 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010579 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10580 return Error(E, diag::note_expr_divide_by_zero);
10581
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010582 ComplexValue LHS = Result;
10583 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10584 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10585 Result.getComplexIntReal() =
10586 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10587 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10588 Result.getComplexIntImag() =
10589 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10590 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10591 }
10592 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010593 }
10594
John McCall93d91dc2010-05-07 17:22:02 +000010595 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010596}
10597
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010598bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10599 // Get the operand value into 'Result'.
10600 if (!Visit(E->getSubExpr()))
10601 return false;
10602
10603 switch (E->getOpcode()) {
10604 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010605 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010606 case UO_Extension:
10607 return true;
10608 case UO_Plus:
10609 // The result is always just the subexpr.
10610 return true;
10611 case UO_Minus:
10612 if (Result.isComplexFloat()) {
10613 Result.getComplexFloatReal().changeSign();
10614 Result.getComplexFloatImag().changeSign();
10615 }
10616 else {
10617 Result.getComplexIntReal() = -Result.getComplexIntReal();
10618 Result.getComplexIntImag() = -Result.getComplexIntImag();
10619 }
10620 return true;
10621 case UO_Not:
10622 if (Result.isComplexFloat())
10623 Result.getComplexFloatImag().changeSign();
10624 else
10625 Result.getComplexIntImag() = -Result.getComplexIntImag();
10626 return true;
10627 }
10628}
10629
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010630bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10631 if (E->getNumInits() == 2) {
10632 if (E->getType()->isComplexType()) {
10633 Result.makeComplexFloat();
10634 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10635 return false;
10636 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10637 return false;
10638 } else {
10639 Result.makeComplexInt();
10640 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10641 return false;
10642 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10643 return false;
10644 }
10645 return true;
10646 }
10647 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10648}
10649
Anders Carlsson537969c2008-11-16 20:27:53 +000010650//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010651// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10652// implicit conversion.
10653//===----------------------------------------------------------------------===//
10654
10655namespace {
10656class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010657 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010658 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010659 APValue &Result;
10660public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010661 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10662 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010663
10664 bool Success(const APValue &V, const Expr *E) {
10665 Result = V;
10666 return true;
10667 }
10668
10669 bool ZeroInitialization(const Expr *E) {
10670 ImplicitValueInitExpr VIE(
10671 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010672 // For atomic-qualified class (and array) types in C++, initialize the
10673 // _Atomic-wrapped subobject directly, in-place.
10674 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10675 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010676 }
10677
10678 bool VisitCastExpr(const CastExpr *E) {
10679 switch (E->getCastKind()) {
10680 default:
10681 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10682 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010683 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10684 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010685 }
10686 }
10687};
10688} // end anonymous namespace
10689
Richard Smith64cb9ca2017-02-22 22:09:50 +000010690static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10691 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010692 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010693 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010694}
10695
10696//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010697// Void expression evaluation, primarily for a cast to void on the LHS of a
10698// comma operator
10699//===----------------------------------------------------------------------===//
10700
10701namespace {
10702class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010703 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010704public:
10705 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10706
Richard Smith2e312c82012-03-03 22:46:17 +000010707 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010708
Richard Smith7cd577b2017-08-17 19:35:50 +000010709 bool ZeroInitialization(const Expr *E) { return true; }
10710
Richard Smith42d3af92011-12-07 00:43:50 +000010711 bool VisitCastExpr(const CastExpr *E) {
10712 switch (E->getCastKind()) {
10713 default:
10714 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10715 case CK_ToVoid:
10716 VisitIgnoredValue(E->getSubExpr());
10717 return true;
10718 }
10719 }
Hal Finkela8443c32014-07-17 14:49:58 +000010720
10721 bool VisitCallExpr(const CallExpr *E) {
10722 switch (E->getBuiltinCallee()) {
10723 default:
10724 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10725 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010726 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010727 // The argument is not evaluated!
10728 return true;
10729 }
10730 }
Richard Smith42d3af92011-12-07 00:43:50 +000010731};
10732} // end anonymous namespace
10733
10734static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10735 assert(E->isRValue() && E->getType()->isVoidType());
10736 return VoidExprEvaluator(Info).Visit(E);
10737}
10738
10739//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010740// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010741//===----------------------------------------------------------------------===//
10742
Richard Smith2e312c82012-03-03 22:46:17 +000010743static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010744 // In C, function designators are not lvalues, but we evaluate them as if they
10745 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010746 QualType T = E->getType();
10747 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010748 LValue LV;
10749 if (!EvaluateLValue(E, LV, Info))
10750 return false;
10751 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010752 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010753 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010754 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010755 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010756 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010757 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010758 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010759 LValue LV;
10760 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010761 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010762 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010763 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010764 llvm::APFloat F(0.0);
10765 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010766 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010767 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010768 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010769 ComplexValue C;
10770 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010771 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010772 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010773 } else if (T->isFixedPointType()) {
10774 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010775 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010776 MemberPtr P;
10777 if (!EvaluateMemberPointer(E, P, Info))
10778 return false;
10779 P.moveInto(Result);
10780 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010781 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010782 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010783 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010784 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010785 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010786 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010787 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010788 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010789 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010790 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010791 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010792 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010793 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010794 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010795 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010796 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010797 if (!EvaluateVoid(E, Info))
10798 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010799 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010800 QualType Unqual = T.getAtomicUnqualifiedType();
10801 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10802 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010803 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010804 if (!EvaluateAtomic(E, &LV, Value, Info))
10805 return false;
10806 } else {
10807 if (!EvaluateAtomic(E, nullptr, Result, Info))
10808 return false;
10809 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010810 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010811 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010812 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010813 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010814 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010815 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010816 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010817
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010818 return true;
10819}
10820
Richard Smithb228a862012-02-15 02:18:13 +000010821/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10822/// cases, the in-place evaluation is essential, since later initializers for
10823/// an object can indirectly refer to subobjects which were initialized earlier.
10824static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010825 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010826 assert(!E->isValueDependent());
10827
Richard Smith7525ff62013-05-09 07:14:00 +000010828 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010829 return false;
10830
10831 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010832 // Evaluate arrays and record types in-place, so that later initializers can
10833 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010834 QualType T = E->getType();
10835 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010836 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010837 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010838 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010839 else if (T->isAtomicType()) {
10840 QualType Unqual = T.getAtomicUnqualifiedType();
10841 if (Unqual->isArrayType() || Unqual->isRecordType())
10842 return EvaluateAtomic(E, &This, Result, Info);
10843 }
Richard Smithed5165f2011-11-04 05:33:44 +000010844 }
10845
10846 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010847 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010848}
10849
Richard Smithf57d8cb2011-12-09 22:58:01 +000010850/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10851/// lvalue-to-rvalue cast if it is an lvalue.
10852static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010853 if (E->getType().isNull())
10854 return false;
10855
Nick Lewyckyc190f962017-05-02 01:06:16 +000010856 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010857 return false;
10858
Richard Smith2e312c82012-03-03 22:46:17 +000010859 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010860 return false;
10861
10862 if (E->isGLValue()) {
10863 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010864 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010865 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010866 return false;
10867 }
10868
Richard Smith2e312c82012-03-03 22:46:17 +000010869 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010870 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010871}
Richard Smith11562c52011-10-28 17:51:58 +000010872
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010873static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010874 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010875 // Fast-path evaluations of integer literals, since we sometimes see files
10876 // containing vast quantities of these.
10877 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10878 Result.Val = APValue(APSInt(L->getValue(),
10879 L->getType()->isUnsignedIntegerType()));
10880 IsConst = true;
10881 return true;
10882 }
James Dennett0492ef02014-03-14 17:44:10 +000010883
10884 // This case should be rare, but we need to check it before we check on
10885 // the type below.
10886 if (Exp->getType().isNull()) {
10887 IsConst = false;
10888 return true;
10889 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010890
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010891 // FIXME: Evaluating values of large array and record types can cause
10892 // performance problems. Only do so in C++11 for now.
10893 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10894 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010895 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010896 IsConst = false;
10897 return true;
10898 }
10899 return false;
10900}
10901
Fangrui Song407659a2018-11-30 23:41:18 +000010902static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10903 Expr::SideEffectsKind SEK) {
10904 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10905 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10906}
10907
10908static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10909 const ASTContext &Ctx, EvalInfo &Info) {
10910 bool IsConst;
10911 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10912 return IsConst;
10913
10914 return EvaluateAsRValue(Info, E, Result.Val);
10915}
10916
10917static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10918 const ASTContext &Ctx,
10919 Expr::SideEffectsKind AllowSideEffects,
10920 EvalInfo &Info) {
10921 if (!E->getType()->isIntegralOrEnumerationType())
10922 return false;
10923
10924 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
10925 !ExprResult.Val.isInt() ||
10926 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10927 return false;
10928
10929 return true;
10930}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010931
Richard Smith7b553f12011-10-29 00:50:52 +000010932/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010933/// any crazy technique (that has nothing to do with language standards) that
10934/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010935/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10936/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000010937bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
10938 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010939 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000010940 Info.InConstantContext = InConstantContext;
10941 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000010942}
10943
Jay Foad39c79802011-01-12 09:06:06 +000010944bool Expr::EvaluateAsBooleanCondition(bool &Result,
10945 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010946 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010947 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010948 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010949}
10950
Fangrui Song407659a2018-11-30 23:41:18 +000010951bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000010952 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000010953 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10954 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000010955}
10956
Richard Trieube234c32016-04-21 21:04:55 +000010957bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10958 SideEffectsKind AllowSideEffects) const {
10959 if (!getType()->isRealFloatingType())
10960 return false;
10961
10962 EvalResult ExprResult;
10963 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010964 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010965 return false;
10966
10967 Result = ExprResult.Val.getFloat();
10968 return true;
10969}
10970
Jay Foad39c79802011-01-12 09:06:06 +000010971bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010972 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010973
John McCall45d55e42010-05-07 21:00:08 +000010974 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010975 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10976 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010977 Ctx.getLValueReferenceType(getType()), LV,
10978 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010979 return false;
10980
Richard Smith2e312c82012-03-03 22:46:17 +000010981 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010982 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010983}
10984
Reid Kleckner1a840d22018-05-10 18:57:35 +000010985bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10986 const ASTContext &Ctx) const {
10987 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10988 EvalInfo Info(Ctx, Result, EM);
10989 if (!::Evaluate(Result.Val, Info, this))
10990 return false;
10991
10992 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10993 Usage);
10994}
10995
Richard Smithd0b4dd62011-12-19 06:19:21 +000010996bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10997 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010998 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010999 // FIXME: Evaluating initializers for large array and record types can cause
11000 // performance problems. Only do so in C++11 for now.
11001 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011002 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011003 return false;
11004
Richard Smithd0b4dd62011-12-19 06:19:21 +000011005 Expr::EvalStatus EStatus;
11006 EStatus.Diag = &Notes;
11007
Richard Smith0c6124b2015-12-03 01:36:22 +000011008 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11009 ? EvalInfo::EM_ConstantExpression
11010 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011011 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011012 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011013
11014 LValue LVal;
11015 LVal.set(VD);
11016
Richard Smithfddd3842011-12-30 21:15:51 +000011017 // C++11 [basic.start.init]p2:
11018 // Variables with static storage duration or thread storage duration shall be
11019 // zero-initialized before any other initialization takes place.
11020 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011021 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011022 !VD->getType()->isReferenceType()) {
11023 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011024 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011025 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011026 return false;
11027 }
11028
Richard Smith7525ff62013-05-09 07:14:00 +000011029 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11030 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011031 EStatus.HasSideEffects)
11032 return false;
11033
11034 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11035 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011036}
11037
Richard Smith7b553f12011-10-29 00:50:52 +000011038/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11039/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011040bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011041 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011042 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011043 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011044}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011045
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011046APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011047 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011048 EvalResult EVResult;
11049 EVResult.Diag = Diag;
11050 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11051 Info.InConstantContext = true;
11052
11053 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011054 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011055 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011056 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011057
Fangrui Song407659a2018-11-30 23:41:18 +000011058 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011059}
John McCall864e3962010-05-07 05:32:02 +000011060
David Bolvansky3b6ae572018-10-18 20:49:06 +000011061APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11062 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011063 EvalResult EVResult;
11064 EVResult.Diag = Diag;
11065 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11066 Info.InConstantContext = true;
11067
11068 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011069 (void)Result;
11070 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011071 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011072
Fangrui Song407659a2018-11-30 23:41:18 +000011073 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011074}
11075
Richard Smithe9ff7702013-11-05 22:23:30 +000011076void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011077 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011078 EvalResult EVResult;
11079 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11080 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11081 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011082 }
11083}
11084
Richard Smithe6c01442013-06-05 00:46:14 +000011085bool Expr::EvalResult::isGlobalLValue() const {
11086 assert(Val.isLValue());
11087 return IsGlobalLValue(Val.getLValueBase());
11088}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011089
11090
John McCall864e3962010-05-07 05:32:02 +000011091/// isIntegerConstantExpr - this recursive routine will test if an expression is
11092/// an integer constant expression.
11093
11094/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11095/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011096
11097// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011098// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11099// and a (possibly null) SourceLocation indicating the location of the problem.
11100//
John McCall864e3962010-05-07 05:32:02 +000011101// Note that to reduce code duplication, this helper does no evaluation
11102// itself; the caller checks whether the expression is evaluatable, and
11103// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011104// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011105
Dan Gohman28ade552010-07-26 21:25:24 +000011106namespace {
11107
Richard Smith9e575da2012-12-28 13:25:52 +000011108enum ICEKind {
11109 /// This expression is an ICE.
11110 IK_ICE,
11111 /// This expression is not an ICE, but if it isn't evaluated, it's
11112 /// a legal subexpression for an ICE. This return value is used to handle
11113 /// the comma operator in C99 mode, and non-constant subexpressions.
11114 IK_ICEIfUnevaluated,
11115 /// This expression is not an ICE, and is not a legal subexpression for one.
11116 IK_NotICE
11117};
11118
John McCall864e3962010-05-07 05:32:02 +000011119struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011120 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011121 SourceLocation Loc;
11122
Richard Smith9e575da2012-12-28 13:25:52 +000011123 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011124};
11125
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011126}
Dan Gohman28ade552010-07-26 21:25:24 +000011127
Richard Smith9e575da2012-12-28 13:25:52 +000011128static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11129
11130static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011131
Craig Toppera31a8822013-08-22 07:09:37 +000011132static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011133 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011134 Expr::EvalStatus Status;
11135 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11136
11137 Info.InConstantContext = true;
11138 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011139 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011140 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011141
John McCall864e3962010-05-07 05:32:02 +000011142 return NoDiag();
11143}
11144
Craig Toppera31a8822013-08-22 07:09:37 +000011145static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011146 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011147 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011148 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011149
11150 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011151#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011152#define STMT(Node, Base) case Expr::Node##Class:
11153#define EXPR(Node, Base)
11154#include "clang/AST/StmtNodes.inc"
11155 case Expr::PredefinedExprClass:
11156 case Expr::FloatingLiteralClass:
11157 case Expr::ImaginaryLiteralClass:
11158 case Expr::StringLiteralClass:
11159 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011160 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011161 case Expr::MemberExprClass:
11162 case Expr::CompoundAssignOperatorClass:
11163 case Expr::CompoundLiteralExprClass:
11164 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011165 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011166 case Expr::ArrayInitLoopExprClass:
11167 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011168 case Expr::NoInitExprClass:
11169 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011170 case Expr::ImplicitValueInitExprClass:
11171 case Expr::ParenListExprClass:
11172 case Expr::VAArgExprClass:
11173 case Expr::AddrLabelExprClass:
11174 case Expr::StmtExprClass:
11175 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011176 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011177 case Expr::CXXDynamicCastExprClass:
11178 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011179 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011180 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011181 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011182 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011183 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011184 case Expr::CXXThisExprClass:
11185 case Expr::CXXThrowExprClass:
11186 case Expr::CXXNewExprClass:
11187 case Expr::CXXDeleteExprClass:
11188 case Expr::CXXPseudoDestructorExprClass:
11189 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011190 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011191 case Expr::DependentScopeDeclRefExprClass:
11192 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011193 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011194 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011195 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011196 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011197 case Expr::CXXTemporaryObjectExprClass:
11198 case Expr::CXXUnresolvedConstructExprClass:
11199 case Expr::CXXDependentScopeMemberExprClass:
11200 case Expr::UnresolvedMemberExprClass:
11201 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011202 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011203 case Expr::ObjCArrayLiteralClass:
11204 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011205 case Expr::ObjCEncodeExprClass:
11206 case Expr::ObjCMessageExprClass:
11207 case Expr::ObjCSelectorExprClass:
11208 case Expr::ObjCProtocolExprClass:
11209 case Expr::ObjCIvarRefExprClass:
11210 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011211 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011212 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011213 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011214 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011215 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011216 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011217 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011218 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011219 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011220 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011221 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011222 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011223 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011224 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011225 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011226 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011227 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011228 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011229 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011230 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011231 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011232 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011233
Richard Smithf137f932014-01-25 20:50:08 +000011234 case Expr::InitListExprClass: {
11235 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11236 // form "T x = { a };" is equivalent to "T x = a;".
11237 // Unless we're initializing a reference, T is a scalar as it is known to be
11238 // of integral or enumeration type.
11239 if (E->isRValue())
11240 if (cast<InitListExpr>(E)->getNumInits() == 1)
11241 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011242 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011243 }
11244
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011245 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011246 case Expr::GNUNullExprClass:
11247 // GCC considers the GNU __null value to be an integral constant expression.
11248 return NoDiag();
11249
John McCall7c454bb2011-07-15 05:09:51 +000011250 case Expr::SubstNonTypeTemplateParmExprClass:
11251 return
11252 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11253
Bill Wendling7c44da22018-10-31 03:48:47 +000011254 case Expr::ConstantExprClass:
11255 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11256
John McCall864e3962010-05-07 05:32:02 +000011257 case Expr::ParenExprClass:
11258 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011259 case Expr::GenericSelectionExprClass:
11260 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011261 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011262 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011263 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011264 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011265 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011266 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011267 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011268 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011269 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011270 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011271 return NoDiag();
11272 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011273 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011274 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11275 // constant expressions, but they can never be ICEs because an ICE cannot
11276 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011277 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011278 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011279 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011280 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011281 }
Richard Smith6365c912012-02-24 22:12:32 +000011282 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011283 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11284 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011285 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011286 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011287 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011288 // Parameter variables are never constants. Without this check,
11289 // getAnyInitializer() can find a default argument, which leads
11290 // to chaos.
11291 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011292 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011293
11294 // C++ 7.1.5.1p2
11295 // A variable of non-volatile const-qualified integral or enumeration
11296 // type initialized by an ICE can be used in ICEs.
11297 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011298 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011299 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011300
Richard Smithd0b4dd62011-12-19 06:19:21 +000011301 const VarDecl *VD;
11302 // Look for a declaration of this variable that has an initializer, and
11303 // check whether it is an ICE.
11304 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11305 return NoDiag();
11306 else
Richard Smith9e575da2012-12-28 13:25:52 +000011307 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011308 }
11309 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011310 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011311 }
John McCall864e3962010-05-07 05:32:02 +000011312 case Expr::UnaryOperatorClass: {
11313 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11314 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011315 case UO_PostInc:
11316 case UO_PostDec:
11317 case UO_PreInc:
11318 case UO_PreDec:
11319 case UO_AddrOf:
11320 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011321 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011322 // C99 6.6/3 allows increment and decrement within unevaluated
11323 // subexpressions of constant expressions, but they can never be ICEs
11324 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011325 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011326 case UO_Extension:
11327 case UO_LNot:
11328 case UO_Plus:
11329 case UO_Minus:
11330 case UO_Not:
11331 case UO_Real:
11332 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011333 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011334 }
Reid Klecknere540d972018-11-01 17:51:48 +000011335 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011336 }
11337 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011338 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11339 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11340 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11341 // compliance: we should warn earlier for offsetof expressions with
11342 // array subscripts that aren't ICEs, and if the array subscripts
11343 // are ICEs, the value of the offsetof must be an integer constant.
11344 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011345 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011346 case Expr::UnaryExprOrTypeTraitExprClass: {
11347 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11348 if ((Exp->getKind() == UETT_SizeOf) &&
11349 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011350 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011351 return NoDiag();
11352 }
11353 case Expr::BinaryOperatorClass: {
11354 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11355 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011356 case BO_PtrMemD:
11357 case BO_PtrMemI:
11358 case BO_Assign:
11359 case BO_MulAssign:
11360 case BO_DivAssign:
11361 case BO_RemAssign:
11362 case BO_AddAssign:
11363 case BO_SubAssign:
11364 case BO_ShlAssign:
11365 case BO_ShrAssign:
11366 case BO_AndAssign:
11367 case BO_XorAssign:
11368 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011369 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11370 // constant expressions, but they can never be ICEs because an ICE cannot
11371 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011372 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011373
John McCalle3027922010-08-25 11:45:40 +000011374 case BO_Mul:
11375 case BO_Div:
11376 case BO_Rem:
11377 case BO_Add:
11378 case BO_Sub:
11379 case BO_Shl:
11380 case BO_Shr:
11381 case BO_LT:
11382 case BO_GT:
11383 case BO_LE:
11384 case BO_GE:
11385 case BO_EQ:
11386 case BO_NE:
11387 case BO_And:
11388 case BO_Xor:
11389 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011390 case BO_Comma:
11391 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011392 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11393 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011394 if (Exp->getOpcode() == BO_Div ||
11395 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011396 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011397 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011398 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011399 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011400 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011401 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011402 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011403 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011404 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011405 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011406 }
11407 }
11408 }
John McCalle3027922010-08-25 11:45:40 +000011409 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011410 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011411 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11412 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011413 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011414 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011415 } else {
11416 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011417 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011418 }
11419 }
Richard Smith9e575da2012-12-28 13:25:52 +000011420 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011421 }
John McCalle3027922010-08-25 11:45:40 +000011422 case BO_LAnd:
11423 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011424 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11425 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011426 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011427 // Rare case where the RHS has a comma "side-effect"; we need
11428 // to actually check the condition to see whether the side
11429 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011430 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011431 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011432 return RHSResult;
11433 return NoDiag();
11434 }
11435
Richard Smith9e575da2012-12-28 13:25:52 +000011436 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011437 }
11438 }
Reid Klecknere540d972018-11-01 17:51:48 +000011439 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011440 }
11441 case Expr::ImplicitCastExprClass:
11442 case Expr::CStyleCastExprClass:
11443 case Expr::CXXFunctionalCastExprClass:
11444 case Expr::CXXStaticCastExprClass:
11445 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011446 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011447 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011448 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011449 if (isa<ExplicitCastExpr>(E)) {
11450 if (const FloatingLiteral *FL
11451 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11452 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11453 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11454 APSInt IgnoredVal(DestWidth, !DestSigned);
11455 bool Ignored;
11456 // If the value does not fit in the destination type, the behavior is
11457 // undefined, so we are not required to treat it as a constant
11458 // expression.
11459 if (FL->getValue().convertToInteger(IgnoredVal,
11460 llvm::APFloat::rmTowardZero,
11461 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011462 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011463 return NoDiag();
11464 }
11465 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011466 switch (cast<CastExpr>(E)->getCastKind()) {
11467 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011468 case CK_AtomicToNonAtomic:
11469 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011470 case CK_NoOp:
11471 case CK_IntegralToBoolean:
11472 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011473 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011474 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011475 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011476 }
John McCall864e3962010-05-07 05:32:02 +000011477 }
John McCallc07a0c72011-02-17 10:25:35 +000011478 case Expr::BinaryConditionalOperatorClass: {
11479 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11480 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011481 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011482 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011483 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11484 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11485 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011486 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011487 return FalseResult;
11488 }
John McCall864e3962010-05-07 05:32:02 +000011489 case Expr::ConditionalOperatorClass: {
11490 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11491 // If the condition (ignoring parens) is a __builtin_constant_p call,
11492 // then only the true side is actually considered in an integer constant
11493 // expression, and it is fully evaluated. This is an important GNU
11494 // extension. See GCC PR38377 for discussion.
11495 if (const CallExpr *CallCE
11496 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011497 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011498 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011499 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011500 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011501 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011502
Richard Smithf57d8cb2011-12-09 22:58:01 +000011503 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11504 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011505
Richard Smith9e575da2012-12-28 13:25:52 +000011506 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011507 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011508 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011509 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011510 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011511 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011512 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011513 return NoDiag();
11514 // Rare case where the diagnostics depend on which side is evaluated
11515 // Note that if we get here, CondResult is 0, and at least one of
11516 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011517 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011518 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011519 return TrueResult;
11520 }
11521 case Expr::CXXDefaultArgExprClass:
11522 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011523 case Expr::CXXDefaultInitExprClass:
11524 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011525 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011526 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011527 }
11528 }
11529
David Blaikiee4d798f2012-01-20 21:50:17 +000011530 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011531}
11532
Richard Smithf57d8cb2011-12-09 22:58:01 +000011533/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011534static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011535 const Expr *E,
11536 llvm::APSInt *Value,
11537 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011538 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011539 if (Loc) *Loc = E->getExprLoc();
11540 return false;
11541 }
11542
Richard Smith66e05fe2012-01-18 05:21:49 +000011543 APValue Result;
11544 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011545 return false;
11546
Richard Smith98710fc2014-11-13 23:03:19 +000011547 if (!Result.isInt()) {
11548 if (Loc) *Loc = E->getExprLoc();
11549 return false;
11550 }
11551
Richard Smith66e05fe2012-01-18 05:21:49 +000011552 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011553 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011554}
11555
Craig Toppera31a8822013-08-22 07:09:37 +000011556bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11557 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011558 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011559 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011560
Richard Smith9e575da2012-12-28 13:25:52 +000011561 ICEDiag D = CheckICE(this, Ctx);
11562 if (D.Kind != IK_ICE) {
11563 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011564 return false;
11565 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011566 return true;
11567}
11568
Craig Toppera31a8822013-08-22 07:09:37 +000011569bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011570 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011571 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011572 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11573
11574 if (!isIntegerConstantExpr(Ctx, Loc))
11575 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011576
Richard Smith5c40f092015-12-04 03:00:44 +000011577 // The only possible side-effects here are due to UB discovered in the
11578 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11579 // required to treat the expression as an ICE, so we produce the folded
11580 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011581 EvalResult ExprResult;
11582 Expr::EvalStatus Status;
11583 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11584 Info.InConstantContext = true;
11585
11586 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011587 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011588
11589 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011590 return true;
11591}
Richard Smith66e05fe2012-01-18 05:21:49 +000011592
Craig Toppera31a8822013-08-22 07:09:37 +000011593bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011594 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011595}
11596
Craig Toppera31a8822013-08-22 07:09:37 +000011597bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011598 SourceLocation *Loc) const {
11599 // We support this checking in C++98 mode in order to diagnose compatibility
11600 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011601 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011602
Richard Smith98a0a492012-02-14 21:38:30 +000011603 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011604 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011605 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011606 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011607 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011608
11609 APValue Scratch;
11610 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11611
11612 if (!Diags.empty()) {
11613 IsConstExpr = false;
11614 if (Loc) *Loc = Diags[0].first;
11615 } else if (!IsConstExpr) {
11616 // FIXME: This shouldn't happen.
11617 if (Loc) *Loc = getExprLoc();
11618 }
11619
11620 return IsConstExpr;
11621}
Richard Smith253c2a32012-01-27 01:14:48 +000011622
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011623bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11624 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011625 ArrayRef<const Expr*> Args,
11626 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011627 Expr::EvalStatus Status;
11628 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11629
George Burgess IV177399e2017-01-09 04:12:14 +000011630 LValue ThisVal;
11631 const LValue *ThisPtr = nullptr;
11632 if (This) {
11633#ifndef NDEBUG
11634 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11635 assert(MD && "Don't provide `this` for non-methods.");
11636 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11637#endif
11638 if (EvaluateObjectArgument(Info, This, ThisVal))
11639 ThisPtr = &ThisVal;
11640 if (Info.EvalStatus.HasSideEffects)
11641 return false;
11642 }
11643
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011644 ArgVector ArgValues(Args.size());
11645 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11646 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011647 if ((*I)->isValueDependent() ||
11648 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011649 // If evaluation fails, throw away the argument entirely.
11650 ArgValues[I - Args.begin()] = APValue();
11651 if (Info.EvalStatus.HasSideEffects)
11652 return false;
11653 }
11654
11655 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011656 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011657 ArgValues.data());
11658 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11659}
11660
Richard Smith253c2a32012-01-27 01:14:48 +000011661bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011662 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011663 PartialDiagnosticAt> &Diags) {
11664 // FIXME: It would be useful to check constexpr function templates, but at the
11665 // moment the constant expression evaluator cannot cope with the non-rigorous
11666 // ASTs which we build for dependent expressions.
11667 if (FD->isDependentContext())
11668 return true;
11669
11670 Expr::EvalStatus Status;
11671 Status.Diag = &Diags;
11672
Richard Smith6d4c6582013-11-05 22:18:15 +000011673 EvalInfo Info(FD->getASTContext(), Status,
11674 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011675 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011676
11677 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011678 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011679
Richard Smith7525ff62013-05-09 07:14:00 +000011680 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011681 // is a temporary being used as the 'this' pointer.
11682 LValue This;
11683 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011684 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011685
Richard Smith253c2a32012-01-27 01:14:48 +000011686 ArrayRef<const Expr*> Args;
11687
Richard Smith2e312c82012-03-03 22:46:17 +000011688 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011689 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11690 // Evaluate the call as a constant initializer, to allow the construction
11691 // of objects of non-literal types.
11692 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011693 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11694 } else {
11695 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011696 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011697 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011698 }
Richard Smith253c2a32012-01-27 01:14:48 +000011699
11700 return Diags.empty();
11701}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011702
11703bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11704 const FunctionDecl *FD,
11705 SmallVectorImpl<
11706 PartialDiagnosticAt> &Diags) {
11707 Expr::EvalStatus Status;
11708 Status.Diag = &Diags;
11709
11710 EvalInfo Info(FD->getASTContext(), Status,
11711 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11712
11713 // Fabricate a call stack frame to give the arguments a plausible cover story.
11714 ArrayRef<const Expr*> Args;
11715 ArgVector ArgValues(0);
11716 bool Success = EvaluateArgs(Args, ArgValues, Info);
11717 (void)Success;
11718 assert(Success &&
11719 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011720 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011721
11722 APValue ResultScratch;
11723 Evaluate(ResultScratch, Info, E);
11724 return Diags.empty();
11725}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011726
11727bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11728 unsigned Type) const {
11729 if (!getType()->isPointerType())
11730 return false;
11731
11732 Expr::EvalStatus Status;
11733 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011734 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011735}