blob: 5eb2f2e7b84b7c546db1f62b6d8f7ffb295a0ee4 [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
510 // on the overall stack usage of deeply-recursing constexpr evaluataions.
511 // (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
1293namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001294 struct ComplexValue {
1295 private:
1296 bool IsInt;
1297
1298 public:
1299 APSInt IntReal, IntImag;
1300 APFloat FloatReal, FloatImag;
1301
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001302 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001303
1304 void makeComplexFloat() { IsInt = false; }
1305 bool isComplexFloat() const { return !IsInt; }
1306 APFloat &getComplexFloatReal() { return FloatReal; }
1307 APFloat &getComplexFloatImag() { return FloatImag; }
1308
1309 void makeComplexInt() { IsInt = true; }
1310 bool isComplexInt() const { return IsInt; }
1311 APSInt &getComplexIntReal() { return IntReal; }
1312 APSInt &getComplexIntImag() { return IntImag; }
1313
Richard Smith2e312c82012-03-03 22:46:17 +00001314 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001315 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001316 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001317 else
Richard Smith2e312c82012-03-03 22:46:17 +00001318 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001319 }
Richard Smith2e312c82012-03-03 22:46:17 +00001320 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001321 assert(v.isComplexFloat() || v.isComplexInt());
1322 if (v.isComplexFloat()) {
1323 makeComplexFloat();
1324 FloatReal = v.getComplexFloatReal();
1325 FloatImag = v.getComplexFloatImag();
1326 } else {
1327 makeComplexInt();
1328 IntReal = v.getComplexIntReal();
1329 IntImag = v.getComplexIntImag();
1330 }
1331 }
John McCall93d91dc2010-05-07 17:22:02 +00001332 };
John McCall45d55e42010-05-07 21:00:08 +00001333
1334 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001335 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001336 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001337 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001338 bool IsNullPtr : 1;
1339 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001340
Richard Smithce40ad62011-11-12 22:28:03 +00001341 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001342 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001343 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001344 SubobjectDesignator &getLValueDesignator() { return Designator; }
1345 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001346 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001347
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001348 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1349 unsigned getLValueVersion() const { return Base.getVersion(); }
1350
Richard Smith2e312c82012-03-03 22:46:17 +00001351 void moveInto(APValue &V) const {
1352 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001353 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001354 else {
1355 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001356 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001357 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001358 }
John McCall45d55e42010-05-07 21:00:08 +00001359 }
Richard Smith2e312c82012-03-03 22:46:17 +00001360 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001361 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001362 Base = V.getLValueBase();
1363 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001364 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001365 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001366 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001367 }
1368
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001369 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001370#ifndef NDEBUG
1371 // We only allow a few types of invalid bases. Enforce that here.
1372 if (BInvalid) {
1373 const auto *E = B.get<const Expr *>();
1374 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1375 "Unexpected type of invalid base");
1376 }
1377#endif
1378
Richard Smithce40ad62011-11-12 22:28:03 +00001379 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001380 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001381 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001382 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001383 IsNullPtr = false;
1384 }
1385
1386 void setNull(QualType PointerTy, uint64_t TargetVal) {
1387 Base = (Expr *)nullptr;
1388 Offset = CharUnits::fromQuantity(TargetVal);
1389 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001390 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1391 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001392 }
1393
George Burgess IV3a03fab2015-09-04 21:28:13 +00001394 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001395 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001396 }
1397
Richard Smitha8105bc2012-01-06 16:39:00 +00001398 // Check that this LValue is not based on a null pointer. If it is, produce
1399 // a diagnostic and mark the designator as invalid.
1400 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1401 CheckSubobjectKind CSK) {
1402 if (Designator.Invalid)
1403 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001404 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001405 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001406 << CSK;
1407 Designator.setInvalid();
1408 return false;
1409 }
1410 return true;
1411 }
1412
1413 // Check this LValue refers to an object. If not, set the designator to be
1414 // invalid and emit a diagnostic.
1415 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001416 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001417 Designator.checkSubobject(Info, E, CSK);
1418 }
1419
1420 void addDecl(EvalInfo &Info, const Expr *E,
1421 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001422 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1423 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001424 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001425 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1426 if (!Designator.Entries.empty()) {
1427 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1428 Designator.setInvalid();
1429 return;
1430 }
Richard Smithefdb5032017-11-15 03:03:56 +00001431 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1432 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1433 Designator.FirstEntryIsAnUnsizedArray = true;
1434 Designator.addUnsizedArrayUnchecked(ElemTy);
1435 }
George Burgess IVe3763372016-12-22 02:50:20 +00001436 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001437 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001438 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1439 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001440 }
Richard Smith66c96992012-02-18 22:04:06 +00001441 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001442 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1443 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001444 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001445 void clearIsNullPointer() {
1446 IsNullPtr = false;
1447 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001448 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1449 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001450 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1451 // but we're not required to diagnose it and it's valid in C++.)
1452 if (!Index)
1453 return;
1454
1455 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1456 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1457 // offsets.
1458 uint64_t Offset64 = Offset.getQuantity();
1459 uint64_t ElemSize64 = ElementSize.getQuantity();
1460 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1461 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1462
1463 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001464 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001465 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001466 }
1467 void adjustOffset(CharUnits N) {
1468 Offset += N;
1469 if (N.getQuantity())
1470 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001471 }
John McCall45d55e42010-05-07 21:00:08 +00001472 };
Richard Smith027bf112011-11-17 22:56:20 +00001473
1474 struct MemberPtr {
1475 MemberPtr() {}
1476 explicit MemberPtr(const ValueDecl *Decl) :
1477 DeclAndIsDerivedMember(Decl, false), Path() {}
1478
1479 /// The member or (direct or indirect) field referred to by this member
1480 /// pointer, or 0 if this is a null member pointer.
1481 const ValueDecl *getDecl() const {
1482 return DeclAndIsDerivedMember.getPointer();
1483 }
1484 /// Is this actually a member of some type derived from the relevant class?
1485 bool isDerivedMember() const {
1486 return DeclAndIsDerivedMember.getInt();
1487 }
1488 /// Get the class which the declaration actually lives in.
1489 const CXXRecordDecl *getContainingRecord() const {
1490 return cast<CXXRecordDecl>(
1491 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1492 }
1493
Richard Smith2e312c82012-03-03 22:46:17 +00001494 void moveInto(APValue &V) const {
1495 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001496 }
Richard Smith2e312c82012-03-03 22:46:17 +00001497 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001498 assert(V.isMemberPointer());
1499 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1500 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1501 Path.clear();
1502 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1503 Path.insert(Path.end(), P.begin(), P.end());
1504 }
1505
1506 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1507 /// whether the member is a member of some class derived from the class type
1508 /// of the member pointer.
1509 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1510 /// Path - The path of base/derived classes from the member declaration's
1511 /// class (exclusive) to the class type of the member pointer (inclusive).
1512 SmallVector<const CXXRecordDecl*, 4> Path;
1513
1514 /// Perform a cast towards the class of the Decl (either up or down the
1515 /// hierarchy).
1516 bool castBack(const CXXRecordDecl *Class) {
1517 assert(!Path.empty());
1518 const CXXRecordDecl *Expected;
1519 if (Path.size() >= 2)
1520 Expected = Path[Path.size() - 2];
1521 else
1522 Expected = getContainingRecord();
1523 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1524 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1525 // if B does not contain the original member and is not a base or
1526 // derived class of the class containing the original member, the result
1527 // of the cast is undefined.
1528 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1529 // (D::*). We consider that to be a language defect.
1530 return false;
1531 }
1532 Path.pop_back();
1533 return true;
1534 }
1535 /// Perform a base-to-derived member pointer cast.
1536 bool castToDerived(const CXXRecordDecl *Derived) {
1537 if (!getDecl())
1538 return true;
1539 if (!isDerivedMember()) {
1540 Path.push_back(Derived);
1541 return true;
1542 }
1543 if (!castBack(Derived))
1544 return false;
1545 if (Path.empty())
1546 DeclAndIsDerivedMember.setInt(false);
1547 return true;
1548 }
1549 /// Perform a derived-to-base member pointer cast.
1550 bool castToBase(const CXXRecordDecl *Base) {
1551 if (!getDecl())
1552 return true;
1553 if (Path.empty())
1554 DeclAndIsDerivedMember.setInt(true);
1555 if (isDerivedMember()) {
1556 Path.push_back(Base);
1557 return true;
1558 }
1559 return castBack(Base);
1560 }
1561 };
Richard Smith357362d2011-12-13 06:39:58 +00001562
Richard Smith7bb00672012-02-01 01:42:44 +00001563 /// Compare two member pointers, which are assumed to be of the same type.
1564 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1565 if (!LHS.getDecl() || !RHS.getDecl())
1566 return !LHS.getDecl() && !RHS.getDecl();
1567 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1568 return false;
1569 return LHS.Path == RHS.Path;
1570 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001571}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001572
Richard Smith2e312c82012-03-03 22:46:17 +00001573static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001574static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1575 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001576 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001577static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1578 bool InvalidBaseOK = false);
1579static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1580 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001581static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1582 EvalInfo &Info);
1583static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001584static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001585static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001586 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001587static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001588static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001589static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1590 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001591static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001592
1593//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001594// Misc utilities
1595//===----------------------------------------------------------------------===//
1596
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001597/// A helper function to create a temporary and set an LValue.
1598template <class KeyTy>
1599static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1600 LValue &LV, CallStackFrame &Frame) {
1601 LV.set({Key, Frame.Info.CurrentCall->Index,
1602 Frame.Info.CurrentCall->getTempVersion()});
1603 return Frame.createTemporary(Key, IsLifetimeExtended);
1604}
1605
Richard Smithd6cc1982017-01-31 02:23:02 +00001606/// Negate an APSInt in place, converting it to a signed form if necessary, and
1607/// preserving its value (by extending by up to one bit as needed).
1608static void negateAsSigned(APSInt &Int) {
1609 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1610 Int = Int.extend(Int.getBitWidth() + 1);
1611 Int.setIsSigned(true);
1612 }
1613 Int = -Int;
1614}
1615
Richard Smith84401042013-06-03 05:03:02 +00001616/// Produce a string describing the given constexpr call.
1617static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1618 unsigned ArgIndex = 0;
1619 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1620 !isa<CXXConstructorDecl>(Frame->Callee) &&
1621 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1622
1623 if (!IsMemberCall)
1624 Out << *Frame->Callee << '(';
1625
1626 if (Frame->This && IsMemberCall) {
1627 APValue Val;
1628 Frame->This->moveInto(Val);
1629 Val.printPretty(Out, Frame->Info.Ctx,
1630 Frame->This->Designator.MostDerivedType);
1631 // FIXME: Add parens around Val if needed.
1632 Out << "->" << *Frame->Callee << '(';
1633 IsMemberCall = false;
1634 }
1635
1636 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1637 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1638 if (ArgIndex > (unsigned)IsMemberCall)
1639 Out << ", ";
1640
1641 const ParmVarDecl *Param = *I;
1642 const APValue &Arg = Frame->Arguments[ArgIndex];
1643 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1644
1645 if (ArgIndex == 0 && IsMemberCall)
1646 Out << "->" << *Frame->Callee << '(';
1647 }
1648
1649 Out << ')';
1650}
1651
Richard Smithd9f663b2013-04-22 15:31:51 +00001652/// Evaluate an expression to see if it had side-effects, and discard its
1653/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001654/// \return \c true if the caller should keep evaluating.
1655static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001656 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001657 if (!Evaluate(Scratch, Info, E))
1658 // We don't need the value, but we might have skipped a side effect here.
1659 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001660 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001661}
1662
Richard Smithd62306a2011-11-10 06:34:14 +00001663/// Should this call expression be treated as a string literal?
1664static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001665 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001666 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1667 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1668}
1669
Richard Smithce40ad62011-11-12 22:28:03 +00001670static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001671 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1672 // constant expression of pointer type that evaluates to...
1673
1674 // ... a null pointer value, or a prvalue core constant expression of type
1675 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001676 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001677
Richard Smithce40ad62011-11-12 22:28:03 +00001678 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1679 // ... the address of an object with static storage duration,
1680 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1681 return VD->hasGlobalStorage();
1682 // ... the address of a function,
1683 return isa<FunctionDecl>(D);
1684 }
1685
1686 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001687 switch (E->getStmtClass()) {
1688 default:
1689 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001690 case Expr::CompoundLiteralExprClass: {
1691 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1692 return CLE->isFileScope() && CLE->isLValue();
1693 }
Richard Smithe6c01442013-06-05 00:46:14 +00001694 case Expr::MaterializeTemporaryExprClass:
1695 // A materialized temporary might have been lifetime-extended to static
1696 // storage duration.
1697 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001698 // A string literal has static storage duration.
1699 case Expr::StringLiteralClass:
1700 case Expr::PredefinedExprClass:
1701 case Expr::ObjCStringLiteralClass:
1702 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001703 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001704 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001705 return true;
1706 case Expr::CallExprClass:
1707 return IsStringLiteralCall(cast<CallExpr>(E));
1708 // For GCC compatibility, &&label has static storage duration.
1709 case Expr::AddrLabelExprClass:
1710 return true;
1711 // A Block literal expression may be used as the initialization value for
1712 // Block variables at global or local static scope.
1713 case Expr::BlockExprClass:
1714 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001715 case Expr::ImplicitValueInitExprClass:
1716 // FIXME:
1717 // We can never form an lvalue with an implicit value initialization as its
1718 // base through expression evaluation, so these only appear in one case: the
1719 // implicit variable declaration we invent when checking whether a constexpr
1720 // constructor can produce a constant expression. We must assume that such
1721 // an expression might be a global lvalue.
1722 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001723 }
John McCall95007602010-05-10 23:27:23 +00001724}
1725
Richard Smith06f71b52018-08-04 00:57:17 +00001726static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1727 return LVal.Base.dyn_cast<const ValueDecl*>();
1728}
1729
1730static bool IsLiteralLValue(const LValue &Value) {
1731 if (Value.getLValueCallIndex())
1732 return false;
1733 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1734 return E && !isa<MaterializeTemporaryExpr>(E);
1735}
1736
1737static bool IsWeakLValue(const LValue &Value) {
1738 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1739 return Decl && Decl->isWeak();
1740}
1741
1742static bool isZeroSized(const LValue &Value) {
1743 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1744 if (Decl && isa<VarDecl>(Decl)) {
1745 QualType Ty = Decl->getType();
1746 if (Ty->isArrayType())
1747 return Ty->isIncompleteType() ||
1748 Decl->getASTContext().getTypeSize(Ty) == 0;
1749 }
1750 return false;
1751}
1752
1753static bool HasSameBase(const LValue &A, const LValue &B) {
1754 if (!A.getLValueBase())
1755 return !B.getLValueBase();
1756 if (!B.getLValueBase())
1757 return false;
1758
1759 if (A.getLValueBase().getOpaqueValue() !=
1760 B.getLValueBase().getOpaqueValue()) {
1761 const Decl *ADecl = GetLValueBaseDecl(A);
1762 if (!ADecl)
1763 return false;
1764 const Decl *BDecl = GetLValueBaseDecl(B);
1765 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1766 return false;
1767 }
1768
1769 return IsGlobalLValue(A.getLValueBase()) ||
1770 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1771 A.getLValueVersion() == B.getLValueVersion());
1772}
1773
Richard Smithb228a862012-02-15 02:18:13 +00001774static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1775 assert(Base && "no location for a null lvalue");
1776 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1777 if (VD)
1778 Info.Note(VD->getLocation(), diag::note_declared_at);
1779 else
Ted Kremenek28831752012-08-23 20:46:57 +00001780 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001781 diag::note_constexpr_temporary_here);
1782}
1783
Richard Smith80815602011-11-07 05:07:52 +00001784/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001785/// value for an address or reference constant expression. Return true if we
1786/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001787static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001788 QualType Type, const LValue &LVal,
1789 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001790 bool IsReferenceType = Type->isReferenceType();
1791
Richard Smith357362d2011-12-13 06:39:58 +00001792 APValue::LValueBase Base = LVal.getLValueBase();
1793 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1794
Richard Smith0dea49e2012-02-18 04:58:18 +00001795 // Check that the object is a global. Note that the fake 'this' object we
1796 // manufacture when checking potential constant expressions is conservatively
1797 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001798 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001799 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001800 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001801 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001802 << IsReferenceType << !Designator.Entries.empty()
1803 << !!VD << VD;
1804 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001805 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001806 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001807 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001808 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001809 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001810 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001811 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001812 LVal.getLValueCallIndex() == 0) &&
1813 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001814
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001815 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1816 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001817 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001818 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001819 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001820
Hans Wennborg82dd8772014-06-25 22:19:48 +00001821 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001822 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001823 return false;
1824 }
1825 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1826 // __declspec(dllimport) must be handled very carefully:
1827 // We must never initialize an expression with the thunk in C++.
1828 // Doing otherwise would allow the same id-expression to yield
1829 // different addresses for the same function in different translation
1830 // units. However, this means that we must dynamically initialize the
1831 // expression with the contents of the import address table at runtime.
1832 //
1833 // The C language has no notion of ODR; furthermore, it has no notion of
1834 // dynamic initialization. This means that we are permitted to
1835 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001836 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1837 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001838 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001839 }
1840 }
1841
Richard Smitha8105bc2012-01-06 16:39:00 +00001842 // Allow address constant expressions to be past-the-end pointers. This is
1843 // an extension: the standard requires them to point to an object.
1844 if (!IsReferenceType)
1845 return true;
1846
1847 // A reference constant expression must refer to an object.
1848 if (!Base) {
1849 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001850 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001851 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001852 }
1853
Richard Smith357362d2011-12-13 06:39:58 +00001854 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001855 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001856 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001857 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001858 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001859 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001860 }
1861
Richard Smith80815602011-11-07 05:07:52 +00001862 return true;
1863}
1864
Reid Klecknercd016d82017-07-07 22:04:29 +00001865/// Member pointers are constant expressions unless they point to a
1866/// non-virtual dllimport member function.
1867static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1868 SourceLocation Loc,
1869 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001870 const APValue &Value,
1871 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001872 const ValueDecl *Member = Value.getMemberPointerDecl();
1873 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1874 if (!FD)
1875 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001876 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1877 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001878}
1879
Richard Smithfddd3842011-12-30 21:15:51 +00001880/// Check that this core constant expression is of literal type, and if not,
1881/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001882static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001883 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001884 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001885 return true;
1886
Richard Smith7525ff62013-05-09 07:14:00 +00001887 // C++1y: A constant initializer for an object o [...] may also invoke
1888 // constexpr constructors for o and its subobjects even if those objects
1889 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001890 //
1891 // C++11 missed this detail for aggregates, so classes like this:
1892 // struct foo_t { union { int i; volatile int j; } u; };
1893 // are not (obviously) initializable like so:
1894 // __attribute__((__require_constant_initialization__))
1895 // static const foo_t x = {{0}};
1896 // because "i" is a subobject with non-literal initialization (due to the
1897 // volatile member of the union). See:
1898 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1899 // Therefore, we use the C++1y behavior.
1900 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001901 return true;
1902
Richard Smithfddd3842011-12-30 21:15:51 +00001903 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001904 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001905 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001906 << E->getType();
1907 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001908 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001909 return false;
1910}
1911
Richard Smith0b0a0b62011-10-29 20:57:55 +00001912/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001913/// constant expression. If not, report an appropriate diagnostic. Does not
1914/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001915static bool
1916CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1917 const APValue &Value,
1918 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001919 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001920 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001921 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001922 return false;
1923 }
1924
Richard Smith77be48a2014-07-31 06:31:19 +00001925 // We allow _Atomic(T) to be initialized from anything that T can be
1926 // initialized from.
1927 if (const AtomicType *AT = Type->getAs<AtomicType>())
1928 Type = AT->getValueType();
1929
Richard Smithb228a862012-02-15 02:18:13 +00001930 // Core issue 1454: For a literal constant expression of array or class type,
1931 // each subobject of its value shall have been initialized by a constant
1932 // expression.
1933 if (Value.isArray()) {
1934 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1935 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1936 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001937 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001938 return false;
1939 }
1940 if (!Value.hasArrayFiller())
1941 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001942 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1943 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001944 }
Richard Smithb228a862012-02-15 02:18:13 +00001945 if (Value.isUnion() && Value.getUnionField()) {
1946 return CheckConstantExpression(Info, DiagLoc,
1947 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001948 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001949 }
1950 if (Value.isStruct()) {
1951 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1952 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1953 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001954 for (const CXXBaseSpecifier &BS : CD->bases()) {
1955 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1956 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001957 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001958 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001959 }
1960 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001961 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001962 if (I->isUnnamedBitfield())
1963 continue;
1964
David Blaikie2d7c57e2012-04-30 02:36:29 +00001965 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001966 Value.getStructField(I->getFieldIndex()),
1967 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001968 return false;
1969 }
1970 }
1971
1972 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001973 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001974 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001975 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001976 }
1977
Reid Klecknercd016d82017-07-07 22:04:29 +00001978 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00001979 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001980
Richard Smithb228a862012-02-15 02:18:13 +00001981 // Everything else is fine.
1982 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001983}
1984
Richard Smith2e312c82012-03-03 22:46:17 +00001985static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001986 // A null base expression indicates a null pointer. These are always
1987 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001988 if (!Value.getLValueBase()) {
1989 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001990 return true;
1991 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001992
Richard Smith027bf112011-11-17 22:56:20 +00001993 // We have a non-null base. These are generally known to be true, but if it's
1994 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001995 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001996 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001997 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001998}
1999
Richard Smith2e312c82012-03-03 22:46:17 +00002000static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002001 switch (Val.getKind()) {
2002 case APValue::Uninitialized:
2003 return false;
2004 case APValue::Int:
2005 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002006 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002007 case APValue::Float:
2008 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002009 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002010 case APValue::ComplexInt:
2011 Result = Val.getComplexIntReal().getBoolValue() ||
2012 Val.getComplexIntImag().getBoolValue();
2013 return true;
2014 case APValue::ComplexFloat:
2015 Result = !Val.getComplexFloatReal().isZero() ||
2016 !Val.getComplexFloatImag().isZero();
2017 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002018 case APValue::LValue:
2019 return EvalPointerValueAsBool(Val, Result);
2020 case APValue::MemberPointer:
2021 Result = Val.getMemberPointerDecl();
2022 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002023 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002024 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002025 case APValue::Struct:
2026 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002027 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002028 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002029 }
2030
Richard Smith11562c52011-10-28 17:51:58 +00002031 llvm_unreachable("unknown APValue kind");
2032}
2033
2034static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2035 EvalInfo &Info) {
2036 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002037 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002038 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002039 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002040 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002041}
2042
Richard Smith357362d2011-12-13 06:39:58 +00002043template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002044static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002045 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002046 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002047 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002048 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002049}
2050
2051static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2052 QualType SrcType, const APFloat &Value,
2053 QualType DestType, APSInt &Result) {
2054 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002055 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002056 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002057
Richard Smith357362d2011-12-13 06:39:58 +00002058 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002059 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002060 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2061 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002062 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002063 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002064}
2065
Richard Smith357362d2011-12-13 06:39:58 +00002066static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2067 QualType SrcType, QualType DestType,
2068 APFloat &Result) {
2069 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002070 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002071 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2072 APFloat::rmNearestTiesToEven, &ignored)
2073 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002074 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002075 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002076}
2077
Richard Smith911e1422012-01-30 22:27:01 +00002078static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2079 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002080 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002081 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002082 // Figure out if this is a truncate, extend or noop cast.
2083 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002084 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002085 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002086 if (DestType->isBooleanType())
2087 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002088 return Result;
2089}
2090
Richard Smith357362d2011-12-13 06:39:58 +00002091static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2092 QualType SrcType, const APSInt &Value,
2093 QualType DestType, APFloat &Result) {
2094 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2095 if (Result.convertFromAPInt(Value, Value.isSigned(),
2096 APFloat::rmNearestTiesToEven)
2097 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002098 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002099 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002100}
2101
Richard Smith49ca8aa2013-08-06 07:09:20 +00002102static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2103 APValue &Value, const FieldDecl *FD) {
2104 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2105
2106 if (!Value.isInt()) {
2107 // Trying to store a pointer-cast-to-integer into a bitfield.
2108 // FIXME: In this case, we should provide the diagnostic for casting
2109 // a pointer to an integer.
2110 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002111 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002112 return false;
2113 }
2114
2115 APSInt &Int = Value.getInt();
2116 unsigned OldBitWidth = Int.getBitWidth();
2117 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2118 if (NewBitWidth < OldBitWidth)
2119 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2120 return true;
2121}
2122
Eli Friedman803acb32011-12-22 03:51:45 +00002123static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2124 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002125 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002126 if (!Evaluate(SVal, Info, E))
2127 return false;
2128 if (SVal.isInt()) {
2129 Res = SVal.getInt();
2130 return true;
2131 }
2132 if (SVal.isFloat()) {
2133 Res = SVal.getFloat().bitcastToAPInt();
2134 return true;
2135 }
2136 if (SVal.isVector()) {
2137 QualType VecTy = E->getType();
2138 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2139 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2140 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2141 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2142 Res = llvm::APInt::getNullValue(VecSize);
2143 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2144 APValue &Elt = SVal.getVectorElt(i);
2145 llvm::APInt EltAsInt;
2146 if (Elt.isInt()) {
2147 EltAsInt = Elt.getInt();
2148 } else if (Elt.isFloat()) {
2149 EltAsInt = Elt.getFloat().bitcastToAPInt();
2150 } else {
2151 // Don't try to handle vectors of anything other than int or float
2152 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002154 return false;
2155 }
2156 unsigned BaseEltSize = EltAsInt.getBitWidth();
2157 if (BigEndian)
2158 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2159 else
2160 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2161 }
2162 return true;
2163 }
2164 // Give up if the input isn't an int, float, or vector. For example, we
2165 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002166 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002167 return false;
2168}
2169
Richard Smith43e77732013-05-07 04:50:00 +00002170/// Perform the given integer operation, which is known to need at most BitWidth
2171/// bits, and check for overflow in the original type (if that type was not an
2172/// unsigned type).
2173template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002174static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2175 const APSInt &LHS, const APSInt &RHS,
2176 unsigned BitWidth, Operation Op,
2177 APSInt &Result) {
2178 if (LHS.isUnsigned()) {
2179 Result = Op(LHS, RHS);
2180 return true;
2181 }
Richard Smith43e77732013-05-07 04:50:00 +00002182
2183 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002184 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002185 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002186 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002187 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002188 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002189 << Result.toString(10) << E->getType();
2190 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002191 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002192 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002193 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002194}
2195
2196/// Perform the given binary integer operation.
2197static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2198 BinaryOperatorKind Opcode, APSInt RHS,
2199 APSInt &Result) {
2200 switch (Opcode) {
2201 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002202 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002203 return false;
2204 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002205 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2206 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002207 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002208 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2209 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002210 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002211 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2212 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002213 case BO_And: Result = LHS & RHS; return true;
2214 case BO_Xor: Result = LHS ^ RHS; return true;
2215 case BO_Or: Result = LHS | RHS; return true;
2216 case BO_Div:
2217 case BO_Rem:
2218 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002219 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002220 return false;
2221 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002222 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2223 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2224 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002225 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2226 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002227 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2228 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002229 return true;
2230 case BO_Shl: {
2231 if (Info.getLangOpts().OpenCL)
2232 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2233 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2234 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2235 RHS.isUnsigned());
2236 else if (RHS.isSigned() && RHS.isNegative()) {
2237 // During constant-folding, a negative shift is an opposite shift. Such
2238 // a shift is not a constant expression.
2239 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2240 RHS = -RHS;
2241 goto shift_right;
2242 }
2243 shift_left:
2244 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2245 // the shifted type.
2246 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2247 if (SA != RHS) {
2248 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2249 << RHS << E->getType() << LHS.getBitWidth();
2250 } else if (LHS.isSigned()) {
2251 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2252 // operand, and must not overflow the corresponding unsigned type.
2253 if (LHS.isNegative())
2254 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2255 else if (LHS.countLeadingZeros() < SA)
2256 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2257 }
2258 Result = LHS << SA;
2259 return true;
2260 }
2261 case BO_Shr: {
2262 if (Info.getLangOpts().OpenCL)
2263 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2264 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2265 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2266 RHS.isUnsigned());
2267 else if (RHS.isSigned() && RHS.isNegative()) {
2268 // During constant-folding, a negative shift is an opposite shift. Such a
2269 // shift is not a constant expression.
2270 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2271 RHS = -RHS;
2272 goto shift_left;
2273 }
2274 shift_right:
2275 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2276 // shifted type.
2277 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2278 if (SA != RHS)
2279 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2280 << RHS << E->getType() << LHS.getBitWidth();
2281 Result = LHS >> SA;
2282 return true;
2283 }
2284
2285 case BO_LT: Result = LHS < RHS; return true;
2286 case BO_GT: Result = LHS > RHS; return true;
2287 case BO_LE: Result = LHS <= RHS; return true;
2288 case BO_GE: Result = LHS >= RHS; return true;
2289 case BO_EQ: Result = LHS == RHS; return true;
2290 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002291 case BO_Cmp:
2292 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002293 }
2294}
2295
Richard Smith861b5b52013-05-07 23:34:45 +00002296/// Perform the given binary floating-point operation, in-place, on LHS.
2297static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2298 APFloat &LHS, BinaryOperatorKind Opcode,
2299 const APFloat &RHS) {
2300 switch (Opcode) {
2301 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002302 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002303 return false;
2304 case BO_Mul:
2305 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2306 break;
2307 case BO_Add:
2308 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2309 break;
2310 case BO_Sub:
2311 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2312 break;
2313 case BO_Div:
2314 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2315 break;
2316 }
2317
Richard Smith0c6124b2015-12-03 01:36:22 +00002318 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002319 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002320 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002321 }
Richard Smith861b5b52013-05-07 23:34:45 +00002322 return true;
2323}
2324
Richard Smitha8105bc2012-01-06 16:39:00 +00002325/// Cast an lvalue referring to a base subobject to a derived class, by
2326/// truncating the lvalue's path to the given length.
2327static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2328 const RecordDecl *TruncatedType,
2329 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002330 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002331
2332 // Check we actually point to a derived class object.
2333 if (TruncatedElements == D.Entries.size())
2334 return true;
2335 assert(TruncatedElements >= D.MostDerivedPathLength &&
2336 "not casting to a derived class");
2337 if (!Result.checkSubobject(Info, E, CSK_Derived))
2338 return false;
2339
2340 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002341 const RecordDecl *RD = TruncatedType;
2342 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002343 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002344 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2345 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002346 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002347 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002348 else
Richard Smithd62306a2011-11-10 06:34:14 +00002349 Result.Offset -= Layout.getBaseClassOffset(Base);
2350 RD = Base;
2351 }
Richard Smith027bf112011-11-17 22:56:20 +00002352 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002353 return true;
2354}
2355
John McCalld7bca762012-05-01 00:38:49 +00002356static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002357 const CXXRecordDecl *Derived,
2358 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002359 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002360 if (!RL) {
2361 if (Derived->isInvalidDecl()) return false;
2362 RL = &Info.Ctx.getASTRecordLayout(Derived);
2363 }
2364
Richard Smithd62306a2011-11-10 06:34:14 +00002365 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002366 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002367 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002368}
2369
Richard Smitha8105bc2012-01-06 16:39:00 +00002370static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002371 const CXXRecordDecl *DerivedDecl,
2372 const CXXBaseSpecifier *Base) {
2373 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2374
John McCalld7bca762012-05-01 00:38:49 +00002375 if (!Base->isVirtual())
2376 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002377
Richard Smitha8105bc2012-01-06 16:39:00 +00002378 SubobjectDesignator &D = Obj.Designator;
2379 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002380 return false;
2381
Richard Smitha8105bc2012-01-06 16:39:00 +00002382 // Extract most-derived object and corresponding type.
2383 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2384 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2385 return false;
2386
2387 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002388 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002389 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2390 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002391 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002392 return true;
2393}
2394
Richard Smith84401042013-06-03 05:03:02 +00002395static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2396 QualType Type, LValue &Result) {
2397 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2398 PathE = E->path_end();
2399 PathI != PathE; ++PathI) {
2400 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2401 *PathI))
2402 return false;
2403 Type = (*PathI)->getType();
2404 }
2405 return true;
2406}
2407
Richard Smithd62306a2011-11-10 06:34:14 +00002408/// Update LVal to refer to the given field, which must be a member of the type
2409/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002410static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002411 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002412 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002413 if (!RL) {
2414 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002415 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002416 }
Richard Smithd62306a2011-11-10 06:34:14 +00002417
2418 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002419 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002420 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002421 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002422}
2423
Richard Smith1b78b3d2012-01-25 22:15:11 +00002424/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002425static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002426 LValue &LVal,
2427 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002428 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002429 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002430 return false;
2431 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002432}
2433
Richard Smithd62306a2011-11-10 06:34:14 +00002434/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002435static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2436 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002437 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2438 // extension.
2439 if (Type->isVoidType() || Type->isFunctionType()) {
2440 Size = CharUnits::One();
2441 return true;
2442 }
2443
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002444 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002445 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002446 return false;
2447 }
2448
Richard Smithd62306a2011-11-10 06:34:14 +00002449 if (!Type->isConstantSizeType()) {
2450 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002451 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002452 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002453 return false;
2454 }
2455
2456 Size = Info.Ctx.getTypeSizeInChars(Type);
2457 return true;
2458}
2459
2460/// Update a pointer value to model pointer arithmetic.
2461/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002462/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002463/// \param LVal - The pointer value to be updated.
2464/// \param EltTy - The pointee type represented by LVal.
2465/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002466static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2467 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002468 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002469 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002470 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002471 return false;
2472
Yaxun Liu402804b2016-12-15 08:09:08 +00002473 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002474 return true;
2475}
2476
Richard Smithd6cc1982017-01-31 02:23:02 +00002477static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2478 LValue &LVal, QualType EltTy,
2479 int64_t Adjustment) {
2480 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2481 APSInt::get(Adjustment));
2482}
2483
Richard Smith66c96992012-02-18 22:04:06 +00002484/// Update an lvalue to refer to a component of a complex number.
2485/// \param Info - Information about the ongoing evaluation.
2486/// \param LVal - The lvalue to be updated.
2487/// \param EltTy - The complex number's component type.
2488/// \param Imag - False for the real component, true for the imaginary.
2489static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2490 LValue &LVal, QualType EltTy,
2491 bool Imag) {
2492 if (Imag) {
2493 CharUnits SizeOfComponent;
2494 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2495 return false;
2496 LVal.Offset += SizeOfComponent;
2497 }
2498 LVal.addComplex(Info, E, EltTy, Imag);
2499 return true;
2500}
2501
Faisal Vali051e3a22017-02-16 04:12:21 +00002502static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2503 QualType Type, const LValue &LVal,
2504 APValue &RVal);
2505
Richard Smith27908702011-10-24 17:54:18 +00002506/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002507///
2508/// \param Info Information about the ongoing evaluation.
2509/// \param E An expression to be used when printing diagnostics.
2510/// \param VD The variable whose initializer should be obtained.
2511/// \param Frame The frame in which the variable was created. Must be null
2512/// if this variable is not local to the evaluation.
2513/// \param Result Filled in with a pointer to the value of the variable.
2514static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2515 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002516 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002517
Richard Smith254a73d2011-10-28 22:34:42 +00002518 // If this is a parameter to an active constexpr function call, perform
2519 // argument substitution.
2520 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002521 // Assume arguments of a potential constant expression are unknown
2522 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002523 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002524 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002525 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002526 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002527 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002528 }
Richard Smith3229b742013-05-05 21:17:10 +00002529 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002530 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002531 }
Richard Smith27908702011-10-24 17:54:18 +00002532
Richard Smithd9f663b2013-04-22 15:31:51 +00002533 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002534 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002535 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2536 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002537 if (!Result) {
2538 // Assume variables referenced within a lambda's call operator that were
2539 // not declared within the call operator are captures and during checking
2540 // of a potential constant expression, assume they are unknown constant
2541 // expressions.
2542 assert(isLambdaCallOperator(Frame->Callee) &&
2543 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2544 "missing value for local variable");
2545 if (Info.checkingPotentialConstantExpression())
2546 return false;
2547 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002548 Info.FFDiag(E->getBeginLoc(),
2549 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002550 << "captures not currently allowed";
2551 return false;
2552 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002553 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002554 }
2555
Richard Smithd0b4dd62011-12-19 06:19:21 +00002556 // Dig out the initializer, and use the declaration which it's attached to.
2557 const Expr *Init = VD->getAnyInitializer(VD);
2558 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002559 // If we're checking a potential constant expression, the variable could be
2560 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002561 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002562 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002563 return false;
2564 }
2565
Richard Smithd62306a2011-11-10 06:34:14 +00002566 // If we're currently evaluating the initializer of this declaration, use that
2567 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002568 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002569 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002570 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002571 }
2572
Richard Smithcecf1842011-11-01 21:06:14 +00002573 // Never evaluate the initializer of a weak variable. We can't be sure that
2574 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002575 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002576 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002577 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002578 }
Richard Smithcecf1842011-11-01 21:06:14 +00002579
Richard Smithd0b4dd62011-12-19 06:19:21 +00002580 // Check that we can fold the initializer. In C++, we will have already done
2581 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002582 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002583 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002584 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002585 Notes.size() + 1) << VD;
2586 Info.Note(VD->getLocation(), diag::note_declared_at);
2587 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002588 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002589 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002590 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002591 Notes.size() + 1) << VD;
2592 Info.Note(VD->getLocation(), diag::note_declared_at);
2593 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002594 }
Richard Smith27908702011-10-24 17:54:18 +00002595
Richard Smith3229b742013-05-05 21:17:10 +00002596 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002597 return true;
Richard Smith27908702011-10-24 17:54:18 +00002598}
2599
Richard Smith11562c52011-10-28 17:51:58 +00002600static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002601 Qualifiers Quals = T.getQualifiers();
2602 return Quals.hasConst() && !Quals.hasVolatile();
2603}
2604
Richard Smithe97cbd72011-11-11 04:05:33 +00002605/// Get the base index of the given base class within an APValue representing
2606/// the given derived class.
2607static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2608 const CXXRecordDecl *Base) {
2609 Base = Base->getCanonicalDecl();
2610 unsigned Index = 0;
2611 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2612 E = Derived->bases_end(); I != E; ++I, ++Index) {
2613 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2614 return Index;
2615 }
2616
2617 llvm_unreachable("base class missing from derived class's bases list");
2618}
2619
Richard Smith3da88fa2013-04-26 14:36:30 +00002620/// Extract the value of a character from a string literal.
2621static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2622 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002623 // FIXME: Support MakeStringConstant
2624 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2625 std::string Str;
2626 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2627 assert(Index <= Str.size() && "Index too large");
2628 return APSInt::getUnsigned(Str.c_str()[Index]);
2629 }
2630
Alexey Bataevec474782014-10-09 08:45:04 +00002631 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2632 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002633 const StringLiteral *S = cast<StringLiteral>(Lit);
2634 const ConstantArrayType *CAT =
2635 Info.Ctx.getAsConstantArrayType(S->getType());
2636 assert(CAT && "string literal isn't an array");
2637 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002638 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002639
2640 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002641 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002642 if (Index < S->getLength())
2643 Value = S->getCodeUnit(Index);
2644 return Value;
2645}
2646
Richard Smith3da88fa2013-04-26 14:36:30 +00002647// Expand a string literal into an array of characters.
2648static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2649 APValue &Result) {
2650 const StringLiteral *S = cast<StringLiteral>(Lit);
2651 const ConstantArrayType *CAT =
2652 Info.Ctx.getAsConstantArrayType(S->getType());
2653 assert(CAT && "string literal isn't an array");
2654 QualType CharType = CAT->getElementType();
2655 assert(CharType->isIntegerType() && "unexpected character type");
2656
2657 unsigned Elts = CAT->getSize().getZExtValue();
2658 Result = APValue(APValue::UninitArray(),
2659 std::min(S->getLength(), Elts), Elts);
2660 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2661 CharType->isUnsignedIntegerType());
2662 if (Result.hasArrayFiller())
2663 Result.getArrayFiller() = APValue(Value);
2664 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2665 Value = S->getCodeUnit(I);
2666 Result.getArrayInitializedElt(I) = APValue(Value);
2667 }
2668}
2669
2670// Expand an array so that it has more than Index filled elements.
2671static void expandArray(APValue &Array, unsigned Index) {
2672 unsigned Size = Array.getArraySize();
2673 assert(Index < Size);
2674
2675 // Always at least double the number of elements for which we store a value.
2676 unsigned OldElts = Array.getArrayInitializedElts();
2677 unsigned NewElts = std::max(Index+1, OldElts * 2);
2678 NewElts = std::min(Size, std::max(NewElts, 8u));
2679
2680 // Copy the data across.
2681 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2682 for (unsigned I = 0; I != OldElts; ++I)
2683 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2684 for (unsigned I = OldElts; I != NewElts; ++I)
2685 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2686 if (NewValue.hasArrayFiller())
2687 NewValue.getArrayFiller() = Array.getArrayFiller();
2688 Array.swap(NewValue);
2689}
2690
Richard Smithb01fe402014-09-16 01:24:02 +00002691/// Determine whether a type would actually be read by an lvalue-to-rvalue
2692/// conversion. If it's of class type, we may assume that the copy operation
2693/// is trivial. Note that this is never true for a union type with fields
2694/// (because the copy always "reads" the active member) and always true for
2695/// a non-class type.
2696static bool isReadByLvalueToRvalueConversion(QualType T) {
2697 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2698 if (!RD || (RD->isUnion() && !RD->field_empty()))
2699 return true;
2700 if (RD->isEmpty())
2701 return false;
2702
2703 for (auto *Field : RD->fields())
2704 if (isReadByLvalueToRvalueConversion(Field->getType()))
2705 return true;
2706
2707 for (auto &BaseSpec : RD->bases())
2708 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2709 return true;
2710
2711 return false;
2712}
2713
2714/// Diagnose an attempt to read from any unreadable field within the specified
2715/// type, which might be a class type.
2716static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2717 QualType T) {
2718 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2719 if (!RD)
2720 return false;
2721
2722 if (!RD->hasMutableFields())
2723 return false;
2724
2725 for (auto *Field : RD->fields()) {
2726 // If we're actually going to read this field in some way, then it can't
2727 // be mutable. If we're in a union, then assigning to a mutable field
2728 // (even an empty one) can change the active member, so that's not OK.
2729 // FIXME: Add core issue number for the union case.
2730 if (Field->isMutable() &&
2731 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002732 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002733 Info.Note(Field->getLocation(), diag::note_declared_at);
2734 return true;
2735 }
2736
2737 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2738 return true;
2739 }
2740
2741 for (auto &BaseSpec : RD->bases())
2742 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2743 return true;
2744
2745 // All mutable fields were empty, and thus not actually read.
2746 return false;
2747}
2748
Richard Smith861b5b52013-05-07 23:34:45 +00002749/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002750enum AccessKinds {
2751 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002752 AK_Assign,
2753 AK_Increment,
2754 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002755};
2756
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002757namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002758/// A handle to a complete object (an object that is not a subobject of
2759/// another object).
2760struct CompleteObject {
2761 /// The value of the complete object.
2762 APValue *Value;
2763 /// The type of the complete object.
2764 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002765 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002766
Craig Topper36250ad2014-05-12 05:36:57 +00002767 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002768 CompleteObject(APValue *Value, QualType Type,
2769 bool LifetimeStartedInEvaluation)
2770 : Value(Value), Type(Type),
2771 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002772 assert(Value && "missing value for complete object");
2773 }
2774
Aaron Ballman67347662015-02-15 22:00:28 +00002775 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002776};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002777} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002778
Richard Smith3da88fa2013-04-26 14:36:30 +00002779/// Find the designated sub-object of an rvalue.
2780template<typename SubobjectHandler>
2781typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002782findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002783 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002784 if (Sub.Invalid)
2785 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002786 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002787 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002788 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002789 Info.FFDiag(E, Sub.isOnePastTheEnd()
2790 ? diag::note_constexpr_access_past_end
2791 : diag::note_constexpr_access_unsized_array)
2792 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002793 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002794 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002795 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002796 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002797
Richard Smith3229b742013-05-05 21:17:10 +00002798 APValue *O = Obj.Value;
2799 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002800 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002801 const bool MayReadMutableMembers =
2802 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002803
Richard Smithd62306a2011-11-10 06:34:14 +00002804 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002805 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2806 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002807 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002808 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002809 return handler.failed();
2810 }
2811
Richard Smith49ca8aa2013-08-06 07:09:20 +00002812 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002813 // If we are reading an object of class type, there may still be more
2814 // things we need to check: if there are any mutable subobjects, we
2815 // cannot perform this read. (This only happens when performing a trivial
2816 // copy or assignment.)
2817 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002818 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002819 return handler.failed();
2820
Richard Smith49ca8aa2013-08-06 07:09:20 +00002821 if (!handler.found(*O, ObjType))
2822 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002823
Richard Smith49ca8aa2013-08-06 07:09:20 +00002824 // If we modified a bit-field, truncate it to the right width.
2825 if (handler.AccessKind != AK_Read &&
2826 LastField && LastField->isBitField() &&
2827 !truncateBitfieldValue(Info, E, *O, LastField))
2828 return false;
2829
2830 return true;
2831 }
2832
Craig Topper36250ad2014-05-12 05:36:57 +00002833 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002834 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002835 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002836 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002837 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002838 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002839 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002840 // Note, it should not be possible to form a pointer with a valid
2841 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002842 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002843 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002844 << handler.AccessKind;
2845 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002846 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002847 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002848 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002849
2850 ObjType = CAT->getElementType();
2851
Richard Smith14a94132012-02-17 03:35:37 +00002852 // An array object is represented as either an Array APValue or as an
2853 // LValue which refers to a string literal.
2854 if (O->isLValue()) {
2855 assert(I == N - 1 && "extracting subobject of character?");
2856 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002857 if (handler.AccessKind != AK_Read)
2858 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2859 *O);
2860 else
2861 return handler.foundString(*O, ObjType, Index);
2862 }
2863
2864 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002865 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 else if (handler.AccessKind != AK_Read) {
2867 expandArray(*O, Index);
2868 O = &O->getArrayInitializedElt(Index);
2869 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002870 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002871 } else if (ObjType->isAnyComplexType()) {
2872 // Next subobject is a complex number.
2873 uint64_t Index = Sub.Entries[I].ArrayIndex;
2874 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002875 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002876 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002877 << handler.AccessKind;
2878 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002879 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002880 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002881 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002882
2883 bool WasConstQualified = ObjType.isConstQualified();
2884 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2885 if (WasConstQualified)
2886 ObjType.addConst();
2887
Richard Smith66c96992012-02-18 22:04:06 +00002888 assert(I == N - 1 && "extracting subobject of scalar?");
2889 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002890 return handler.found(Index ? O->getComplexIntImag()
2891 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002892 } else {
2893 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002894 return handler.found(Index ? O->getComplexFloatImag()
2895 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002896 }
Richard Smithd62306a2011-11-10 06:34:14 +00002897 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002898 // In C++14 onwards, it is permitted to read a mutable member whose
2899 // lifetime began within the evaluation.
2900 // FIXME: Should we also allow this in C++11?
2901 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2902 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002903 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002904 << Field;
2905 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002906 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002907 }
2908
Richard Smithd62306a2011-11-10 06:34:14 +00002909 // Next subobject is a class, struct or union field.
2910 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2911 if (RD->isUnion()) {
2912 const FieldDecl *UnionField = O->getUnionField();
2913 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002914 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002915 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002916 << handler.AccessKind << Field << !UnionField << UnionField;
2917 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002918 }
Richard Smithd62306a2011-11-10 06:34:14 +00002919 O = &O->getUnionValue();
2920 } else
2921 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002922
2923 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002924 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002925 if (WasConstQualified && !Field->isMutable())
2926 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002927
2928 if (ObjType.isVolatileQualified()) {
2929 if (Info.getLangOpts().CPlusPlus) {
2930 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002931 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002932 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002933 Info.Note(Field->getLocation(), diag::note_declared_at);
2934 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002936 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002938 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002939
2940 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002941 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002942 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002943 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2944 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2945 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002946
2947 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002948 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002949 if (WasConstQualified)
2950 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002951 }
2952 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002953}
2954
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002955namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002956struct ExtractSubobjectHandler {
2957 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002958 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002959
2960 static const AccessKinds AccessKind = AK_Read;
2961
2962 typedef bool result_type;
2963 bool failed() { return false; }
2964 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002965 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002966 return true;
2967 }
2968 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002969 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002970 return true;
2971 }
2972 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002973 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002974 return true;
2975 }
2976 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002977 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002978 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2979 return true;
2980 }
2981};
Richard Smith3229b742013-05-05 21:17:10 +00002982} // end anonymous namespace
2983
Richard Smith3da88fa2013-04-26 14:36:30 +00002984const AccessKinds ExtractSubobjectHandler::AccessKind;
2985
2986/// Extract the designated sub-object of an rvalue.
2987static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002988 const CompleteObject &Obj,
2989 const SubobjectDesignator &Sub,
2990 APValue &Result) {
2991 ExtractSubobjectHandler Handler = { Info, Result };
2992 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002993}
2994
Richard Smith3229b742013-05-05 21:17:10 +00002995namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002996struct ModifySubobjectHandler {
2997 EvalInfo &Info;
2998 APValue &NewVal;
2999 const Expr *E;
3000
3001 typedef bool result_type;
3002 static const AccessKinds AccessKind = AK_Assign;
3003
3004 bool checkConst(QualType QT) {
3005 // Assigning to a const object has undefined behavior.
3006 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003007 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003008 return false;
3009 }
3010 return true;
3011 }
3012
3013 bool failed() { return false; }
3014 bool found(APValue &Subobj, QualType SubobjType) {
3015 if (!checkConst(SubobjType))
3016 return false;
3017 // We've been given ownership of NewVal, so just swap it in.
3018 Subobj.swap(NewVal);
3019 return true;
3020 }
3021 bool found(APSInt &Value, QualType SubobjType) {
3022 if (!checkConst(SubobjType))
3023 return false;
3024 if (!NewVal.isInt()) {
3025 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003026 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003027 return false;
3028 }
3029 Value = NewVal.getInt();
3030 return true;
3031 }
3032 bool found(APFloat &Value, QualType SubobjType) {
3033 if (!checkConst(SubobjType))
3034 return false;
3035 Value = NewVal.getFloat();
3036 return true;
3037 }
3038 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3039 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3040 }
3041};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003042} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003043
Richard Smith3229b742013-05-05 21:17:10 +00003044const AccessKinds ModifySubobjectHandler::AccessKind;
3045
Richard Smith3da88fa2013-04-26 14:36:30 +00003046/// Update the designated sub-object of an rvalue to the given value.
3047static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003048 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003049 const SubobjectDesignator &Sub,
3050 APValue &NewVal) {
3051 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003052 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003053}
3054
Richard Smith84f6dcf2012-02-02 01:16:57 +00003055/// Find the position where two subobject designators diverge, or equivalently
3056/// the length of the common initial subsequence.
3057static unsigned FindDesignatorMismatch(QualType ObjType,
3058 const SubobjectDesignator &A,
3059 const SubobjectDesignator &B,
3060 bool &WasArrayIndex) {
3061 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3062 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003063 if (!ObjType.isNull() &&
3064 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003065 // Next subobject is an array element.
3066 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3067 WasArrayIndex = true;
3068 return I;
3069 }
Richard Smith66c96992012-02-18 22:04:06 +00003070 if (ObjType->isAnyComplexType())
3071 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3072 else
3073 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003074 } else {
3075 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3076 WasArrayIndex = false;
3077 return I;
3078 }
3079 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3080 // Next subobject is a field.
3081 ObjType = FD->getType();
3082 else
3083 // Next subobject is a base class.
3084 ObjType = QualType();
3085 }
3086 }
3087 WasArrayIndex = false;
3088 return I;
3089}
3090
3091/// Determine whether the given subobject designators refer to elements of the
3092/// same array object.
3093static bool AreElementsOfSameArray(QualType ObjType,
3094 const SubobjectDesignator &A,
3095 const SubobjectDesignator &B) {
3096 if (A.Entries.size() != B.Entries.size())
3097 return false;
3098
George Burgess IVa51c4072015-10-16 01:49:01 +00003099 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003100 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3101 // A is a subobject of the array element.
3102 return false;
3103
3104 // If A (and B) designates an array element, the last entry will be the array
3105 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3106 // of length 1' case, and the entire path must match.
3107 bool WasArrayIndex;
3108 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3109 return CommonLength >= A.Entries.size() - IsArray;
3110}
3111
Richard Smith3229b742013-05-05 21:17:10 +00003112/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003113static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3114 AccessKinds AK, const LValue &LVal,
3115 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003116 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003117 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003118 return CompleteObject();
3119 }
3120
Craig Topper36250ad2014-05-12 05:36:57 +00003121 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003122 if (LVal.getLValueCallIndex()) {
3123 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003124 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003125 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003126 << AK << LVal.Base.is<const ValueDecl*>();
3127 NoteLValueLocation(Info, LVal.Base);
3128 return CompleteObject();
3129 }
Richard Smith3229b742013-05-05 21:17:10 +00003130 }
3131
3132 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3133 // is not a constant expression (even if the object is non-volatile). We also
3134 // apply this rule to C++98, in order to conform to the expected 'volatile'
3135 // semantics.
3136 if (LValType.isVolatileQualified()) {
3137 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003138 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003139 << AK << LValType;
3140 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003141 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003142 return CompleteObject();
3143 }
3144
3145 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003146 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003147 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003148 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003149
3150 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3151 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3152 // In C++11, constexpr, non-volatile variables initialized with constant
3153 // expressions are constant expressions too. Inside constexpr functions,
3154 // parameters are constant expressions even if they're non-const.
3155 // In C++1y, objects local to a constant expression (those with a Frame) are
3156 // both readable and writable inside constant expressions.
3157 // In C, such things can also be folded, although they are not ICEs.
3158 const VarDecl *VD = dyn_cast<VarDecl>(D);
3159 if (VD) {
3160 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3161 VD = VDef;
3162 }
3163 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003164 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003165 return CompleteObject();
3166 }
3167
3168 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003169 if (BaseType.isVolatileQualified()) {
3170 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003171 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003172 << AK << 1 << VD;
3173 Info.Note(VD->getLocation(), diag::note_declared_at);
3174 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003175 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003176 }
3177 return CompleteObject();
3178 }
3179
3180 // Unless we're looking at a local variable or argument in a constexpr call,
3181 // the variable we're reading must be const.
3182 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003183 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003184 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3185 // OK, we can read and modify an object if we're in the process of
3186 // evaluating its initializer, because its lifetime began in this
3187 // evaluation.
3188 } else if (AK != AK_Read) {
3189 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003190 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003191 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003192 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003193 // OK, we can read this variable.
3194 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003195 // In OpenCL if a variable is in constant address space it is a const value.
3196 if (!(BaseType.isConstQualified() ||
3197 (Info.getLangOpts().OpenCL &&
3198 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003199 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003200 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003201 Info.Note(VD->getLocation(), diag::note_declared_at);
3202 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003203 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003204 }
3205 return CompleteObject();
3206 }
3207 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3208 // We support folding of const floating-point types, in order to make
3209 // static const data members of such types (supported as an extension)
3210 // more useful.
3211 if (Info.getLangOpts().CPlusPlus11) {
3212 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3213 Info.Note(VD->getLocation(), diag::note_declared_at);
3214 } else {
3215 Info.CCEDiag(E);
3216 }
George Burgess IVb5316982016-12-27 05:33:20 +00003217 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3218 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3219 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003220 } else {
3221 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003222 if (Info.checkingPotentialConstantExpression() &&
3223 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3224 // The definition of this variable could be constexpr. We can't
3225 // access it right now, but may be able to in future.
3226 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003228 Info.Note(VD->getLocation(), diag::note_declared_at);
3229 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003230 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003231 }
3232 return CompleteObject();
3233 }
3234 }
3235
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003236 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003237 return CompleteObject();
3238 } else {
3239 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3240
3241 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003242 if (const MaterializeTemporaryExpr *MTE =
3243 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3244 assert(MTE->getStorageDuration() == SD_Static &&
3245 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003246
Richard Smithe6c01442013-06-05 00:46:14 +00003247 // Per C++1y [expr.const]p2:
3248 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3249 // - a [...] glvalue of integral or enumeration type that refers to
3250 // a non-volatile const object [...]
3251 // [...]
3252 // - a [...] glvalue of literal type that refers to a non-volatile
3253 // object whose lifetime began within the evaluation of e.
3254 //
3255 // C++11 misses the 'began within the evaluation of e' check and
3256 // instead allows all temporaries, including things like:
3257 // int &&r = 1;
3258 // int x = ++r;
3259 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003260 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003261 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3262 const ValueDecl *ED = MTE->getExtendingDecl();
3263 if (!(BaseType.isConstQualified() &&
3264 BaseType->isIntegralOrEnumerationType()) &&
3265 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003266 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003267 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3268 return CompleteObject();
3269 }
3270
3271 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3272 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003273 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003274 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003275 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003276 return CompleteObject();
3277 }
3278 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003279 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003280 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003281 }
Richard Smith3229b742013-05-05 21:17:10 +00003282
3283 // Volatile temporary objects cannot be accessed in constant expressions.
3284 if (BaseType.isVolatileQualified()) {
3285 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003286 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003287 << AK << 0;
3288 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3289 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003290 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003291 }
3292 return CompleteObject();
3293 }
3294 }
3295
Richard Smith7525ff62013-05-09 07:14:00 +00003296 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003297 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003298 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003299 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3300 LVal.getLValueCallIndex(),
3301 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003302 BaseType = Info.Ctx.getCanonicalType(BaseType);
3303 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003304 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003305 }
3306
Richard Smith9defb7d2018-02-21 03:38:30 +00003307 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003308 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003309 //
3310 // FIXME: Not all local state is mutable. Allow local constant subobjects
3311 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003312 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3313 Info.EvalStatus.HasSideEffects) ||
3314 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003315 return CompleteObject();
3316
Richard Smith9defb7d2018-02-21 03:38:30 +00003317 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003318}
3319
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003320/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003321/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3322/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003323///
3324/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003325/// \param Conv - The expression for which we are performing the conversion.
3326/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003327/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3328/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003329/// \param LVal - The glvalue on which we are attempting to perform this action.
3330/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003331static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003332 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003333 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003334 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003335 return false;
3336
Richard Smith3229b742013-05-05 21:17:10 +00003337 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003338 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003339 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003340 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3341 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3342 // initializer until now for such expressions. Such an expression can't be
3343 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003344 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003345 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003346 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003347 }
Richard Smith3229b742013-05-05 21:17:10 +00003348 APValue Lit;
3349 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3350 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003351 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003352 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003353 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003354 // We represent a string literal array as an lvalue pointing at the
3355 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003356 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003357 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003358 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003359 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003360 }
Richard Smith11562c52011-10-28 17:51:58 +00003361 }
3362
Richard Smith3229b742013-05-05 21:17:10 +00003363 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3364 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003365}
3366
3367/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003368static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003369 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003370 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003371 return false;
3372
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003373 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003374 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003375 return false;
3376 }
3377
Richard Smith3229b742013-05-05 21:17:10 +00003378 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003379 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3380}
3381
3382namespace {
3383struct CompoundAssignSubobjectHandler {
3384 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003385 const Expr *E;
3386 QualType PromotedLHSType;
3387 BinaryOperatorKind Opcode;
3388 const APValue &RHS;
3389
3390 static const AccessKinds AccessKind = AK_Assign;
3391
3392 typedef bool result_type;
3393
3394 bool checkConst(QualType QT) {
3395 // Assigning to a const object has undefined behavior.
3396 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003397 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003398 return false;
3399 }
3400 return true;
3401 }
3402
3403 bool failed() { return false; }
3404 bool found(APValue &Subobj, QualType SubobjType) {
3405 switch (Subobj.getKind()) {
3406 case APValue::Int:
3407 return found(Subobj.getInt(), SubobjType);
3408 case APValue::Float:
3409 return found(Subobj.getFloat(), SubobjType);
3410 case APValue::ComplexInt:
3411 case APValue::ComplexFloat:
3412 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003413 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003414 return false;
3415 case APValue::LValue:
3416 return foundPointer(Subobj, SubobjType);
3417 default:
3418 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003419 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003420 return false;
3421 }
3422 }
3423 bool found(APSInt &Value, QualType SubobjType) {
3424 if (!checkConst(SubobjType))
3425 return false;
3426
3427 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3428 // We don't support compound assignment on integer-cast-to-pointer
3429 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003430 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003431 return false;
3432 }
3433
3434 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3435 SubobjType, Value);
3436 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3437 return false;
3438 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3439 return true;
3440 }
3441 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003442 return checkConst(SubobjType) &&
3443 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3444 Value) &&
3445 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3446 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003447 }
3448 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3449 if (!checkConst(SubobjType))
3450 return false;
3451
3452 QualType PointeeType;
3453 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3454 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003455
3456 if (PointeeType.isNull() || !RHS.isInt() ||
3457 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003458 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003459 return false;
3460 }
3461
Richard Smithd6cc1982017-01-31 02:23:02 +00003462 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003463 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003464 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003465
3466 LValue LVal;
3467 LVal.setFrom(Info.Ctx, Subobj);
3468 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3469 return false;
3470 LVal.moveInto(Subobj);
3471 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003472 }
3473 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3474 llvm_unreachable("shouldn't encounter string elements here");
3475 }
3476};
3477} // end anonymous namespace
3478
3479const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3480
3481/// Perform a compound assignment of LVal <op>= RVal.
3482static bool handleCompoundAssignment(
3483 EvalInfo &Info, const Expr *E,
3484 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3485 BinaryOperatorKind Opcode, const APValue &RVal) {
3486 if (LVal.Designator.Invalid)
3487 return false;
3488
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003489 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003490 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003491 return false;
3492 }
3493
3494 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3495 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3496 RVal };
3497 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3498}
3499
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003500namespace {
3501struct IncDecSubobjectHandler {
3502 EvalInfo &Info;
3503 const UnaryOperator *E;
3504 AccessKinds AccessKind;
3505 APValue *Old;
3506
Richard Smith243ef902013-05-05 23:31:59 +00003507 typedef bool result_type;
3508
3509 bool checkConst(QualType QT) {
3510 // Assigning to a const object has undefined behavior.
3511 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003512 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003513 return false;
3514 }
3515 return true;
3516 }
3517
3518 bool failed() { return false; }
3519 bool found(APValue &Subobj, QualType SubobjType) {
3520 // Stash the old value. Also clear Old, so we don't clobber it later
3521 // if we're post-incrementing a complex.
3522 if (Old) {
3523 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003524 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003525 }
3526
3527 switch (Subobj.getKind()) {
3528 case APValue::Int:
3529 return found(Subobj.getInt(), SubobjType);
3530 case APValue::Float:
3531 return found(Subobj.getFloat(), SubobjType);
3532 case APValue::ComplexInt:
3533 return found(Subobj.getComplexIntReal(),
3534 SubobjType->castAs<ComplexType>()->getElementType()
3535 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3536 case APValue::ComplexFloat:
3537 return found(Subobj.getComplexFloatReal(),
3538 SubobjType->castAs<ComplexType>()->getElementType()
3539 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3540 case APValue::LValue:
3541 return foundPointer(Subobj, SubobjType);
3542 default:
3543 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003544 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003545 return false;
3546 }
3547 }
3548 bool found(APSInt &Value, QualType SubobjType) {
3549 if (!checkConst(SubobjType))
3550 return false;
3551
3552 if (!SubobjType->isIntegerType()) {
3553 // We don't support increment / decrement on integer-cast-to-pointer
3554 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003555 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003556 return false;
3557 }
3558
3559 if (Old) *Old = APValue(Value);
3560
3561 // bool arithmetic promotes to int, and the conversion back to bool
3562 // doesn't reduce mod 2^n, so special-case it.
3563 if (SubobjType->isBooleanType()) {
3564 if (AccessKind == AK_Increment)
3565 Value = 1;
3566 else
3567 Value = !Value;
3568 return true;
3569 }
3570
3571 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003572 if (AccessKind == AK_Increment) {
3573 ++Value;
3574
3575 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3576 APSInt ActualValue(Value, /*IsUnsigned*/true);
3577 return HandleOverflow(Info, E, ActualValue, SubobjType);
3578 }
3579 } else {
3580 --Value;
3581
3582 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3583 unsigned BitWidth = Value.getBitWidth();
3584 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3585 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003586 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003587 }
3588 }
3589 return true;
3590 }
3591 bool found(APFloat &Value, QualType SubobjType) {
3592 if (!checkConst(SubobjType))
3593 return false;
3594
3595 if (Old) *Old = APValue(Value);
3596
3597 APFloat One(Value.getSemantics(), 1);
3598 if (AccessKind == AK_Increment)
3599 Value.add(One, APFloat::rmNearestTiesToEven);
3600 else
3601 Value.subtract(One, APFloat::rmNearestTiesToEven);
3602 return true;
3603 }
3604 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3605 if (!checkConst(SubobjType))
3606 return false;
3607
3608 QualType PointeeType;
3609 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3610 PointeeType = PT->getPointeeType();
3611 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003612 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003613 return false;
3614 }
3615
3616 LValue LVal;
3617 LVal.setFrom(Info.Ctx, Subobj);
3618 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3619 AccessKind == AK_Increment ? 1 : -1))
3620 return false;
3621 LVal.moveInto(Subobj);
3622 return true;
3623 }
3624 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3625 llvm_unreachable("shouldn't encounter string elements here");
3626 }
3627};
3628} // end anonymous namespace
3629
3630/// Perform an increment or decrement on LVal.
3631static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3632 QualType LValType, bool IsIncrement, APValue *Old) {
3633 if (LVal.Designator.Invalid)
3634 return false;
3635
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003636 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003637 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003638 return false;
3639 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003640
3641 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3642 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3643 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3644 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3645}
3646
Richard Smithe97cbd72011-11-11 04:05:33 +00003647/// Build an lvalue for the object argument of a member function call.
3648static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3649 LValue &This) {
3650 if (Object->getType()->isPointerType())
3651 return EvaluatePointer(Object, This, Info);
3652
3653 if (Object->isGLValue())
3654 return EvaluateLValue(Object, This, Info);
3655
Richard Smithd9f663b2013-04-22 15:31:51 +00003656 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003657 return EvaluateTemporary(Object, This, Info);
3658
Faisal Valie690b7a2016-07-02 22:34:24 +00003659 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003660 return false;
3661}
3662
3663/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3664/// lvalue referring to the result.
3665///
3666/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003667/// \param LV - An lvalue referring to the base of the member pointer.
3668/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003669/// \param IncludeMember - Specifies whether the member itself is included in
3670/// the resulting LValue subobject designator. This is not possible when
3671/// creating a bound member function.
3672/// \return The field or method declaration to which the member pointer refers,
3673/// or 0 if evaluation fails.
3674static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003675 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003676 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003677 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003678 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003679 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003680 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003681 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003682
3683 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3684 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003685 if (!MemPtr.getDecl()) {
3686 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003687 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003688 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003689 }
Richard Smith253c2a32012-01-27 01:14:48 +00003690
Richard Smith027bf112011-11-17 22:56:20 +00003691 if (MemPtr.isDerivedMember()) {
3692 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003693 // The end of the derived-to-base path for the base object must match the
3694 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003695 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003696 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003697 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003698 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003699 }
Richard Smith027bf112011-11-17 22:56:20 +00003700 unsigned PathLengthToMember =
3701 LV.Designator.Entries.size() - MemPtr.Path.size();
3702 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3703 const CXXRecordDecl *LVDecl = getAsBaseClass(
3704 LV.Designator.Entries[PathLengthToMember + I]);
3705 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003706 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003707 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003708 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003709 }
Richard Smith027bf112011-11-17 22:56:20 +00003710 }
3711
3712 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003713 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003714 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003715 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003716 } else if (!MemPtr.Path.empty()) {
3717 // Extend the LValue path with the member pointer's path.
3718 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3719 MemPtr.Path.size() + IncludeMember);
3720
3721 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003722 if (const PointerType *PT = LVType->getAs<PointerType>())
3723 LVType = PT->getPointeeType();
3724 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3725 assert(RD && "member pointer access on non-class-type expression");
3726 // The first class in the path is that of the lvalue.
3727 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3728 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003729 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003730 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003731 RD = Base;
3732 }
3733 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003734 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3735 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003736 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003737 }
3738
3739 // Add the member. Note that we cannot build bound member functions here.
3740 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003741 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003742 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003743 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003744 } else if (const IndirectFieldDecl *IFD =
3745 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003746 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003747 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003748 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003749 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003750 }
Richard Smith027bf112011-11-17 22:56:20 +00003751 }
3752
3753 return MemPtr.getDecl();
3754}
3755
Richard Smith84401042013-06-03 05:03:02 +00003756static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3757 const BinaryOperator *BO,
3758 LValue &LV,
3759 bool IncludeMember = true) {
3760 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3761
3762 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003763 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003764 MemberPtr MemPtr;
3765 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3766 }
Craig Topper36250ad2014-05-12 05:36:57 +00003767 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003768 }
3769
3770 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3771 BO->getRHS(), IncludeMember);
3772}
3773
Richard Smith027bf112011-11-17 22:56:20 +00003774/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3775/// the provided lvalue, which currently refers to the base object.
3776static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3777 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003778 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003779 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003780 return false;
3781
Richard Smitha8105bc2012-01-06 16:39:00 +00003782 QualType TargetQT = E->getType();
3783 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3784 TargetQT = PT->getPointeeType();
3785
3786 // Check this cast lands within the final derived-to-base subobject path.
3787 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003788 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003789 << D.MostDerivedType << TargetQT;
3790 return false;
3791 }
3792
Richard Smith027bf112011-11-17 22:56:20 +00003793 // Check the type of the final cast. We don't need to check the path,
3794 // since a cast can only be formed if the path is unique.
3795 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003796 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3797 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003798 if (NewEntriesSize == D.MostDerivedPathLength)
3799 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3800 else
Richard Smith027bf112011-11-17 22:56:20 +00003801 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003802 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003803 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003804 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003805 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003806 }
Richard Smith027bf112011-11-17 22:56:20 +00003807
3808 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003809 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003810}
3811
Mike Stump876387b2009-10-27 22:09:17 +00003812namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003813enum EvalStmtResult {
3814 /// Evaluation failed.
3815 ESR_Failed,
3816 /// Hit a 'return' statement.
3817 ESR_Returned,
3818 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003819 ESR_Succeeded,
3820 /// Hit a 'continue' statement.
3821 ESR_Continue,
3822 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003823 ESR_Break,
3824 /// Still scanning for 'case' or 'default' statement.
3825 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003826};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003827}
Richard Smith254a73d2011-10-28 22:34:42 +00003828
Richard Smith97fcf4b2016-08-14 23:15:52 +00003829static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3830 // We don't need to evaluate the initializer for a static local.
3831 if (!VD->hasLocalStorage())
3832 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003833
Richard Smith97fcf4b2016-08-14 23:15:52 +00003834 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003835 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003836
Richard Smith97fcf4b2016-08-14 23:15:52 +00003837 const Expr *InitE = VD->getInit();
3838 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003839 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3840 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003841 Val = APValue();
3842 return false;
3843 }
Richard Smith51f03172013-06-20 03:00:05 +00003844
Richard Smith97fcf4b2016-08-14 23:15:52 +00003845 if (InitE->isValueDependent())
3846 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003847
Richard Smith97fcf4b2016-08-14 23:15:52 +00003848 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3849 // Wipe out any partially-computed value, to allow tracking that this
3850 // evaluation failed.
3851 Val = APValue();
3852 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003853 }
3854
3855 return true;
3856}
3857
Richard Smith97fcf4b2016-08-14 23:15:52 +00003858static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3859 bool OK = true;
3860
3861 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3862 OK &= EvaluateVarDecl(Info, VD);
3863
3864 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3865 for (auto *BD : DD->bindings())
3866 if (auto *VD = BD->getHoldingVar())
3867 OK &= EvaluateDecl(Info, VD);
3868
3869 return OK;
3870}
3871
3872
Richard Smith4e18ca52013-05-06 05:56:11 +00003873/// Evaluate a condition (either a variable declaration or an expression).
3874static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3875 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003876 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003877 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3878 return false;
3879 return EvaluateAsBooleanCondition(Cond, Result, Info);
3880}
3881
Richard Smith89210072016-04-04 23:29:43 +00003882namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003883/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003884/// statement should be stored.
3885struct StmtResult {
3886 /// The APValue that should be filled in with the returned value.
3887 APValue &Value;
3888 /// The location containing the result, if any (used to support RVO).
3889 const LValue *Slot;
3890};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003891
3892struct TempVersionRAII {
3893 CallStackFrame &Frame;
3894
3895 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3896 Frame.pushTempVersion();
3897 }
3898
3899 ~TempVersionRAII() {
3900 Frame.popTempVersion();
3901 }
3902};
3903
Richard Smith89210072016-04-04 23:29:43 +00003904}
Richard Smith52a980a2015-08-28 02:43:42 +00003905
3906static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003907 const Stmt *S,
3908 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003909
3910/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003911static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003912 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003913 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003914 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003915 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003916 case ESR_Break:
3917 return ESR_Succeeded;
3918 case ESR_Succeeded:
3919 case ESR_Continue:
3920 return ESR_Continue;
3921 case ESR_Failed:
3922 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003923 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003924 return ESR;
3925 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003926 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003927}
3928
Richard Smith496ddcf2013-05-12 17:32:42 +00003929/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003930static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003931 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003932 BlockScopeRAII Scope(Info);
3933
Richard Smith496ddcf2013-05-12 17:32:42 +00003934 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003935 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003936 {
3937 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003938 if (const Stmt *Init = SS->getInit()) {
3939 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3940 if (ESR != ESR_Succeeded)
3941 return ESR;
3942 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003943 if (SS->getConditionVariable() &&
3944 !EvaluateDecl(Info, SS->getConditionVariable()))
3945 return ESR_Failed;
3946 if (!EvaluateInteger(SS->getCond(), Value, Info))
3947 return ESR_Failed;
3948 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003949
3950 // Find the switch case corresponding to the value of the condition.
3951 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003952 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003953 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3954 SC = SC->getNextSwitchCase()) {
3955 if (isa<DefaultStmt>(SC)) {
3956 Found = SC;
3957 continue;
3958 }
3959
3960 const CaseStmt *CS = cast<CaseStmt>(SC);
3961 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3962 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3963 : LHS;
3964 if (LHS <= Value && Value <= RHS) {
3965 Found = SC;
3966 break;
3967 }
3968 }
3969
3970 if (!Found)
3971 return ESR_Succeeded;
3972
3973 // Search the switch body for the switch case and evaluate it from there.
3974 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3975 case ESR_Break:
3976 return ESR_Succeeded;
3977 case ESR_Succeeded:
3978 case ESR_Continue:
3979 case ESR_Failed:
3980 case ESR_Returned:
3981 return ESR;
3982 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003983 // This can only happen if the switch case is nested within a statement
3984 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003985 Info.FFDiag(Found->getBeginLoc(),
3986 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003987 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003988 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003989 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003990}
3991
Richard Smith254a73d2011-10-28 22:34:42 +00003992// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003993static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003994 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003995 if (!Info.nextStep(S))
3996 return ESR_Failed;
3997
Richard Smith496ddcf2013-05-12 17:32:42 +00003998 // If we're hunting down a 'case' or 'default' label, recurse through
3999 // substatements until we hit the label.
4000 if (Case) {
4001 // FIXME: We don't start the lifetime of objects whose initialization we
4002 // jump over. However, such objects must be of class type with a trivial
4003 // default constructor that initialize all subobjects, so must be empty,
4004 // so this almost never matters.
4005 switch (S->getStmtClass()) {
4006 case Stmt::CompoundStmtClass:
4007 // FIXME: Precompute which substatement of a compound statement we
4008 // would jump to, and go straight there rather than performing a
4009 // linear scan each time.
4010 case Stmt::LabelStmtClass:
4011 case Stmt::AttributedStmtClass:
4012 case Stmt::DoStmtClass:
4013 break;
4014
4015 case Stmt::CaseStmtClass:
4016 case Stmt::DefaultStmtClass:
4017 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004018 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004019 break;
4020
4021 case Stmt::IfStmtClass: {
4022 // FIXME: Precompute which side of an 'if' we would jump to, and go
4023 // straight there rather than scanning both sides.
4024 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004025
4026 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4027 // preceded by our switch label.
4028 BlockScopeRAII Scope(Info);
4029
Richard Smith496ddcf2013-05-12 17:32:42 +00004030 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4031 if (ESR != ESR_CaseNotFound || !IS->getElse())
4032 return ESR;
4033 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4034 }
4035
4036 case Stmt::WhileStmtClass: {
4037 EvalStmtResult ESR =
4038 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4039 if (ESR != ESR_Continue)
4040 return ESR;
4041 break;
4042 }
4043
4044 case Stmt::ForStmtClass: {
4045 const ForStmt *FS = cast<ForStmt>(S);
4046 EvalStmtResult ESR =
4047 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4048 if (ESR != ESR_Continue)
4049 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004050 if (FS->getInc()) {
4051 FullExpressionRAII IncScope(Info);
4052 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4053 return ESR_Failed;
4054 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004055 break;
4056 }
4057
4058 case Stmt::DeclStmtClass:
4059 // FIXME: If the variable has initialization that can't be jumped over,
4060 // bail out of any immediately-surrounding compound-statement too.
4061 default:
4062 return ESR_CaseNotFound;
4063 }
4064 }
4065
Richard Smith254a73d2011-10-28 22:34:42 +00004066 switch (S->getStmtClass()) {
4067 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004068 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004069 // Don't bother evaluating beyond an expression-statement which couldn't
4070 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004071 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004072 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004073 return ESR_Failed;
4074 return ESR_Succeeded;
4075 }
4076
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004077 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004078 return ESR_Failed;
4079
4080 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004081 return ESR_Succeeded;
4082
Richard Smithd9f663b2013-04-22 15:31:51 +00004083 case Stmt::DeclStmtClass: {
4084 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004085 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004086 // Each declaration initialization is its own full-expression.
4087 // FIXME: This isn't quite right; if we're performing aggregate
4088 // initialization, each braced subexpression is its own full-expression.
4089 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004090 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004091 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004092 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004093 return ESR_Succeeded;
4094 }
4095
Richard Smith357362d2011-12-13 06:39:58 +00004096 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004097 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004098 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004099 if (RetExpr &&
4100 !(Result.Slot
4101 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4102 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004103 return ESR_Failed;
4104 return ESR_Returned;
4105 }
Richard Smith254a73d2011-10-28 22:34:42 +00004106
4107 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004108 BlockScopeRAII Scope(Info);
4109
Richard Smith254a73d2011-10-28 22:34:42 +00004110 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004111 for (const auto *BI : CS->body()) {
4112 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004113 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004114 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004115 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004116 return ESR;
4117 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004118 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004119 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004120
4121 case Stmt::IfStmtClass: {
4122 const IfStmt *IS = cast<IfStmt>(S);
4123
4124 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004125 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004126 if (const Stmt *Init = IS->getInit()) {
4127 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4128 if (ESR != ESR_Succeeded)
4129 return ESR;
4130 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004131 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004132 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004133 return ESR_Failed;
4134
4135 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4136 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4137 if (ESR != ESR_Succeeded)
4138 return ESR;
4139 }
4140 return ESR_Succeeded;
4141 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004142
4143 case Stmt::WhileStmtClass: {
4144 const WhileStmt *WS = cast<WhileStmt>(S);
4145 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004147 bool Continue;
4148 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4149 Continue))
4150 return ESR_Failed;
4151 if (!Continue)
4152 break;
4153
4154 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4155 if (ESR != ESR_Continue)
4156 return ESR;
4157 }
4158 return ESR_Succeeded;
4159 }
4160
4161 case Stmt::DoStmtClass: {
4162 const DoStmt *DS = cast<DoStmt>(S);
4163 bool Continue;
4164 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004165 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004166 if (ESR != ESR_Continue)
4167 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004168 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004169
Richard Smith08d6a2c2013-07-24 07:11:57 +00004170 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004171 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4172 return ESR_Failed;
4173 } while (Continue);
4174 return ESR_Succeeded;
4175 }
4176
4177 case Stmt::ForStmtClass: {
4178 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004179 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004180 if (FS->getInit()) {
4181 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4182 if (ESR != ESR_Succeeded)
4183 return ESR;
4184 }
4185 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004186 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004187 bool Continue = true;
4188 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4189 FS->getCond(), Continue))
4190 return ESR_Failed;
4191 if (!Continue)
4192 break;
4193
4194 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4195 if (ESR != ESR_Continue)
4196 return ESR;
4197
Richard Smith08d6a2c2013-07-24 07:11:57 +00004198 if (FS->getInc()) {
4199 FullExpressionRAII IncScope(Info);
4200 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4201 return ESR_Failed;
4202 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004203 }
4204 return ESR_Succeeded;
4205 }
4206
Richard Smith896e0d72013-05-06 06:51:17 +00004207 case Stmt::CXXForRangeStmtClass: {
4208 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004209 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004210
Richard Smith8baa5002018-09-28 18:44:09 +00004211 // Evaluate the init-statement if present.
4212 if (FS->getInit()) {
4213 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4214 if (ESR != ESR_Succeeded)
4215 return ESR;
4216 }
4217
Richard Smith896e0d72013-05-06 06:51:17 +00004218 // Initialize the __range variable.
4219 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4220 if (ESR != ESR_Succeeded)
4221 return ESR;
4222
4223 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004224 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4225 if (ESR != ESR_Succeeded)
4226 return ESR;
4227 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004228 if (ESR != ESR_Succeeded)
4229 return ESR;
4230
4231 while (true) {
4232 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004233 {
4234 bool Continue = true;
4235 FullExpressionRAII CondExpr(Info);
4236 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4237 return ESR_Failed;
4238 if (!Continue)
4239 break;
4240 }
Richard Smith896e0d72013-05-06 06:51:17 +00004241
4242 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004243 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004244 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4245 if (ESR != ESR_Succeeded)
4246 return ESR;
4247
4248 // Loop body.
4249 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4250 if (ESR != ESR_Continue)
4251 return ESR;
4252
4253 // Increment: ++__begin
4254 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4255 return ESR_Failed;
4256 }
4257
4258 return ESR_Succeeded;
4259 }
4260
Richard Smith496ddcf2013-05-12 17:32:42 +00004261 case Stmt::SwitchStmtClass:
4262 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4263
Richard Smith4e18ca52013-05-06 05:56:11 +00004264 case Stmt::ContinueStmtClass:
4265 return ESR_Continue;
4266
4267 case Stmt::BreakStmtClass:
4268 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004269
4270 case Stmt::LabelStmtClass:
4271 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4272
4273 case Stmt::AttributedStmtClass:
4274 // As a general principle, C++11 attributes can be ignored without
4275 // any semantic impact.
4276 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4277 Case);
4278
4279 case Stmt::CaseStmtClass:
4280 case Stmt::DefaultStmtClass:
4281 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004282 }
4283}
4284
Richard Smithcc36f692011-12-22 02:22:31 +00004285/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4286/// default constructor. If so, we'll fold it whether or not it's marked as
4287/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4288/// so we need special handling.
4289static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004290 const CXXConstructorDecl *CD,
4291 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004292 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4293 return false;
4294
Richard Smith66e05fe2012-01-18 05:21:49 +00004295 // Value-initialization does not call a trivial default constructor, so such a
4296 // call is a core constant expression whether or not the constructor is
4297 // constexpr.
4298 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004299 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004300 // FIXME: If DiagDecl is an implicitly-declared special member function,
4301 // we should be much more explicit about why it's not constexpr.
4302 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4303 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4304 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004305 } else {
4306 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4307 }
4308 }
4309 return true;
4310}
4311
Richard Smith357362d2011-12-13 06:39:58 +00004312/// CheckConstexprFunction - Check that a function can be called in a constant
4313/// expression.
4314static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4315 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004316 const FunctionDecl *Definition,
4317 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004318 // Potential constant expressions can contain calls to declared, but not yet
4319 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004320 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004321 Declaration->isConstexpr())
4322 return false;
4323
James Y Knightc7d3e602018-10-05 17:49:48 +00004324 // Bail out if the function declaration itself is invalid. We will
4325 // have produced a relevant diagnostic while parsing it, so just
4326 // note the problematic sub-expression.
4327 if (Declaration->isInvalidDecl()) {
4328 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004329 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004330 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004331
Richard Smith357362d2011-12-13 06:39:58 +00004332 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004333 if (Definition && Definition->isConstexpr() &&
4334 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004335 return true;
4336
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004337 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004338 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004339
Richard Smith5179eb72016-06-28 19:03:57 +00004340 // If this function is not constexpr because it is an inherited
4341 // non-constexpr constructor, diagnose that directly.
4342 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4343 if (CD && CD->isInheritingConstructor()) {
4344 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004345 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004346 DiagDecl = CD = Inherited;
4347 }
4348
4349 // FIXME: If DiagDecl is an implicitly-declared special member function
4350 // or an inheriting constructor, we should be much more explicit about why
4351 // it's not constexpr.
4352 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004353 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004354 << CD->getInheritedConstructor().getConstructor()->getParent();
4355 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004356 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004357 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004358 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4359 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004360 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004361 }
4362 return false;
4363}
4364
Richard Smithbe6dd812014-11-19 21:27:17 +00004365/// Determine if a class has any fields that might need to be copied by a
4366/// trivial copy or move operation.
4367static bool hasFields(const CXXRecordDecl *RD) {
4368 if (!RD || RD->isEmpty())
4369 return false;
4370 for (auto *FD : RD->fields()) {
4371 if (FD->isUnnamedBitfield())
4372 continue;
4373 return true;
4374 }
4375 for (auto &Base : RD->bases())
4376 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4377 return true;
4378 return false;
4379}
4380
Richard Smithd62306a2011-11-10 06:34:14 +00004381namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004382typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004383}
4384
4385/// EvaluateArgs - Evaluate the arguments to a function call.
4386static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4387 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004388 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004389 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004390 I != E; ++I) {
4391 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4392 // If we're checking for a potential constant expression, evaluate all
4393 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004394 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004395 return false;
4396 Success = false;
4397 }
4398 }
4399 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004400}
4401
Richard Smith254a73d2011-10-28 22:34:42 +00004402/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004403static bool HandleFunctionCall(SourceLocation CallLoc,
4404 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004405 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004406 EvalInfo &Info, APValue &Result,
4407 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004408 ArgVector ArgValues(Args.size());
4409 if (!EvaluateArgs(Args, ArgValues, Info))
4410 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004411
Richard Smith253c2a32012-01-27 01:14:48 +00004412 if (!Info.CheckCallLimit(CallLoc))
4413 return false;
4414
4415 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004416
4417 // For a trivial copy or move assignment, perform an APValue copy. This is
4418 // essential for unions, where the operations performed by the assignment
4419 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004420 //
4421 // Skip this for non-union classes with no fields; in that case, the defaulted
4422 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004423 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004424 if (MD && MD->isDefaulted() &&
4425 (MD->getParent()->isUnion() ||
4426 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004427 assert(This &&
4428 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4429 LValue RHS;
4430 RHS.setFrom(Info.Ctx, ArgValues[0]);
4431 APValue RHSValue;
4432 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4433 RHS, RHSValue))
4434 return false;
4435 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4436 RHSValue))
4437 return false;
4438 This->moveInto(Result);
4439 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004440 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004441 // We're in a lambda; determine the lambda capture field maps unless we're
4442 // just constexpr checking a lambda's call operator. constexpr checking is
4443 // done before the captures have been added to the closure object (unless
4444 // we're inferring constexpr-ness), so we don't have access to them in this
4445 // case. But since we don't need the captures to constexpr check, we can
4446 // just ignore them.
4447 if (!Info.checkingPotentialConstantExpression())
4448 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4449 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004450 }
4451
Richard Smith52a980a2015-08-28 02:43:42 +00004452 StmtResult Ret = {Result, ResultSlot};
4453 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004454 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004455 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004456 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004457 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004458 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004459 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004460}
4461
Richard Smithd62306a2011-11-10 06:34:14 +00004462/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004463static bool HandleConstructorCall(const Expr *E, const LValue &This,
4464 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004465 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004466 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004467 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004468 if (!Info.CheckCallLimit(CallLoc))
4469 return false;
4470
Richard Smith3607ffe2012-02-13 03:54:03 +00004471 const CXXRecordDecl *RD = Definition->getParent();
4472 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004473 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004474 return false;
4475 }
4476
Erik Pilkington42925492017-10-04 00:18:55 +00004477 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004478 Info, {This.getLValueBase(),
4479 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004480 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004481
Richard Smith52a980a2015-08-28 02:43:42 +00004482 // FIXME: Creating an APValue just to hold a nonexistent return value is
4483 // wasteful.
4484 APValue RetVal;
4485 StmtResult Ret = {RetVal, nullptr};
4486
Richard Smith5179eb72016-06-28 19:03:57 +00004487 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004488 if (Definition->isDelegatingConstructor()) {
4489 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004490 {
4491 FullExpressionRAII InitScope(Info);
4492 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4493 return false;
4494 }
Richard Smith52a980a2015-08-28 02:43:42 +00004495 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004496 }
4497
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004498 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004499 // essential for unions (or classes with anonymous union members), where the
4500 // operations performed by the constructor cannot be represented by
4501 // ctor-initializers.
4502 //
4503 // Skip this for empty non-union classes; we should not perform an
4504 // lvalue-to-rvalue conversion on them because their copy constructor does not
4505 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004506 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004507 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004508 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004509 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004510 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004511 return handleLValueToRValueConversion(
4512 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4513 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004514 }
4515
4516 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004517 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004518 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004519 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004520
John McCalld7bca762012-05-01 00:38:49 +00004521 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004522 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4523
Richard Smith08d6a2c2013-07-24 07:11:57 +00004524 // A scope for temporaries lifetime-extended by reference members.
4525 BlockScopeRAII LifetimeExtendedScope(Info);
4526
Richard Smith253c2a32012-01-27 01:14:48 +00004527 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004528 unsigned BasesSeen = 0;
4529#ifndef NDEBUG
4530 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4531#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004532 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004533 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004534 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004535 APValue *Value = &Result;
4536
4537 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004538 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004539 if (I->isBaseInitializer()) {
4540 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004541#ifndef NDEBUG
4542 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004543 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004544 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4545 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4546 "base class initializers not in expected order");
4547 ++BaseIt;
4548#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004549 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004550 BaseType->getAsCXXRecordDecl(), &Layout))
4551 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004552 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004553 } else if ((FD = I->getMember())) {
4554 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004555 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004556 if (RD->isUnion()) {
4557 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004558 Value = &Result.getUnionValue();
4559 } else {
4560 Value = &Result.getStructField(FD->getFieldIndex());
4561 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004562 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004563 // Walk the indirect field decl's chain to find the object to initialize,
4564 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004565 auto IndirectFieldChain = IFD->chain();
4566 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004567 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004568 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4569 // Switch the union field if it differs. This happens if we had
4570 // preceding zero-initialization, and we're now initializing a union
4571 // subobject other than the first.
4572 // FIXME: In this case, the values of the other subobjects are
4573 // specified, since zero-initialization sets all padding bits to zero.
4574 if (Value->isUninit() ||
4575 (Value->isUnion() && Value->getUnionField() != FD)) {
4576 if (CD->isUnion())
4577 *Value = APValue(FD);
4578 else
4579 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004580 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004581 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004582 // Store Subobject as its parent before updating it for the last element
4583 // in the chain.
4584 if (C == IndirectFieldChain.back())
4585 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004586 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004587 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004588 if (CD->isUnion())
4589 Value = &Value->getUnionValue();
4590 else
4591 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004592 }
Richard Smithd62306a2011-11-10 06:34:14 +00004593 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004594 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004595 }
Richard Smith253c2a32012-01-27 01:14:48 +00004596
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004597 // Need to override This for implicit field initializers as in this case
4598 // This refers to innermost anonymous struct/union containing initializer,
4599 // not to currently constructed class.
4600 const Expr *Init = I->getInit();
4601 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4602 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004603 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004604 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4605 (FD && FD->isBitField() &&
4606 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004607 // If we're checking for a potential constant expression, evaluate all
4608 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004609 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004610 return false;
4611 Success = false;
4612 }
Richard Smithd62306a2011-11-10 06:34:14 +00004613 }
4614
Richard Smithd9f663b2013-04-22 15:31:51 +00004615 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004616 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004617}
4618
Richard Smith5179eb72016-06-28 19:03:57 +00004619static bool HandleConstructorCall(const Expr *E, const LValue &This,
4620 ArrayRef<const Expr*> Args,
4621 const CXXConstructorDecl *Definition,
4622 EvalInfo &Info, APValue &Result) {
4623 ArgVector ArgValues(Args.size());
4624 if (!EvaluateArgs(Args, ArgValues, Info))
4625 return false;
4626
4627 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4628 Info, Result);
4629}
4630
Eli Friedman9a156e52008-11-12 09:44:48 +00004631//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004632// Generic Evaluation
4633//===----------------------------------------------------------------------===//
4634namespace {
4635
Aaron Ballman68af21c2014-01-03 19:26:43 +00004636template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004637class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004638 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004639private:
Richard Smith52a980a2015-08-28 02:43:42 +00004640 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004641 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004642 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004643 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004644 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004645 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004646 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004647
Richard Smith17100ba2012-02-16 02:46:34 +00004648 // Check whether a conditional operator with a non-constant condition is a
4649 // potential constant expression. If neither arm is a potential constant
4650 // expression, then the conditional operator is not either.
4651 template<typename ConditionalOperator>
4652 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004653 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004654
4655 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004656 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004657 {
Richard Smith17100ba2012-02-16 02:46:34 +00004658 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004659 StmtVisitorTy::Visit(E->getFalseExpr());
4660 if (Diag.empty())
4661 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004662 }
Richard Smith17100ba2012-02-16 02:46:34 +00004663
George Burgess IV8c892b52016-05-25 22:31:54 +00004664 {
4665 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004666 Diag.clear();
4667 StmtVisitorTy::Visit(E->getTrueExpr());
4668 if (Diag.empty())
4669 return;
4670 }
4671
4672 Error(E, diag::note_constexpr_conditional_never_const);
4673 }
4674
4675
4676 template<typename ConditionalOperator>
4677 bool HandleConditionalOperator(const ConditionalOperator *E) {
4678 bool BoolResult;
4679 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004680 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004681 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004682 return false;
4683 }
4684 if (Info.noteFailure()) {
4685 StmtVisitorTy::Visit(E->getTrueExpr());
4686 StmtVisitorTy::Visit(E->getFalseExpr());
4687 }
Richard Smith17100ba2012-02-16 02:46:34 +00004688 return false;
4689 }
4690
4691 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4692 return StmtVisitorTy::Visit(EvalExpr);
4693 }
4694
Peter Collingbournee9200682011-05-13 03:29:01 +00004695protected:
4696 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004697 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004698 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4699
Richard Smith92b1ce02011-12-12 09:28:41 +00004700 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004701 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004702 }
4703
Aaron Ballman68af21c2014-01-03 19:26:43 +00004704 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004705
4706public:
4707 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4708
4709 EvalInfo &getEvalInfo() { return Info; }
4710
Richard Smithf57d8cb2011-12-09 22:58:01 +00004711 /// Report an evaluation error. This should only be called when an error is
4712 /// first discovered. When propagating an error, just return false.
4713 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004714 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004715 return false;
4716 }
4717 bool Error(const Expr *E) {
4718 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4719 }
4720
Aaron Ballman68af21c2014-01-03 19:26:43 +00004721 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004722 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004723 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004724 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004725 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004726 }
4727
Bill Wendling8003edc2018-11-09 00:41:36 +00004728 bool VisitConstantExpr(const ConstantExpr *E)
4729 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004732 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004733 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004734 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004735 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004736 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004737 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004738 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004739 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004740 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004741 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004742 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4743 TempVersionRAII RAII(*Info.CurrentCall);
4744 return StmtVisitorTy::Visit(E->getExpr());
4745 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004746 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004747 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004748 // The initializer may not have been parsed yet, or might be erroneous.
4749 if (!E->getExpr())
4750 return Error(E);
4751 return StmtVisitorTy::Visit(E->getExpr());
4752 }
Richard Smith5894a912011-12-19 22:12:41 +00004753 // We cannot create any objects for which cleanups are required, so there is
4754 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004755 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004756 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004757
Aaron Ballman68af21c2014-01-03 19:26:43 +00004758 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004759 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4760 return static_cast<Derived*>(this)->VisitCastExpr(E);
4761 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004762 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4764 return static_cast<Derived*>(this)->VisitCastExpr(E);
4765 }
4766
Aaron Ballman68af21c2014-01-03 19:26:43 +00004767 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004768 switch (E->getOpcode()) {
4769 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004770 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004771
4772 case BO_Comma:
4773 VisitIgnoredValue(E->getLHS());
4774 return StmtVisitorTy::Visit(E->getRHS());
4775
4776 case BO_PtrMemD:
4777 case BO_PtrMemI: {
4778 LValue Obj;
4779 if (!HandleMemberPointerAccess(Info, E, Obj))
4780 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004781 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004782 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004783 return false;
4784 return DerivedSuccess(Result, E);
4785 }
4786 }
4787 }
4788
Aaron Ballman68af21c2014-01-03 19:26:43 +00004789 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004790 // Evaluate and cache the common expression. We treat it as a temporary,
4791 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004792 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004793 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004794 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004795
Richard Smith17100ba2012-02-16 02:46:34 +00004796 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004797 }
4798
Aaron Ballman68af21c2014-01-03 19:26:43 +00004799 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004800 bool IsBcpCall = false;
4801 // If the condition (ignoring parens) is a __builtin_constant_p call,
4802 // the result is a constant expression if it can be folded without
4803 // side-effects. This is an important GNU extension. See GCC PR38377
4804 // for discussion.
4805 if (const CallExpr *CallCE =
4806 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004807 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004808 IsBcpCall = true;
4809
4810 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4811 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004812 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004813 return false;
4814
Richard Smith6d4c6582013-11-05 22:18:15 +00004815 FoldConstant Fold(Info, IsBcpCall);
4816 if (!HandleConditionalOperator(E)) {
4817 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004818 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004819 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004820
4821 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004822 }
4823
Aaron Ballman68af21c2014-01-03 19:26:43 +00004824 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004825 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004826 return DerivedSuccess(*Value, E);
4827
4828 const Expr *Source = E->getSourceExpr();
4829 if (!Source)
4830 return Error(E);
4831 if (Source == E) { // sanity checking.
4832 assert(0 && "OpaqueValueExpr recursively refers to itself");
4833 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004834 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004835 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004836 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004837
Aaron Ballman68af21c2014-01-03 19:26:43 +00004838 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004839 APValue Result;
4840 if (!handleCallExpr(E, Result, nullptr))
4841 return false;
4842 return DerivedSuccess(Result, E);
4843 }
4844
4845 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004846 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004847 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004848 QualType CalleeType = Callee->getType();
4849
Craig Topper36250ad2014-05-12 05:36:57 +00004850 const FunctionDecl *FD = nullptr;
4851 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004852 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004853 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004854
Richard Smithe97cbd72011-11-11 04:05:33 +00004855 // Extract function decl and 'this' pointer from the callee.
4856 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004857 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004858 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4859 // Explicit bound member calls, such as x.f() or p->g();
4860 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004861 return false;
4862 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004863 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004864 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004865 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4866 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004867 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4868 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004869 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004870 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004871 return Error(Callee);
4872
4873 FD = dyn_cast<FunctionDecl>(Member);
4874 if (!FD)
4875 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004876 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004877 LValue Call;
4878 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004879 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004880
Richard Smitha8105bc2012-01-06 16:39:00 +00004881 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004882 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004883 FD = dyn_cast_or_null<FunctionDecl>(
4884 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004885 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004886 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004887 // Don't call function pointers which have been cast to some other type.
4888 // Per DR (no number yet), the caller and callee can differ in noexcept.
4889 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4890 CalleeType->getPointeeType(), FD->getType())) {
4891 return Error(E);
4892 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004893
4894 // Overloaded operator calls to member functions are represented as normal
4895 // calls with '*this' as the first argument.
4896 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4897 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004898 // FIXME: When selecting an implicit conversion for an overloaded
4899 // operator delete, we sometimes try to evaluate calls to conversion
4900 // operators without a 'this' parameter!
4901 if (Args.empty())
4902 return Error(E);
4903
Nick Lewycky13073a62017-06-12 21:15:44 +00004904 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004905 return false;
4906 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004907 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004908 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004909 // Map the static invoker for the lambda back to the call operator.
4910 // Conveniently, we don't have to slice out the 'this' argument (as is
4911 // being done for the non-static case), since a static member function
4912 // doesn't have an implicit argument passed in.
4913 const CXXRecordDecl *ClosureClass = MD->getParent();
4914 assert(
4915 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4916 "Number of captures must be zero for conversion to function-ptr");
4917
4918 const CXXMethodDecl *LambdaCallOp =
4919 ClosureClass->getLambdaCallOperator();
4920
4921 // Set 'FD', the function that will be called below, to the call
4922 // operator. If the closure object represents a generic lambda, find
4923 // the corresponding specialization of the call operator.
4924
4925 if (ClosureClass->isGenericLambda()) {
4926 assert(MD->isFunctionTemplateSpecialization() &&
4927 "A generic lambda's static-invoker function must be a "
4928 "template specialization");
4929 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4930 FunctionTemplateDecl *CallOpTemplate =
4931 LambdaCallOp->getDescribedFunctionTemplate();
4932 void *InsertPos = nullptr;
4933 FunctionDecl *CorrespondingCallOpSpecialization =
4934 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4935 assert(CorrespondingCallOpSpecialization &&
4936 "We must always have a function call operator specialization "
4937 "that corresponds to our static invoker specialization");
4938 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4939 } else
4940 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004941 }
4942
Fangrui Song6907ce22018-07-30 19:24:48 +00004943
Richard Smithe97cbd72011-11-11 04:05:33 +00004944 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004945 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004946
Richard Smith47b34932012-02-01 02:39:43 +00004947 if (This && !This->checkSubobject(Info, E, CSK_This))
4948 return false;
4949
Richard Smith3607ffe2012-02-13 03:54:03 +00004950 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4951 // calls to such functions in constant expressions.
4952 if (This && !HasQualifier &&
4953 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4954 return Error(E, diag::note_constexpr_virtual_call);
4955
Craig Topper36250ad2014-05-12 05:36:57 +00004956 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004957 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004958
Nick Lewycky13073a62017-06-12 21:15:44 +00004959 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4960 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004961 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004962 return false;
4963
Richard Smith52a980a2015-08-28 02:43:42 +00004964 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004965 }
4966
Aaron Ballman68af21c2014-01-03 19:26:43 +00004967 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004968 return StmtVisitorTy::Visit(E->getInitializer());
4969 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004970 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004971 if (E->getNumInits() == 0)
4972 return DerivedZeroInitialization(E);
4973 if (E->getNumInits() == 1)
4974 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004975 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004976 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004977 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004978 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004979 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004980 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004981 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004982 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004983 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004984 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004985 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004986
Richard Smithd62306a2011-11-10 06:34:14 +00004987 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004988 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004989 assert(!E->isArrow() && "missing call to bound member function?");
4990
Richard Smith2e312c82012-03-03 22:46:17 +00004991 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004992 if (!Evaluate(Val, Info, E->getBase()))
4993 return false;
4994
4995 QualType BaseTy = E->getBase()->getType();
4996
4997 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004998 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004999 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005000 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005001 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5002
Richard Smith9defb7d2018-02-21 03:38:30 +00005003 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005004 SubobjectDesignator Designator(BaseTy);
5005 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005006
Richard Smith3229b742013-05-05 21:17:10 +00005007 APValue Result;
5008 return extractSubobject(Info, E, Obj, Designator, Result) &&
5009 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005010 }
5011
Aaron Ballman68af21c2014-01-03 19:26:43 +00005012 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005013 switch (E->getCastKind()) {
5014 default:
5015 break;
5016
Richard Smitha23ab512013-05-23 00:30:41 +00005017 case CK_AtomicToNonAtomic: {
5018 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005019 // This does not need to be done in place even for class/array types:
5020 // atomic-to-non-atomic conversion implies copying the object
5021 // representation.
5022 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005023 return false;
5024 return DerivedSuccess(AtomicVal, E);
5025 }
5026
Richard Smith11562c52011-10-28 17:51:58 +00005027 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005028 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005029 return StmtVisitorTy::Visit(E->getSubExpr());
5030
5031 case CK_LValueToRValue: {
5032 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005033 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5034 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005035 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005036 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005037 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005038 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005039 return false;
5040 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005041 }
5042 }
5043
Richard Smithf57d8cb2011-12-09 22:58:01 +00005044 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005045 }
5046
Aaron Ballman68af21c2014-01-03 19:26:43 +00005047 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005048 return VisitUnaryPostIncDec(UO);
5049 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005050 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005051 return VisitUnaryPostIncDec(UO);
5052 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005053 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005054 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005055 return Error(UO);
5056
5057 LValue LVal;
5058 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5059 return false;
5060 APValue RVal;
5061 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5062 UO->isIncrementOp(), &RVal))
5063 return false;
5064 return DerivedSuccess(RVal, UO);
5065 }
5066
Aaron Ballman68af21c2014-01-03 19:26:43 +00005067 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005068 // We will have checked the full-expressions inside the statement expression
5069 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005070 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005071 return Error(E);
5072
Richard Smith08d6a2c2013-07-24 07:11:57 +00005073 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005074 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005075 if (CS->body_empty())
5076 return true;
5077
Richard Smith51f03172013-06-20 03:00:05 +00005078 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5079 BE = CS->body_end();
5080 /**/; ++BI) {
5081 if (BI + 1 == BE) {
5082 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5083 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005084 Info.FFDiag((*BI)->getBeginLoc(),
5085 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005086 return false;
5087 }
5088 return this->Visit(FinalExpr);
5089 }
5090
5091 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005092 StmtResult Result = { ReturnValue, nullptr };
5093 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005094 if (ESR != ESR_Succeeded) {
5095 // FIXME: If the statement-expression terminated due to 'return',
5096 // 'break', or 'continue', it would be nice to propagate that to
5097 // the outer statement evaluation rather than bailing out.
5098 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005099 Info.FFDiag((*BI)->getBeginLoc(),
5100 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005101 return false;
5102 }
5103 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005104
5105 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005106 }
5107
Richard Smith4a678122011-10-24 18:44:57 +00005108 /// Visit a value which is evaluated, but whose value is ignored.
5109 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005110 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005111 }
David Majnemere9807b22016-02-26 04:23:19 +00005112
5113 /// Potentially visit a MemberExpr's base expression.
5114 void VisitIgnoredBaseExpression(const Expr *E) {
5115 // While MSVC doesn't evaluate the base expression, it does diagnose the
5116 // presence of side-effecting behavior.
5117 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5118 return;
5119 VisitIgnoredValue(E);
5120 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005121};
5122
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005123} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005124
5125//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005126// Common base class for lvalue and temporary evaluation.
5127//===----------------------------------------------------------------------===//
5128namespace {
5129template<class Derived>
5130class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005131 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005132protected:
5133 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005134 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005135 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005136 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005137
5138 bool Success(APValue::LValueBase B) {
5139 Result.set(B);
5140 return true;
5141 }
5142
George Burgess IVf9013bf2017-02-10 22:52:29 +00005143 bool evaluatePointer(const Expr *E, LValue &Result) {
5144 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5145 }
5146
Richard Smith027bf112011-11-17 22:56:20 +00005147public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005148 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5149 : ExprEvaluatorBaseTy(Info), Result(Result),
5150 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005151
Richard Smith2e312c82012-03-03 22:46:17 +00005152 bool Success(const APValue &V, const Expr *E) {
5153 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005154 return true;
5155 }
Richard Smith027bf112011-11-17 22:56:20 +00005156
Richard Smith027bf112011-11-17 22:56:20 +00005157 bool VisitMemberExpr(const MemberExpr *E) {
5158 // Handle non-static data members.
5159 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005160 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005161 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005162 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005163 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005164 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005165 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005166 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005167 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005168 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005169 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005170 BaseTy = E->getBase()->getType();
5171 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005172 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005173 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005174 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005175 Result.setInvalid(E);
5176 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005177 }
Richard Smith027bf112011-11-17 22:56:20 +00005178
Richard Smith1b78b3d2012-01-25 22:15:11 +00005179 const ValueDecl *MD = E->getMemberDecl();
5180 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5181 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5182 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5183 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005184 if (!HandleLValueMember(this->Info, E, Result, FD))
5185 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005186 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005187 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5188 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005189 } else
5190 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005191
Richard Smith1b78b3d2012-01-25 22:15:11 +00005192 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005193 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005194 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005195 RefValue))
5196 return false;
5197 return Success(RefValue, E);
5198 }
5199 return true;
5200 }
5201
5202 bool VisitBinaryOperator(const BinaryOperator *E) {
5203 switch (E->getOpcode()) {
5204 default:
5205 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5206
5207 case BO_PtrMemD:
5208 case BO_PtrMemI:
5209 return HandleMemberPointerAccess(this->Info, E, Result);
5210 }
5211 }
5212
5213 bool VisitCastExpr(const CastExpr *E) {
5214 switch (E->getCastKind()) {
5215 default:
5216 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5217
5218 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005219 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005220 if (!this->Visit(E->getSubExpr()))
5221 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005222
5223 // Now figure out the necessary offset to add to the base LV to get from
5224 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005225 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5226 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005227 }
5228 }
5229};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005230}
Richard Smith027bf112011-11-17 22:56:20 +00005231
5232//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005233// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005234//
5235// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5236// function designators (in C), decl references to void objects (in C), and
5237// temporaries (if building with -Wno-address-of-temporary).
5238//
5239// LValue evaluation produces values comprising a base expression of one of the
5240// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005241// - Declarations
5242// * VarDecl
5243// * FunctionDecl
5244// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005245// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005246// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005247// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005248// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005249// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005250// * ObjCEncodeExpr
5251// * AddrLabelExpr
5252// * BlockExpr
5253// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005254// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005255// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005256// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005257// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5258// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005259// * A MaterializeTemporaryExpr that has static storage duration, with no
5260// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005261// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005262//===----------------------------------------------------------------------===//
5263namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005264class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005265 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005266public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005267 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5268 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005269
Richard Smith11562c52011-10-28 17:51:58 +00005270 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005271 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005272
Peter Collingbournee9200682011-05-13 03:29:01 +00005273 bool VisitDeclRefExpr(const DeclRefExpr *E);
5274 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005275 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005276 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5277 bool VisitMemberExpr(const MemberExpr *E);
5278 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5279 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005280 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005281 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005282 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5283 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005284 bool VisitUnaryReal(const UnaryOperator *E);
5285 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005286 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5287 return VisitUnaryPreIncDec(UO);
5288 }
5289 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5290 return VisitUnaryPreIncDec(UO);
5291 }
Richard Smith3229b742013-05-05 21:17:10 +00005292 bool VisitBinAssign(const BinaryOperator *BO);
5293 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005294
Peter Collingbournee9200682011-05-13 03:29:01 +00005295 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005296 switch (E->getCastKind()) {
5297 default:
Richard Smith027bf112011-11-17 22:56:20 +00005298 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005299
Eli Friedmance3e02a2011-10-11 00:13:24 +00005300 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005301 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005302 if (!Visit(E->getSubExpr()))
5303 return false;
5304 Result.Designator.setInvalid();
5305 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005306
Richard Smith027bf112011-11-17 22:56:20 +00005307 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005308 if (!Visit(E->getSubExpr()))
5309 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005310 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005311 }
5312 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005313};
5314} // end anonymous namespace
5315
Richard Smith11562c52011-10-28 17:51:58 +00005316/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005317/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005318/// * function designators in C, and
5319/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005320/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005321static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5322 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005323 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005324 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005325 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005326}
5327
Peter Collingbournee9200682011-05-13 03:29:01 +00005328bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005329 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005330 return Success(FD);
5331 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005332 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005333 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005334 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005335 return Error(E);
5336}
Richard Smith733237d2011-10-24 23:14:33 +00005337
Faisal Vali0528a312016-11-13 06:09:16 +00005338
Richard Smith11562c52011-10-28 17:51:58 +00005339bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005340
5341 // If we are within a lambda's call operator, check whether the 'VD' referred
5342 // to within 'E' actually represents a lambda-capture that maps to a
5343 // data-member/field within the closure object, and if so, evaluate to the
5344 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005345 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5346 isa<DeclRefExpr>(E) &&
5347 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5348 // We don't always have a complete capture-map when checking or inferring if
5349 // the function call operator meets the requirements of a constexpr function
5350 // - but we don't need to evaluate the captures to determine constexprness
5351 // (dcl.constexpr C++17).
5352 if (Info.checkingPotentialConstantExpression())
5353 return false;
5354
Faisal Vali051e3a22017-02-16 04:12:21 +00005355 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005356 // Start with 'Result' referring to the complete closure object...
5357 Result = *Info.CurrentCall->This;
5358 // ... then update it to refer to the field of the closure object
5359 // that represents the capture.
5360 if (!HandleLValueMember(Info, E, Result, FD))
5361 return false;
5362 // And if the field is of reference type, update 'Result' to refer to what
5363 // the field refers to.
5364 if (FD->getType()->isReferenceType()) {
5365 APValue RVal;
5366 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5367 RVal))
5368 return false;
5369 Result.setFrom(Info.Ctx, RVal);
5370 }
5371 return true;
5372 }
5373 }
Craig Topper36250ad2014-05-12 05:36:57 +00005374 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005375 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5376 // Only if a local variable was declared in the function currently being
5377 // evaluated, do we expect to be able to find its value in the current
5378 // frame. (Otherwise it was likely declared in an enclosing context and
5379 // could either have a valid evaluatable value (for e.g. a constexpr
5380 // variable) or be ill-formed (and trigger an appropriate evaluation
5381 // diagnostic)).
5382 if (Info.CurrentCall->Callee &&
5383 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5384 Frame = Info.CurrentCall;
5385 }
5386 }
Richard Smith3229b742013-05-05 21:17:10 +00005387
Richard Smithfec09922011-11-01 16:57:24 +00005388 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005389 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005390 Result.set({VD, Frame->Index,
5391 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005392 return true;
5393 }
Richard Smithce40ad62011-11-12 22:28:03 +00005394 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005395 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005396
Richard Smith3229b742013-05-05 21:17:10 +00005397 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005398 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005399 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005400 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005401 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005402 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005403 return false;
5404 }
Richard Smith3229b742013-05-05 21:17:10 +00005405 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005406}
5407
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005408bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5409 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005410 // Walk through the expression to find the materialized temporary itself.
5411 SmallVector<const Expr *, 2> CommaLHSs;
5412 SmallVector<SubobjectAdjustment, 2> Adjustments;
5413 const Expr *Inner = E->GetTemporaryExpr()->
5414 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005415
Richard Smith84401042013-06-03 05:03:02 +00005416 // If we passed any comma operators, evaluate their LHSs.
5417 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5418 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5419 return false;
5420
Richard Smithe6c01442013-06-05 00:46:14 +00005421 // A materialized temporary with static storage duration can appear within the
5422 // result of a constant expression evaluation, so we need to preserve its
5423 // value for use outside this evaluation.
5424 APValue *Value;
5425 if (E->getStorageDuration() == SD_Static) {
5426 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005427 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005428 Result.set(E);
5429 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005430 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5431 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005432 }
5433
Richard Smithea4ad5d2013-06-06 08:19:16 +00005434 QualType Type = Inner->getType();
5435
Richard Smith84401042013-06-03 05:03:02 +00005436 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005437 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5438 (E->getStorageDuration() == SD_Static &&
5439 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5440 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005441 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005442 }
Richard Smith84401042013-06-03 05:03:02 +00005443
5444 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005445 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5446 --I;
5447 switch (Adjustments[I].Kind) {
5448 case SubobjectAdjustment::DerivedToBaseAdjustment:
5449 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5450 Type, Result))
5451 return false;
5452 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5453 break;
5454
5455 case SubobjectAdjustment::FieldAdjustment:
5456 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5457 return false;
5458 Type = Adjustments[I].Field->getType();
5459 break;
5460
5461 case SubobjectAdjustment::MemberPointerAdjustment:
5462 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5463 Adjustments[I].Ptr.RHS))
5464 return false;
5465 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5466 break;
5467 }
5468 }
5469
5470 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005471}
5472
Peter Collingbournee9200682011-05-13 03:29:01 +00005473bool
5474LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005475 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5476 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005477 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5478 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005479 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005480}
5481
Richard Smith6e525142011-12-27 12:18:28 +00005482bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005483 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005484 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005485
Faisal Valie690b7a2016-07-02 22:34:24 +00005486 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005487 << E->getExprOperand()->getType()
5488 << E->getExprOperand()->getSourceRange();
5489 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005490}
5491
Francois Pichet0066db92012-04-16 04:08:35 +00005492bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5493 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005494}
Francois Pichet0066db92012-04-16 04:08:35 +00005495
Peter Collingbournee9200682011-05-13 03:29:01 +00005496bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005497 // Handle static data members.
5498 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005499 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005500 return VisitVarDecl(E, VD);
5501 }
5502
Richard Smith254a73d2011-10-28 22:34:42 +00005503 // Handle static member functions.
5504 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5505 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005506 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005507 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005508 }
5509 }
5510
Richard Smithd62306a2011-11-10 06:34:14 +00005511 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005512 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005513}
5514
Peter Collingbournee9200682011-05-13 03:29:01 +00005515bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005516 // FIXME: Deal with vectors as array subscript bases.
5517 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005518 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005519
Nick Lewyckyad888682017-04-27 07:27:36 +00005520 bool Success = true;
5521 if (!evaluatePointer(E->getBase(), Result)) {
5522 if (!Info.noteFailure())
5523 return false;
5524 Success = false;
5525 }
Mike Stump11289f42009-09-09 15:08:12 +00005526
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005527 APSInt Index;
5528 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005529 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005530
Nick Lewyckyad888682017-04-27 07:27:36 +00005531 return Success &&
5532 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005533}
Eli Friedman9a156e52008-11-12 09:44:48 +00005534
Peter Collingbournee9200682011-05-13 03:29:01 +00005535bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005536 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005537}
5538
Richard Smith66c96992012-02-18 22:04:06 +00005539bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5540 if (!Visit(E->getSubExpr()))
5541 return false;
5542 // __real is a no-op on scalar lvalues.
5543 if (E->getSubExpr()->getType()->isAnyComplexType())
5544 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5545 return true;
5546}
5547
5548bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5549 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5550 "lvalue __imag__ on scalar?");
5551 if (!Visit(E->getSubExpr()))
5552 return false;
5553 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5554 return true;
5555}
5556
Richard Smith243ef902013-05-05 23:31:59 +00005557bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005558 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005559 return Error(UO);
5560
5561 if (!this->Visit(UO->getSubExpr()))
5562 return false;
5563
Richard Smith243ef902013-05-05 23:31:59 +00005564 return handleIncDec(
5565 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005566 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005567}
5568
5569bool LValueExprEvaluator::VisitCompoundAssignOperator(
5570 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005571 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005572 return Error(CAO);
5573
Richard Smith3229b742013-05-05 21:17:10 +00005574 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005575
5576 // The overall lvalue result is the result of evaluating the LHS.
5577 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005578 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005579 Evaluate(RHS, this->Info, CAO->getRHS());
5580 return false;
5581 }
5582
Richard Smith3229b742013-05-05 21:17:10 +00005583 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5584 return false;
5585
Richard Smith43e77732013-05-07 04:50:00 +00005586 return handleCompoundAssignment(
5587 this->Info, CAO,
5588 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5589 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005590}
5591
5592bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005593 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005594 return Error(E);
5595
Richard Smith3229b742013-05-05 21:17:10 +00005596 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005597
5598 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005599 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005600 Evaluate(NewVal, this->Info, E->getRHS());
5601 return false;
5602 }
5603
Richard Smith3229b742013-05-05 21:17:10 +00005604 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5605 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005606
5607 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005608 NewVal);
5609}
5610
Eli Friedman9a156e52008-11-12 09:44:48 +00005611//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005612// Pointer Evaluation
5613//===----------------------------------------------------------------------===//
5614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005615/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005616/// returned by a function with the alloc_size attribute. Returns true if we
5617/// were successful. Places an unsigned number into `Result`.
5618///
5619/// This expects the given CallExpr to be a call to a function with an
5620/// alloc_size attribute.
5621static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5622 const CallExpr *Call,
5623 llvm::APInt &Result) {
5624 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5625
Joel E. Denny81508102018-03-13 14:51:22 +00005626 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5627 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005628 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5629 if (Call->getNumArgs() <= SizeArgNo)
5630 return false;
5631
5632 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005633 Expr::EvalResult ExprResult;
5634 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005635 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005636 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005637 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5638 return false;
5639 Into = Into.zextOrSelf(BitsInSizeT);
5640 return true;
5641 };
5642
5643 APSInt SizeOfElem;
5644 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5645 return false;
5646
Joel E. Denny81508102018-03-13 14:51:22 +00005647 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005648 Result = std::move(SizeOfElem);
5649 return true;
5650 }
5651
5652 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005653 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005654 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5655 return false;
5656
5657 bool Overflow;
5658 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5659 if (Overflow)
5660 return false;
5661
5662 Result = std::move(BytesAvailable);
5663 return true;
5664}
5665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005666/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005667/// function.
5668static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5669 const LValue &LVal,
5670 llvm::APInt &Result) {
5671 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5672 "Can't get the size of a non alloc_size function");
5673 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5674 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5675 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5676}
5677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005678/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005679/// a function with the alloc_size attribute. If it was possible to do so, this
5680/// function will return true, make Result's Base point to said function call,
5681/// and mark Result's Base as invalid.
5682static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5683 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005684 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005685 return false;
5686
5687 // Because we do no form of static analysis, we only support const variables.
5688 //
5689 // Additionally, we can't support parameters, nor can we support static
5690 // variables (in the latter case, use-before-assign isn't UB; in the former,
5691 // we have no clue what they'll be assigned to).
5692 const auto *VD =
5693 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5694 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5695 return false;
5696
5697 const Expr *Init = VD->getAnyInitializer();
5698 if (!Init)
5699 return false;
5700
5701 const Expr *E = Init->IgnoreParens();
5702 if (!tryUnwrapAllocSizeCall(E))
5703 return false;
5704
5705 // Store E instead of E unwrapped so that the type of the LValue's base is
5706 // what the user wanted.
5707 Result.setInvalid(E);
5708
5709 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005710 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005711 return true;
5712}
5713
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005714namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005715class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005716 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005717 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005718 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005719
Peter Collingbournee9200682011-05-13 03:29:01 +00005720 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005721 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005722 return true;
5723 }
George Burgess IVe3763372016-12-22 02:50:20 +00005724
George Burgess IVf9013bf2017-02-10 22:52:29 +00005725 bool evaluateLValue(const Expr *E, LValue &Result) {
5726 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5727 }
5728
5729 bool evaluatePointer(const Expr *E, LValue &Result) {
5730 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5731 }
5732
George Burgess IVe3763372016-12-22 02:50:20 +00005733 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005734public:
Mike Stump11289f42009-09-09 15:08:12 +00005735
George Burgess IVf9013bf2017-02-10 22:52:29 +00005736 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5737 : ExprEvaluatorBaseTy(info), Result(Result),
5738 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005739
Richard Smith2e312c82012-03-03 22:46:17 +00005740 bool Success(const APValue &V, const Expr *E) {
5741 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005742 return true;
5743 }
Richard Smithfddd3842011-12-30 21:15:51 +00005744 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005745 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5746 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005747 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005748 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005749
John McCall45d55e42010-05-07 21:00:08 +00005750 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005751 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005752 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005753 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005754 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005755 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5756 if (Info.noteFailure())
5757 EvaluateIgnoredValue(Info, E->getSubExpr());
5758 return Error(E);
5759 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005760 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005761 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005762 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005763 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005764 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005765 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005766 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005767 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005768 }
Richard Smithd62306a2011-11-10 06:34:14 +00005769 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005770 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005771 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005772 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005773 if (!Info.CurrentCall->This) {
5774 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005775 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005776 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005777 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005778 return false;
5779 }
Richard Smithd62306a2011-11-10 06:34:14 +00005780 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005781 // If we are inside a lambda's call operator, the 'this' expression refers
5782 // to the enclosing '*this' object (either by value or reference) which is
5783 // either copied into the closure object's field that represents the '*this'
5784 // or refers to '*this'.
5785 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5786 // Update 'Result' to refer to the data member/field of the closure object
5787 // that represents the '*this' capture.
5788 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005789 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005790 return false;
5791 // If we captured '*this' by reference, replace the field with its referent.
5792 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5793 ->isPointerType()) {
5794 APValue RVal;
5795 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5796 RVal))
5797 return false;
5798
5799 Result.setFrom(Info.Ctx, RVal);
5800 }
5801 }
Richard Smithd62306a2011-11-10 06:34:14 +00005802 return true;
5803 }
John McCallc07a0c72011-02-17 10:25:35 +00005804
Eli Friedman449fe542009-03-23 04:56:01 +00005805 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005806};
Chris Lattner05706e882008-07-11 18:11:29 +00005807} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005808
George Burgess IVf9013bf2017-02-10 22:52:29 +00005809static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5810 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005811 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005812 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005813}
5814
John McCall45d55e42010-05-07 21:00:08 +00005815bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005816 if (E->getOpcode() != BO_Add &&
5817 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005818 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005819
Chris Lattner05706e882008-07-11 18:11:29 +00005820 const Expr *PExp = E->getLHS();
5821 const Expr *IExp = E->getRHS();
5822 if (IExp->getType()->isPointerType())
5823 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005824
George Burgess IVf9013bf2017-02-10 22:52:29 +00005825 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005826 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005827 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005828
John McCall45d55e42010-05-07 21:00:08 +00005829 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005830 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005831 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005832
Richard Smith96e0c102011-11-04 02:25:55 +00005833 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005834 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005835
Ted Kremenek28831752012-08-23 20:46:57 +00005836 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005837 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005838}
Eli Friedman9a156e52008-11-12 09:44:48 +00005839
John McCall45d55e42010-05-07 21:00:08 +00005840bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005841 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005842}
Mike Stump11289f42009-09-09 15:08:12 +00005843
Richard Smith81dfef92018-07-11 00:29:05 +00005844bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5845 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005846
Eli Friedman847a2bc2009-12-27 05:43:15 +00005847 switch (E->getCastKind()) {
5848 default:
5849 break;
5850
John McCalle3027922010-08-25 11:45:40 +00005851 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005852 case CK_CPointerToObjCPointerCast:
5853 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005854 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005855 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005856 if (!Visit(SubExpr))
5857 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005858 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5859 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5860 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005861 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005862 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005863 if (SubExpr->getType()->isVoidPointerType())
5864 CCEDiag(E, diag::note_constexpr_invalid_cast)
5865 << 3 << SubExpr->getType();
5866 else
5867 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5868 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005869 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5870 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005871 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005872
Anders Carlsson18275092010-10-31 20:41:46 +00005873 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005874 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005875 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005876 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005877 if (!Result.Base && Result.Offset.isZero())
5878 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005879
Richard Smithd62306a2011-11-10 06:34:14 +00005880 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005881 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005882 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5883 castAs<PointerType>()->getPointeeType(),
5884 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005885
Richard Smith027bf112011-11-17 22:56:20 +00005886 case CK_BaseToDerived:
5887 if (!Visit(E->getSubExpr()))
5888 return false;
5889 if (!Result.Base && Result.Offset.isZero())
5890 return true;
5891 return HandleBaseToDerivedCast(Info, E, Result);
5892
Richard Smith0b0a0b62011-10-29 20:57:55 +00005893 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005894 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005895 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005896
John McCalle3027922010-08-25 11:45:40 +00005897 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005898 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5899
Richard Smith2e312c82012-03-03 22:46:17 +00005900 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005901 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005902 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005903
John McCall45d55e42010-05-07 21:00:08 +00005904 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005905 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5906 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005907 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005908 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005909 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005910 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005911 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005912 return true;
5913 } else {
5914 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005915 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005916 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005917 }
5918 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005919
5920 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005921 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005922 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005923 return false;
5924 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005925 APValue &Value = createTemporary(SubExpr, false, Result,
5926 *Info.CurrentCall);
5927 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005928 return false;
5929 }
Richard Smith96e0c102011-11-04 02:25:55 +00005930 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005931 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5932 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005933 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005934 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005935 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005936 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005937 }
Richard Smithdd785442011-10-31 20:57:44 +00005938
John McCalle3027922010-08-25 11:45:40 +00005939 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005940 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005941
5942 case CK_LValueToRValue: {
5943 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005944 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005945 return false;
5946
5947 APValue RVal;
5948 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5949 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5950 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005951 return InvalidBaseOK &&
5952 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005953 return Success(RVal, E);
5954 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005955 }
5956
Richard Smith11562c52011-10-28 17:51:58 +00005957 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005958}
Chris Lattner05706e882008-07-11 18:11:29 +00005959
Richard Smith6822bd72018-10-26 19:26:45 +00005960static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5961 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005962 // C++ [expr.alignof]p3:
5963 // When alignof is applied to a reference type, the result is the
5964 // alignment of the referenced type.
5965 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5966 T = Ref->getPointeeType();
5967
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005968 if (T.getQualifiers().hasUnaligned())
5969 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00005970
5971 const bool AlignOfReturnsPreferred =
5972 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
5973
5974 // __alignof is defined to return the preferred alignment.
5975 // Before 8, clang returned the preferred alignment for alignof and _Alignof
5976 // as well.
5977 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
5978 return Info.Ctx.toCharUnitsFromBits(
5979 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5980 // alignof and _Alignof are defined to return the ABI alignment.
5981 else if (ExprKind == UETT_AlignOf)
5982 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
5983 else
5984 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00005985}
5986
Richard Smith6822bd72018-10-26 19:26:45 +00005987static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
5988 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005989 E = E->IgnoreParens();
5990
5991 // The kinds of expressions that we have special-case logic here for
5992 // should be kept up to date with the special checks for those
5993 // expressions in Sema.
5994
5995 // alignof decl is always accepted, even if it doesn't make sense: we default
5996 // to 1 in those cases.
5997 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5998 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5999 /*RefAsPointee*/true);
6000
6001 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6002 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6003 /*RefAsPointee*/true);
6004
Richard Smith6822bd72018-10-26 19:26:45 +00006005 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006006}
6007
George Burgess IVe3763372016-12-22 02:50:20 +00006008// To be clear: this happily visits unsupported builtins. Better name welcomed.
6009bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6010 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6011 return true;
6012
George Burgess IVf9013bf2017-02-10 22:52:29 +00006013 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006014 return false;
6015
6016 Result.setInvalid(E);
6017 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006018 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006019 return true;
6020}
6021
Peter Collingbournee9200682011-05-13 03:29:01 +00006022bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006023 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006024 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006025
Richard Smith6328cbd2016-11-16 00:57:23 +00006026 if (unsigned BuiltinOp = E->getBuiltinCallee())
6027 return VisitBuiltinCallExpr(E, BuiltinOp);
6028
George Burgess IVe3763372016-12-22 02:50:20 +00006029 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006030}
6031
6032bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6033 unsigned BuiltinOp) {
6034 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006035 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006036 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006037 case Builtin::BI__builtin_assume_aligned: {
6038 // We need to be very careful here because: if the pointer does not have the
6039 // asserted alignment, then the behavior is undefined, and undefined
6040 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006041 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006042 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006043
Hal Finkel0dd05d42014-10-03 17:18:37 +00006044 LValue OffsetResult(Result);
6045 APSInt Alignment;
6046 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6047 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006048 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006049
6050 if (E->getNumArgs() > 2) {
6051 APSInt Offset;
6052 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6053 return false;
6054
Richard Smith642a2362017-01-30 23:30:26 +00006055 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006056 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6057 }
6058
6059 // If there is a base object, then it must have the correct alignment.
6060 if (OffsetResult.Base) {
6061 CharUnits BaseAlignment;
6062 if (const ValueDecl *VD =
6063 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6064 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6065 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006066 BaseAlignment = GetAlignOfExpr(
6067 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006068 }
6069
6070 if (BaseAlignment < Align) {
6071 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006072 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006073 CCEDiag(E->getArg(0),
6074 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006075 << (unsigned)BaseAlignment.getQuantity()
6076 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006077 return false;
6078 }
6079 }
6080
6081 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006082 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006083 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006084
Richard Smith642a2362017-01-30 23:30:26 +00006085 (OffsetResult.Base
6086 ? CCEDiag(E->getArg(0),
6087 diag::note_constexpr_baa_insufficient_alignment) << 1
6088 : CCEDiag(E->getArg(0),
6089 diag::note_constexpr_baa_value_insufficient_alignment))
6090 << (int)OffsetResult.Offset.getQuantity()
6091 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006092 return false;
6093 }
6094
6095 return true;
6096 }
Richard Smithe9507952016-11-12 01:39:56 +00006097
6098 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006099 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006100 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006101 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006102 if (Info.getLangOpts().CPlusPlus11)
6103 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6104 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006105 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006106 else
6107 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006108 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006109 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006110 case Builtin::BI__builtin_wcschr:
6111 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006112 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006113 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006114 if (!Visit(E->getArg(0)))
6115 return false;
6116 APSInt Desired;
6117 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6118 return false;
6119 uint64_t MaxLength = uint64_t(-1);
6120 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006121 BuiltinOp != Builtin::BIwcschr &&
6122 BuiltinOp != Builtin::BI__builtin_strchr &&
6123 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006124 APSInt N;
6125 if (!EvaluateInteger(E->getArg(2), N, Info))
6126 return false;
6127 MaxLength = N.getExtValue();
6128 }
6129
Richard Smith8110c9d2016-11-29 19:45:17 +00006130 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006131
Richard Smith8110c9d2016-11-29 19:45:17 +00006132 // Figure out what value we're actually looking for (after converting to
6133 // the corresponding unsigned type if necessary).
6134 uint64_t DesiredVal;
6135 bool StopAtNull = false;
6136 switch (BuiltinOp) {
6137 case Builtin::BIstrchr:
6138 case Builtin::BI__builtin_strchr:
6139 // strchr compares directly to the passed integer, and therefore
6140 // always fails if given an int that is not a char.
6141 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6142 E->getArg(1)->getType(),
6143 Desired),
6144 Desired))
6145 return ZeroInitialization(E);
6146 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006147 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006148 case Builtin::BImemchr:
6149 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006150 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006151 // memchr compares by converting both sides to unsigned char. That's also
6152 // correct for strchr if we get this far (to cope with plain char being
6153 // unsigned in the strchr case).
6154 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6155 break;
Richard Smithe9507952016-11-12 01:39:56 +00006156
Richard Smith8110c9d2016-11-29 19:45:17 +00006157 case Builtin::BIwcschr:
6158 case Builtin::BI__builtin_wcschr:
6159 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006160 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006161 case Builtin::BIwmemchr:
6162 case Builtin::BI__builtin_wmemchr:
6163 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6164 DesiredVal = Desired.getZExtValue();
6165 break;
6166 }
Richard Smithe9507952016-11-12 01:39:56 +00006167
6168 for (; MaxLength; --MaxLength) {
6169 APValue Char;
6170 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6171 !Char.isInt())
6172 return false;
6173 if (Char.getInt().getZExtValue() == DesiredVal)
6174 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006175 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006176 break;
6177 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6178 return false;
6179 }
6180 // Not found: return nullptr.
6181 return ZeroInitialization(E);
6182 }
6183
Richard Smith06f71b52018-08-04 00:57:17 +00006184 case Builtin::BImemcpy:
6185 case Builtin::BImemmove:
6186 case Builtin::BIwmemcpy:
6187 case Builtin::BIwmemmove:
6188 if (Info.getLangOpts().CPlusPlus11)
6189 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6190 << /*isConstexpr*/0 << /*isConstructor*/0
6191 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6192 else
6193 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6194 LLVM_FALLTHROUGH;
6195 case Builtin::BI__builtin_memcpy:
6196 case Builtin::BI__builtin_memmove:
6197 case Builtin::BI__builtin_wmemcpy:
6198 case Builtin::BI__builtin_wmemmove: {
6199 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6200 BuiltinOp == Builtin::BIwmemmove ||
6201 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6202 BuiltinOp == Builtin::BI__builtin_wmemmove;
6203 bool Move = BuiltinOp == Builtin::BImemmove ||
6204 BuiltinOp == Builtin::BIwmemmove ||
6205 BuiltinOp == Builtin::BI__builtin_memmove ||
6206 BuiltinOp == Builtin::BI__builtin_wmemmove;
6207
6208 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006209 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006210 return false;
6211 LValue Dest = Result;
6212
6213 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006214 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006215 return false;
6216
6217 APSInt N;
6218 if (!EvaluateInteger(E->getArg(2), N, Info))
6219 return false;
6220 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6221
6222 // If the size is zero, we treat this as always being a valid no-op.
6223 // (Even if one of the src and dest pointers is null.)
6224 if (!N)
6225 return true;
6226
Richard Smith128719c2018-09-13 22:47:33 +00006227 // Otherwise, if either of the operands is null, we can't proceed. Don't
6228 // try to determine the type of the copied objects, because there aren't
6229 // any.
6230 if (!Src.Base || !Dest.Base) {
6231 APValue Val;
6232 (!Src.Base ? Src : Dest).moveInto(Val);
6233 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6234 << Move << WChar << !!Src.Base
6235 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6236 return false;
6237 }
6238 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6239 return false;
6240
Richard Smith06f71b52018-08-04 00:57:17 +00006241 // We require that Src and Dest are both pointers to arrays of
6242 // trivially-copyable type. (For the wide version, the designator will be
6243 // invalid if the designated object is not a wchar_t.)
6244 QualType T = Dest.Designator.getType(Info.Ctx);
6245 QualType SrcT = Src.Designator.getType(Info.Ctx);
6246 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6247 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6248 return false;
6249 }
Petr Pavlued083f22018-10-04 09:25:44 +00006250 if (T->isIncompleteType()) {
6251 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6252 return false;
6253 }
Richard Smith06f71b52018-08-04 00:57:17 +00006254 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6255 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6256 return false;
6257 }
6258
6259 // Figure out how many T's we're copying.
6260 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6261 if (!WChar) {
6262 uint64_t Remainder;
6263 llvm::APInt OrigN = N;
6264 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6265 if (Remainder) {
6266 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6267 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6268 << (unsigned)TSize;
6269 return false;
6270 }
6271 }
6272
6273 // Check that the copying will remain within the arrays, just so that we
6274 // can give a more meaningful diagnostic. This implicitly also checks that
6275 // N fits into 64 bits.
6276 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6277 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6278 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6279 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6280 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6281 << N.toString(10, /*Signed*/false);
6282 return false;
6283 }
6284 uint64_t NElems = N.getZExtValue();
6285 uint64_t NBytes = NElems * TSize;
6286
6287 // Check for overlap.
6288 int Direction = 1;
6289 if (HasSameBase(Src, Dest)) {
6290 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6291 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6292 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6293 // Dest is inside the source region.
6294 if (!Move) {
6295 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6296 return false;
6297 }
6298 // For memmove and friends, copy backwards.
6299 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6300 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6301 return false;
6302 Direction = -1;
6303 } else if (!Move && SrcOffset >= DestOffset &&
6304 SrcOffset - DestOffset < NBytes) {
6305 // Src is inside the destination region for memcpy: invalid.
6306 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6307 return false;
6308 }
6309 }
6310
6311 while (true) {
6312 APValue Val;
6313 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6314 !handleAssignment(Info, E, Dest, T, Val))
6315 return false;
6316 // Do not iterate past the last element; if we're copying backwards, that
6317 // might take us off the start of the array.
6318 if (--NElems == 0)
6319 return true;
6320 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6321 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6322 return false;
6323 }
6324 }
6325
Richard Smith6cbd65d2013-07-11 02:27:57 +00006326 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006327 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006328 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006329}
Chris Lattner05706e882008-07-11 18:11:29 +00006330
6331//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006332// Member Pointer Evaluation
6333//===----------------------------------------------------------------------===//
6334
6335namespace {
6336class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006337 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006338 MemberPtr &Result;
6339
6340 bool Success(const ValueDecl *D) {
6341 Result = MemberPtr(D);
6342 return true;
6343 }
6344public:
6345
6346 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6347 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6348
Richard Smith2e312c82012-03-03 22:46:17 +00006349 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006350 Result.setFrom(V);
6351 return true;
6352 }
Richard Smithfddd3842011-12-30 21:15:51 +00006353 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006354 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006355 }
6356
6357 bool VisitCastExpr(const CastExpr *E);
6358 bool VisitUnaryAddrOf(const UnaryOperator *E);
6359};
6360} // end anonymous namespace
6361
6362static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6363 EvalInfo &Info) {
6364 assert(E->isRValue() && E->getType()->isMemberPointerType());
6365 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6366}
6367
6368bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6369 switch (E->getCastKind()) {
6370 default:
6371 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6372
6373 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006374 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006375 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006376
6377 case CK_BaseToDerivedMemberPointer: {
6378 if (!Visit(E->getSubExpr()))
6379 return false;
6380 if (E->path_empty())
6381 return true;
6382 // Base-to-derived member pointer casts store the path in derived-to-base
6383 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6384 // the wrong end of the derived->base arc, so stagger the path by one class.
6385 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6386 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6387 PathI != PathE; ++PathI) {
6388 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6389 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6390 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006391 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006392 }
6393 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6394 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006395 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006396 return true;
6397 }
6398
6399 case CK_DerivedToBaseMemberPointer:
6400 if (!Visit(E->getSubExpr()))
6401 return false;
6402 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6403 PathE = E->path_end(); PathI != PathE; ++PathI) {
6404 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6405 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6406 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006407 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006408 }
6409 return true;
6410 }
6411}
6412
6413bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6414 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6415 // member can be formed.
6416 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6417}
6418
6419//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006420// Record Evaluation
6421//===----------------------------------------------------------------------===//
6422
6423namespace {
6424 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006425 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006426 const LValue &This;
6427 APValue &Result;
6428 public:
6429
6430 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6431 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6432
Richard Smith2e312c82012-03-03 22:46:17 +00006433 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006434 Result = V;
6435 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006436 }
Richard Smithb8348f52016-05-12 22:16:28 +00006437 bool ZeroInitialization(const Expr *E) {
6438 return ZeroInitialization(E, E->getType());
6439 }
6440 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006441
Richard Smith52a980a2015-08-28 02:43:42 +00006442 bool VisitCallExpr(const CallExpr *E) {
6443 return handleCallExpr(E, Result, &This);
6444 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006445 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006446 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006447 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6448 return VisitCXXConstructExpr(E, E->getType());
6449 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006450 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006451 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006452 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006453 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006454
6455 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006456 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006457}
Richard Smithd62306a2011-11-10 06:34:14 +00006458
Richard Smithfddd3842011-12-30 21:15:51 +00006459/// Perform zero-initialization on an object of non-union class type.
6460/// C++11 [dcl.init]p5:
6461/// To zero-initialize an object or reference of type T means:
6462/// [...]
6463/// -- if T is a (possibly cv-qualified) non-union class type,
6464/// each non-static data member and each base-class subobject is
6465/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006466static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6467 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006468 const LValue &This, APValue &Result) {
6469 assert(!RD->isUnion() && "Expected non-union class type");
6470 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6471 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006472 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006473
John McCalld7bca762012-05-01 00:38:49 +00006474 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006475 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6476
6477 if (CD) {
6478 unsigned Index = 0;
6479 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006480 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006481 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6482 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006483 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6484 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006485 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006486 Result.getStructBase(Index)))
6487 return false;
6488 }
6489 }
6490
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006491 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006492 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006493 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006494 continue;
6495
6496 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006497 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006498 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006499
David Blaikie2d7c57e2012-04-30 02:36:29 +00006500 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006501 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006502 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006503 return false;
6504 }
6505
6506 return true;
6507}
6508
Richard Smithb8348f52016-05-12 22:16:28 +00006509bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6510 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006511 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006512 if (RD->isUnion()) {
6513 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6514 // object's first non-static named data member is zero-initialized
6515 RecordDecl::field_iterator I = RD->field_begin();
6516 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006517 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006518 return true;
6519 }
6520
6521 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006522 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006523 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006524 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006525 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006526 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006527 }
6528
Richard Smith5d108602012-02-17 00:44:16 +00006529 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006530 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006531 return false;
6532 }
6533
Richard Smitha8105bc2012-01-06 16:39:00 +00006534 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006535}
6536
Richard Smithe97cbd72011-11-11 04:05:33 +00006537bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6538 switch (E->getCastKind()) {
6539 default:
6540 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6541
6542 case CK_ConstructorConversion:
6543 return Visit(E->getSubExpr());
6544
6545 case CK_DerivedToBase:
6546 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006547 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006548 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006549 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006550 if (!DerivedObject.isStruct())
6551 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006552
6553 // Derived-to-base rvalue conversion: just slice off the derived part.
6554 APValue *Value = &DerivedObject;
6555 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6556 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6557 PathE = E->path_end(); PathI != PathE; ++PathI) {
6558 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6559 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6560 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6561 RD = Base;
6562 }
6563 Result = *Value;
6564 return true;
6565 }
6566 }
6567}
6568
Richard Smithd62306a2011-11-10 06:34:14 +00006569bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006570 if (E->isTransparent())
6571 return Visit(E->getInit(0));
6572
Richard Smithd62306a2011-11-10 06:34:14 +00006573 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006574 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006575 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6576
6577 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006578 const FieldDecl *Field = E->getInitializedFieldInUnion();
6579 Result = APValue(Field);
6580 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006581 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006582
6583 // If the initializer list for a union does not contain any elements, the
6584 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006585 // FIXME: The element should be initialized from an initializer list.
6586 // Is this difference ever observable for initializer lists which
6587 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006588 ImplicitValueInitExpr VIE(Field->getType());
6589 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6590
Richard Smithd62306a2011-11-10 06:34:14 +00006591 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006592 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6593 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006594
6595 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6596 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6597 isa<CXXDefaultInitExpr>(InitExpr));
6598
Richard Smithb228a862012-02-15 02:18:13 +00006599 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006600 }
6601
Richard Smith872307e2016-03-08 22:17:41 +00006602 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006603 if (Result.isUninit())
6604 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6605 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006606 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006607 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006608
6609 // Initialize base classes.
6610 if (CXXRD) {
6611 for (const auto &Base : CXXRD->bases()) {
6612 assert(ElementNo < E->getNumInits() && "missing init for base class");
6613 const Expr *Init = E->getInit(ElementNo);
6614
6615 LValue Subobject = This;
6616 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6617 return false;
6618
6619 APValue &FieldVal = Result.getStructBase(ElementNo);
6620 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006621 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006622 return false;
6623 Success = false;
6624 }
6625 ++ElementNo;
6626 }
6627 }
6628
6629 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006630 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006631 // Anonymous bit-fields are not considered members of the class for
6632 // purposes of aggregate initialization.
6633 if (Field->isUnnamedBitfield())
6634 continue;
6635
6636 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006637
Richard Smith253c2a32012-01-27 01:14:48 +00006638 bool HaveInit = ElementNo < E->getNumInits();
6639
6640 // FIXME: Diagnostics here should point to the end of the initializer
6641 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006642 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006643 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006644 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006645
6646 // Perform an implicit value-initialization for members beyond the end of
6647 // the initializer list.
6648 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006649 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006650
Richard Smith852c9db2013-04-20 22:23:05 +00006651 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6652 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6653 isa<CXXDefaultInitExpr>(Init));
6654
Richard Smith49ca8aa2013-08-06 07:09:20 +00006655 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6656 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6657 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006658 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006659 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006660 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006661 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006662 }
6663 }
6664
Richard Smith253c2a32012-01-27 01:14:48 +00006665 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006666}
6667
Richard Smithb8348f52016-05-12 22:16:28 +00006668bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6669 QualType T) {
6670 // Note that E's type is not necessarily the type of our class here; we might
6671 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006672 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006673 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6674
Richard Smithfddd3842011-12-30 21:15:51 +00006675 bool ZeroInit = E->requiresZeroInitialization();
6676 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006677 // If we've already performed zero-initialization, we're already done.
6678 if (!Result.isUninit())
6679 return true;
6680
Richard Smithda3f4fd2014-03-05 23:32:50 +00006681 // We can get here in two different ways:
6682 // 1) We're performing value-initialization, and should zero-initialize
6683 // the object, or
6684 // 2) We're performing default-initialization of an object with a trivial
6685 // constexpr default constructor, in which case we should start the
6686 // lifetimes of all the base subobjects (there can be no data member
6687 // subobjects in this case) per [basic.life]p1.
6688 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006689 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006690 }
6691
Craig Topper36250ad2014-05-12 05:36:57 +00006692 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006693 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006694
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006695 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006696 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006697
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006698 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006699 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006700 if (const MaterializeTemporaryExpr *ME
6701 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6702 return Visit(ME->GetTemporaryExpr());
6703
Richard Smithb8348f52016-05-12 22:16:28 +00006704 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006705 return false;
6706
Craig Topper5fc8fc22014-08-27 06:28:36 +00006707 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006708 return HandleConstructorCall(E, This, Args,
6709 cast<CXXConstructorDecl>(Definition), Info,
6710 Result);
6711}
6712
6713bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6714 const CXXInheritedCtorInitExpr *E) {
6715 if (!Info.CurrentCall) {
6716 assert(Info.checkingPotentialConstantExpression());
6717 return false;
6718 }
6719
6720 const CXXConstructorDecl *FD = E->getConstructor();
6721 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6722 return false;
6723
6724 const FunctionDecl *Definition = nullptr;
6725 auto Body = FD->getBody(Definition);
6726
6727 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6728 return false;
6729
6730 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006731 cast<CXXConstructorDecl>(Definition), Info,
6732 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006733}
6734
Richard Smithcc1b96d2013-06-12 22:31:48 +00006735bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6736 const CXXStdInitializerListExpr *E) {
6737 const ConstantArrayType *ArrayType =
6738 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6739
6740 LValue Array;
6741 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6742 return false;
6743
6744 // Get a pointer to the first element of the array.
6745 Array.addArray(Info, E, ArrayType);
6746
6747 // FIXME: Perform the checks on the field types in SemaInit.
6748 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6749 RecordDecl::field_iterator Field = Record->field_begin();
6750 if (Field == Record->field_end())
6751 return Error(E);
6752
6753 // Start pointer.
6754 if (!Field->getType()->isPointerType() ||
6755 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6756 ArrayType->getElementType()))
6757 return Error(E);
6758
6759 // FIXME: What if the initializer_list type has base classes, etc?
6760 Result = APValue(APValue::UninitStruct(), 0, 2);
6761 Array.moveInto(Result.getStructField(0));
6762
6763 if (++Field == Record->field_end())
6764 return Error(E);
6765
6766 if (Field->getType()->isPointerType() &&
6767 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6768 ArrayType->getElementType())) {
6769 // End pointer.
6770 if (!HandleLValueArrayAdjustment(Info, E, Array,
6771 ArrayType->getElementType(),
6772 ArrayType->getSize().getZExtValue()))
6773 return false;
6774 Array.moveInto(Result.getStructField(1));
6775 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6776 // Length.
6777 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6778 else
6779 return Error(E);
6780
6781 if (++Field != Record->field_end())
6782 return Error(E);
6783
6784 return true;
6785}
6786
Faisal Valic72a08c2017-01-09 03:02:53 +00006787bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6788 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6789 if (ClosureClass->isInvalidDecl()) return false;
6790
6791 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006792
Faisal Vali051e3a22017-02-16 04:12:21 +00006793 const size_t NumFields =
6794 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006795
6796 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6797 E->capture_init_end()) &&
6798 "The number of lambda capture initializers should equal the number of "
6799 "fields within the closure type");
6800
Faisal Vali051e3a22017-02-16 04:12:21 +00006801 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6802 // Iterate through all the lambda's closure object's fields and initialize
6803 // them.
6804 auto *CaptureInitIt = E->capture_init_begin();
6805 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6806 bool Success = true;
6807 for (const auto *Field : ClosureClass->fields()) {
6808 assert(CaptureInitIt != E->capture_init_end());
6809 // Get the initializer for this field
6810 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006811
Faisal Vali051e3a22017-02-16 04:12:21 +00006812 // If there is no initializer, either this is a VLA or an error has
6813 // occurred.
6814 if (!CurFieldInit)
6815 return Error(E);
6816
6817 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6818 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6819 if (!Info.keepEvaluatingAfterFailure())
6820 return false;
6821 Success = false;
6822 }
6823 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006824 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006825 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006826}
6827
Richard Smithd62306a2011-11-10 06:34:14 +00006828static bool EvaluateRecord(const Expr *E, const LValue &This,
6829 APValue &Result, EvalInfo &Info) {
6830 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006831 "can't evaluate expression as a record rvalue");
6832 return RecordExprEvaluator(Info, This, Result).Visit(E);
6833}
6834
6835//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006836// Temporary Evaluation
6837//
6838// Temporaries are represented in the AST as rvalues, but generally behave like
6839// lvalues. The full-object of which the temporary is a subobject is implicitly
6840// materialized so that a reference can bind to it.
6841//===----------------------------------------------------------------------===//
6842namespace {
6843class TemporaryExprEvaluator
6844 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6845public:
6846 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006847 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006848
6849 /// Visit an expression which constructs the value of this temporary.
6850 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006851 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6852 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006853 }
6854
6855 bool VisitCastExpr(const CastExpr *E) {
6856 switch (E->getCastKind()) {
6857 default:
6858 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6859
6860 case CK_ConstructorConversion:
6861 return VisitConstructExpr(E->getSubExpr());
6862 }
6863 }
6864 bool VisitInitListExpr(const InitListExpr *E) {
6865 return VisitConstructExpr(E);
6866 }
6867 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6868 return VisitConstructExpr(E);
6869 }
6870 bool VisitCallExpr(const CallExpr *E) {
6871 return VisitConstructExpr(E);
6872 }
Richard Smith513955c2014-12-17 19:24:30 +00006873 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6874 return VisitConstructExpr(E);
6875 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006876 bool VisitLambdaExpr(const LambdaExpr *E) {
6877 return VisitConstructExpr(E);
6878 }
Richard Smith027bf112011-11-17 22:56:20 +00006879};
6880} // end anonymous namespace
6881
6882/// Evaluate an expression of record type as a temporary.
6883static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006884 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006885 return TemporaryExprEvaluator(Info, Result).Visit(E);
6886}
6887
6888//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006889// Vector Evaluation
6890//===----------------------------------------------------------------------===//
6891
6892namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006893 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006894 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006895 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006896 public:
Mike Stump11289f42009-09-09 15:08:12 +00006897
Richard Smith2d406342011-10-22 21:10:00 +00006898 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6899 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006900
Craig Topper9798b932015-09-29 04:30:05 +00006901 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006902 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6903 // FIXME: remove this APValue copy.
6904 Result = APValue(V.data(), V.size());
6905 return true;
6906 }
Richard Smith2e312c82012-03-03 22:46:17 +00006907 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006908 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006909 Result = V;
6910 return true;
6911 }
Richard Smithfddd3842011-12-30 21:15:51 +00006912 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006913
Richard Smith2d406342011-10-22 21:10:00 +00006914 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006915 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006916 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006917 bool VisitInitListExpr(const InitListExpr *E);
6918 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006919 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006920 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006921 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006922 };
6923} // end anonymous namespace
6924
6925static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006926 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006927 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006928}
6929
George Burgess IV533ff002015-12-11 00:23:35 +00006930bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006931 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006932 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006933
Richard Smith161f09a2011-12-06 22:44:34 +00006934 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006935 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006936
Eli Friedmanc757de22011-03-25 00:43:55 +00006937 switch (E->getCastKind()) {
6938 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006939 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006940 if (SETy->isIntegerType()) {
6941 APSInt IntResult;
6942 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006943 return false;
6944 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006945 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006946 APFloat FloatResult(0.0);
6947 if (!EvaluateFloat(SE, FloatResult, Info))
6948 return false;
6949 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006950 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006951 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006952 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006953
6954 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006955 SmallVector<APValue, 4> Elts(NElts, Val);
6956 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006957 }
Eli Friedman803acb32011-12-22 03:51:45 +00006958 case CK_BitCast: {
6959 // Evaluate the operand into an APInt we can extract from.
6960 llvm::APInt SValInt;
6961 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6962 return false;
6963 // Extract the elements
6964 QualType EltTy = VTy->getElementType();
6965 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6966 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6967 SmallVector<APValue, 4> Elts;
6968 if (EltTy->isRealFloatingType()) {
6969 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006970 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006971 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006972 FloatEltSize = 80;
6973 for (unsigned i = 0; i < NElts; i++) {
6974 llvm::APInt Elt;
6975 if (BigEndian)
6976 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6977 else
6978 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006979 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006980 }
6981 } else if (EltTy->isIntegerType()) {
6982 for (unsigned i = 0; i < NElts; i++) {
6983 llvm::APInt Elt;
6984 if (BigEndian)
6985 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6986 else
6987 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6988 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6989 }
6990 } else {
6991 return Error(E);
6992 }
6993 return Success(Elts, E);
6994 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006995 default:
Richard Smith11562c52011-10-28 17:51:58 +00006996 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006997 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006998}
6999
Richard Smith2d406342011-10-22 21:10:00 +00007000bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007001VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007002 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007003 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007004 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007005
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007006 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007007 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007008
Eli Friedmanb9c71292012-01-03 23:24:20 +00007009 // The number of initializers can be less than the number of
7010 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007011 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007012 // should be initialized with zeroes.
7013 unsigned CountInits = 0, CountElts = 0;
7014 while (CountElts < NumElements) {
7015 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007016 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007017 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007018 APValue v;
7019 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7020 return Error(E);
7021 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007022 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007023 Elements.push_back(v.getVectorElt(j));
7024 CountElts += vlen;
7025 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007026 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007027 if (CountInits < NumInits) {
7028 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007029 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007030 } else // trailing integer zero.
7031 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7032 Elements.push_back(APValue(sInt));
7033 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007034 } else {
7035 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007036 if (CountInits < NumInits) {
7037 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007038 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007039 } else // trailing float zero.
7040 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7041 Elements.push_back(APValue(f));
7042 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007043 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007044 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007045 }
Richard Smith2d406342011-10-22 21:10:00 +00007046 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007047}
7048
Richard Smith2d406342011-10-22 21:10:00 +00007049bool
Richard Smithfddd3842011-12-30 21:15:51 +00007050VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007051 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007052 QualType EltTy = VT->getElementType();
7053 APValue ZeroElement;
7054 if (EltTy->isIntegerType())
7055 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7056 else
7057 ZeroElement =
7058 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7059
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007060 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007061 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007062}
7063
Richard Smith2d406342011-10-22 21:10:00 +00007064bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007065 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007066 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007067}
7068
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007069//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007070// Array Evaluation
7071//===----------------------------------------------------------------------===//
7072
7073namespace {
7074 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007075 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007076 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007077 APValue &Result;
7078 public:
7079
Richard Smithd62306a2011-11-10 06:34:14 +00007080 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7081 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007082
7083 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007084 assert((V.isArray() || V.isLValue()) &&
7085 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007086 Result = V;
7087 return true;
7088 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007089
Richard Smithfddd3842011-12-30 21:15:51 +00007090 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007091 const ConstantArrayType *CAT =
7092 Info.Ctx.getAsConstantArrayType(E->getType());
7093 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007094 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007095
7096 Result = APValue(APValue::UninitArray(), 0,
7097 CAT->getSize().getZExtValue());
7098 if (!Result.hasArrayFiller()) return true;
7099
Richard Smithfddd3842011-12-30 21:15:51 +00007100 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007101 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007102 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007103 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007104 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007105 }
7106
Richard Smith52a980a2015-08-28 02:43:42 +00007107 bool VisitCallExpr(const CallExpr *E) {
7108 return handleCallExpr(E, Result, &This);
7109 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007110 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007111 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007112 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007113 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7114 const LValue &Subobject,
7115 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007116 };
7117} // end anonymous namespace
7118
Richard Smithd62306a2011-11-10 06:34:14 +00007119static bool EvaluateArray(const Expr *E, const LValue &This,
7120 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007121 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007122 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007123}
7124
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007125// Return true iff the given array filler may depend on the element index.
7126static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7127 // For now, just whitelist non-class value-initialization and initialization
7128 // lists comprised of them.
7129 if (isa<ImplicitValueInitExpr>(FillerExpr))
7130 return false;
7131 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7132 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7133 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7134 return true;
7135 }
7136 return false;
7137 }
7138 return true;
7139}
7140
Richard Smithf3e9e432011-11-07 09:22:26 +00007141bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7142 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7143 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007144 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007145
Richard Smithca2cfbf2011-12-22 01:07:19 +00007146 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7147 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007148 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007149 LValue LV;
7150 if (!EvaluateLValue(E->getInit(0), LV, Info))
7151 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007152 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007153 LV.moveInto(Val);
7154 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007155 }
7156
Richard Smith253c2a32012-01-27 01:14:48 +00007157 bool Success = true;
7158
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007159 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7160 "zero-initialized array shouldn't have any initialized elts");
7161 APValue Filler;
7162 if (Result.isArray() && Result.hasArrayFiller())
7163 Filler = Result.getArrayFiller();
7164
Richard Smith9543c5e2013-04-22 14:44:29 +00007165 unsigned NumEltsToInit = E->getNumInits();
7166 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007167 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007168
7169 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007170 // array element.
7171 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007172 NumEltsToInit = NumElts;
7173
Nicola Zaghen3538b392018-05-15 13:30:56 +00007174 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7175 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007176
Richard Smith9543c5e2013-04-22 14:44:29 +00007177 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007178
7179 // If the array was previously zero-initialized, preserve the
7180 // zero-initialized values.
7181 if (!Filler.isUninit()) {
7182 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7183 Result.getArrayInitializedElt(I) = Filler;
7184 if (Result.hasArrayFiller())
7185 Result.getArrayFiller() = Filler;
7186 }
7187
Richard Smithd62306a2011-11-10 06:34:14 +00007188 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007189 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007190 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7191 const Expr *Init =
7192 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007193 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007194 Info, Subobject, Init) ||
7195 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007196 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007197 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007198 return false;
7199 Success = false;
7200 }
Richard Smithd62306a2011-11-10 06:34:14 +00007201 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007202
Richard Smith9543c5e2013-04-22 14:44:29 +00007203 if (!Result.hasArrayFiller())
7204 return Success;
7205
7206 // If we get here, we have a trivial filler, which we can just evaluate
7207 // once and splat over the rest of the array elements.
7208 assert(FillerExpr && "no array filler for incomplete init list");
7209 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7210 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007211}
7212
Richard Smith410306b2016-12-12 02:53:20 +00007213bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7214 if (E->getCommonExpr() &&
7215 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7216 Info, E->getCommonExpr()->getSourceExpr()))
7217 return false;
7218
7219 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7220
7221 uint64_t Elements = CAT->getSize().getZExtValue();
7222 Result = APValue(APValue::UninitArray(), Elements, Elements);
7223
7224 LValue Subobject = This;
7225 Subobject.addArray(Info, E, CAT);
7226
7227 bool Success = true;
7228 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7229 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7230 Info, Subobject, E->getSubExpr()) ||
7231 !HandleLValueArrayAdjustment(Info, E, Subobject,
7232 CAT->getElementType(), 1)) {
7233 if (!Info.noteFailure())
7234 return false;
7235 Success = false;
7236 }
7237 }
7238
7239 return Success;
7240}
7241
Richard Smith027bf112011-11-17 22:56:20 +00007242bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007243 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7244}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007245
Richard Smith9543c5e2013-04-22 14:44:29 +00007246bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7247 const LValue &Subobject,
7248 APValue *Value,
7249 QualType Type) {
7250 bool HadZeroInit = !Value->isUninit();
7251
7252 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7253 unsigned N = CAT->getSize().getZExtValue();
7254
7255 // Preserve the array filler if we had prior zero-initialization.
7256 APValue Filler =
7257 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7258 : APValue();
7259
7260 *Value = APValue(APValue::UninitArray(), N, N);
7261
7262 if (HadZeroInit)
7263 for (unsigned I = 0; I != N; ++I)
7264 Value->getArrayInitializedElt(I) = Filler;
7265
7266 // Initialize the elements.
7267 LValue ArrayElt = Subobject;
7268 ArrayElt.addArray(Info, E, CAT);
7269 for (unsigned I = 0; I != N; ++I)
7270 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7271 CAT->getElementType()) ||
7272 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7273 CAT->getElementType(), 1))
7274 return false;
7275
7276 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007277 }
Richard Smith027bf112011-11-17 22:56:20 +00007278
Richard Smith9543c5e2013-04-22 14:44:29 +00007279 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007280 return Error(E);
7281
Richard Smithb8348f52016-05-12 22:16:28 +00007282 return RecordExprEvaluator(Info, Subobject, *Value)
7283 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007284}
7285
Richard Smithf3e9e432011-11-07 09:22:26 +00007286//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007287// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007288//
7289// As a GNU extension, we support casting pointers to sufficiently-wide integer
7290// types and back in constant folding. Integer values are thus represented
7291// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007292//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007293
7294namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007295class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007296 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007297 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007298public:
Richard Smith2e312c82012-03-03 22:46:17 +00007299 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007300 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007301
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007302 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007303 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007304 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007305 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007306 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007307 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007308 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007309 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007310 return true;
7311 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007312 bool Success(const llvm::APSInt &SI, const Expr *E) {
7313 return Success(SI, E, Result);
7314 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007316 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007317 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007318 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007319 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007320 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007321 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007322 Result.getInt().setIsUnsigned(
7323 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007324 return true;
7325 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007326 bool Success(const llvm::APInt &I, const Expr *E) {
7327 return Success(I, E, Result);
7328 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007329
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007330 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007331 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007332 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007333 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007334 return true;
7335 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007336 bool Success(uint64_t Value, const Expr *E) {
7337 return Success(Value, E, Result);
7338 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007339
Ken Dyckdbc01912011-03-11 02:13:43 +00007340 bool Success(CharUnits Size, const Expr *E) {
7341 return Success(Size.getQuantity(), E);
7342 }
7343
Richard Smith2e312c82012-03-03 22:46:17 +00007344 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007345 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007346 Result = V;
7347 return true;
7348 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007349 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007350 }
Mike Stump11289f42009-09-09 15:08:12 +00007351
Richard Smithfddd3842011-12-30 21:15:51 +00007352 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007353
Peter Collingbournee9200682011-05-13 03:29:01 +00007354 //===--------------------------------------------------------------------===//
7355 // Visitor Methods
7356 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007357
Fangrui Song407659a2018-11-30 23:41:18 +00007358 bool VisitConstantExpr(const ConstantExpr *E);
7359
Chris Lattner7174bf32008-07-12 00:38:25 +00007360 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007361 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007362 }
7363 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007364 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007365 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007366
7367 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7368 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007369 if (CheckReferencedDecl(E, E->getDecl()))
7370 return true;
7371
7372 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007373 }
7374 bool VisitMemberExpr(const MemberExpr *E) {
7375 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007376 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007377 return true;
7378 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007379
7380 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007381 }
7382
Peter Collingbournee9200682011-05-13 03:29:01 +00007383 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007384 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007385 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007386 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007387 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007388
Peter Collingbournee9200682011-05-13 03:29:01 +00007389 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007390 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007391
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007392 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007393 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007394 }
Mike Stump11289f42009-09-09 15:08:12 +00007395
Ted Kremeneke65b0862012-03-06 20:05:56 +00007396 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7397 return Success(E->getValue(), E);
7398 }
Richard Smith410306b2016-12-12 02:53:20 +00007399
7400 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7401 if (Info.ArrayInitIndex == uint64_t(-1)) {
7402 // We were asked to evaluate this subexpression independent of the
7403 // enclosing ArrayInitLoopExpr. We can't do that.
7404 Info.FFDiag(E);
7405 return false;
7406 }
7407 return Success(Info.ArrayInitIndex, E);
7408 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007409
Richard Smith4ce706a2011-10-11 21:43:33 +00007410 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007411 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007412 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007413 }
7414
Douglas Gregor29c42f22012-02-24 07:38:34 +00007415 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7416 return Success(E->getValue(), E);
7417 }
7418
John Wiegley6242b6a2011-04-28 00:16:57 +00007419 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7420 return Success(E->getValue(), E);
7421 }
7422
John Wiegleyf9f65842011-04-25 06:54:41 +00007423 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7424 return Success(E->getValue(), E);
7425 }
7426
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007427 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007428 bool VisitUnaryImag(const UnaryOperator *E);
7429
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007430 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007431 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007432
Eli Friedman4e7a2412009-02-27 04:45:43 +00007433 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007434};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007435
7436class FixedPointExprEvaluator
7437 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7438 APValue &Result;
7439
7440 public:
7441 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7442 : ExprEvaluatorBaseTy(info), Result(result) {}
7443
7444 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7445 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7446 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7447 "Invalid evaluation result.");
7448 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7449 "Invalid evaluation result.");
7450 Result = APValue(SI);
7451 return true;
7452 }
7453 bool Success(const llvm::APSInt &SI, const Expr *E) {
7454 return Success(SI, E, Result);
7455 }
7456
7457 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7458 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7459 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7460 "Invalid evaluation result.");
7461 Result = APValue(APSInt(I));
7462 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7463 return true;
7464 }
7465 bool Success(const llvm::APInt &I, const Expr *E) {
7466 return Success(I, E, Result);
7467 }
7468
7469 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7470 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7471 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7472 return true;
7473 }
7474 bool Success(uint64_t Value, const Expr *E) {
7475 return Success(Value, E, Result);
7476 }
7477
7478 bool Success(CharUnits Size, const Expr *E) {
7479 return Success(Size.getQuantity(), E);
7480 }
7481
7482 bool Success(const APValue &V, const Expr *E) {
7483 if (V.isLValue() || V.isAddrLabelDiff()) {
7484 Result = V;
7485 return true;
7486 }
7487 return Success(V.getInt(), E);
7488 }
7489
7490 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7491
7492 //===--------------------------------------------------------------------===//
7493 // Visitor Methods
7494 //===--------------------------------------------------------------------===//
7495
7496 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7497 return Success(E->getValue(), E);
7498 }
7499
7500 bool VisitUnaryOperator(const UnaryOperator *E);
7501};
Chris Lattner05706e882008-07-11 18:11:29 +00007502} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007503
Richard Smith11562c52011-10-28 17:51:58 +00007504/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7505/// produce either the integer value or a pointer.
7506///
7507/// GCC has a heinous extension which folds casts between pointer types and
7508/// pointer-sized integral types. We support this by allowing the evaluation of
7509/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7510/// Some simple arithmetic on such values is supported (they are treated much
7511/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007512static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007513 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007514 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007515 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007516}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007517
Richard Smithf57d8cb2011-12-09 22:58:01 +00007518static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007519 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007520 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007521 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007522 if (!Val.isInt()) {
7523 // FIXME: It would be better to produce the diagnostic for casting
7524 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007525 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007526 return false;
7527 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007528 Result = Val.getInt();
7529 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007530}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007531
Richard Smithf57d8cb2011-12-09 22:58:01 +00007532/// Check whether the given declaration can be directly converted to an integral
7533/// rvalue. If not, no diagnostic is produced; there are other things we can
7534/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007535bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007536 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007537 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007538 // Check for signedness/width mismatches between E type and ECD value.
7539 bool SameSign = (ECD->getInitVal().isSigned()
7540 == E->getType()->isSignedIntegerOrEnumerationType());
7541 bool SameWidth = (ECD->getInitVal().getBitWidth()
7542 == Info.Ctx.getIntWidth(E->getType()));
7543 if (SameSign && SameWidth)
7544 return Success(ECD->getInitVal(), E);
7545 else {
7546 // Get rid of mismatch (otherwise Success assertions will fail)
7547 // by computing a new value matching the type of E.
7548 llvm::APSInt Val = ECD->getInitVal();
7549 if (!SameSign)
7550 Val.setIsSigned(!ECD->getInitVal().isSigned());
7551 if (!SameWidth)
7552 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7553 return Success(Val, E);
7554 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007555 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007556 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007557}
7558
Richard Smith08b682b2018-05-23 21:18:00 +00007559/// Values returned by __builtin_classify_type, chosen to match the values
7560/// produced by GCC's builtin.
7561enum class GCCTypeClass {
7562 None = -1,
7563 Void = 0,
7564 Integer = 1,
7565 // GCC reserves 2 for character types, but instead classifies them as
7566 // integers.
7567 Enum = 3,
7568 Bool = 4,
7569 Pointer = 5,
7570 // GCC reserves 6 for references, but appears to never use it (because
7571 // expressions never have reference type, presumably).
7572 PointerToDataMember = 7,
7573 RealFloat = 8,
7574 Complex = 9,
7575 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7576 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7577 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7578 // uses 12 for that purpose, same as for a class or struct. Maybe it
7579 // internally implements a pointer to member as a struct? Who knows.
7580 PointerToMemberFunction = 12, // Not a bug, see above.
7581 ClassOrStruct = 12,
7582 Union = 13,
7583 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7584 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7585 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7586 // literals.
7587};
7588
Chris Lattner86ee2862008-10-06 06:40:35 +00007589/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7590/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007591static GCCTypeClass
7592EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7593 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007594
Richard Smith08b682b2018-05-23 21:18:00 +00007595 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007596 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7597
7598 switch (CanTy->getTypeClass()) {
7599#define TYPE(ID, BASE)
7600#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7601#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7602#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7603#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007604 case Type::Auto:
7605 case Type::DeducedTemplateSpecialization:
7606 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007607
7608 case Type::Builtin:
7609 switch (BT->getKind()) {
7610#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007611#define SIGNED_TYPE(ID, SINGLETON_ID) \
7612 case BuiltinType::ID: return GCCTypeClass::Integer;
7613#define FLOATING_TYPE(ID, SINGLETON_ID) \
7614 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7615#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7616 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007617#include "clang/AST/BuiltinTypes.def"
7618 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007619 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007620
7621 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007622 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007623
Richard Smith08b682b2018-05-23 21:18:00 +00007624 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007625 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007626 case BuiltinType::WChar_U:
7627 case BuiltinType::Char8:
7628 case BuiltinType::Char16:
7629 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007630 case BuiltinType::UShort:
7631 case BuiltinType::UInt:
7632 case BuiltinType::ULong:
7633 case BuiltinType::ULongLong:
7634 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007635 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007636
Leonard Chanf921d852018-06-04 16:07:52 +00007637 case BuiltinType::UShortAccum:
7638 case BuiltinType::UAccum:
7639 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007640 case BuiltinType::UShortFract:
7641 case BuiltinType::UFract:
7642 case BuiltinType::ULongFract:
7643 case BuiltinType::SatUShortAccum:
7644 case BuiltinType::SatUAccum:
7645 case BuiltinType::SatULongAccum:
7646 case BuiltinType::SatUShortFract:
7647 case BuiltinType::SatUFract:
7648 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007649 return GCCTypeClass::None;
7650
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007651 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007652
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007653 case BuiltinType::ObjCId:
7654 case BuiltinType::ObjCClass:
7655 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007656#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7657 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007658#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007659#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7660 case BuiltinType::Id:
7661#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007662 case BuiltinType::OCLSampler:
7663 case BuiltinType::OCLEvent:
7664 case BuiltinType::OCLClkEvent:
7665 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007666 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007667 return GCCTypeClass::None;
7668
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007669 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007670 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007671 };
Richard Smith08b682b2018-05-23 21:18:00 +00007672 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007673
7674 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007675 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007676
7677 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007678 case Type::ConstantArray:
7679 case Type::VariableArray:
7680 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007681 case Type::FunctionNoProto:
7682 case Type::FunctionProto:
7683 return GCCTypeClass::Pointer;
7684
7685 case Type::MemberPointer:
7686 return CanTy->isMemberDataPointerType()
7687 ? GCCTypeClass::PointerToDataMember
7688 : GCCTypeClass::PointerToMemberFunction;
7689
7690 case Type::Complex:
7691 return GCCTypeClass::Complex;
7692
7693 case Type::Record:
7694 return CanTy->isUnionType() ? GCCTypeClass::Union
7695 : GCCTypeClass::ClassOrStruct;
7696
7697 case Type::Atomic:
7698 // GCC classifies _Atomic T the same as T.
7699 return EvaluateBuiltinClassifyType(
7700 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007701
7702 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007703 case Type::Vector:
7704 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007705 case Type::ObjCObject:
7706 case Type::ObjCInterface:
7707 case Type::ObjCObjectPointer:
7708 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007709 // GCC classifies vectors as None. We follow its lead and classify all
7710 // other types that don't fit into the regular classification the same way.
7711 return GCCTypeClass::None;
7712
7713 case Type::LValueReference:
7714 case Type::RValueReference:
7715 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007716 }
7717
Richard Smith08b682b2018-05-23 21:18:00 +00007718 llvm_unreachable("unexpected type class");
7719}
7720
7721/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7722/// as GCC.
7723static GCCTypeClass
7724EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7725 // If no argument was supplied, default to None. This isn't
7726 // ideal, however it is what gcc does.
7727 if (E->getNumArgs() == 0)
7728 return GCCTypeClass::None;
7729
7730 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7731 // being an ICE, but still folds it to a constant using the type of the first
7732 // argument.
7733 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007734}
7735
Richard Smith5fab0c92011-12-28 19:48:30 +00007736/// EvaluateBuiltinConstantPForLValue - Determine the result of
7737/// __builtin_constant_p when applied to the given lvalue.
7738///
7739/// An lvalue is only "constant" if it is a pointer or reference to the first
7740/// character of a string literal.
7741template<typename LValue>
7742static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007743 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007744 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7745}
7746
7747/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7748/// GCC as we can manage.
7749static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7750 QualType ArgType = Arg->getType();
7751
7752 // __builtin_constant_p always has one operand. The rules which gcc follows
7753 // are not precisely documented, but are as follows:
7754 //
7755 // - If the operand is of integral, floating, complex or enumeration type,
7756 // and can be folded to a known value of that type, it returns 1.
7757 // - If the operand and can be folded to a pointer to the first character
7758 // of a string literal (or such a pointer cast to an integral type), it
7759 // returns 1.
7760 //
7761 // Otherwise, it returns 0.
7762 //
7763 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7764 // its support for this does not currently work.
7765 if (ArgType->isIntegralOrEnumerationType()) {
7766 Expr::EvalResult Result;
7767 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7768 return false;
7769
7770 APValue &V = Result.Val;
7771 if (V.getKind() == APValue::Int)
7772 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007773 if (V.getKind() == APValue::LValue)
7774 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007775 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7776 return Arg->isEvaluatable(Ctx);
7777 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7778 LValue LV;
7779 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007780 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007781 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7782 : EvaluatePointer(Arg, LV, Info)) &&
7783 !Status.HasSideEffects)
7784 return EvaluateBuiltinConstantPForLValue(LV);
7785 }
7786
7787 // Anything else isn't considered to be sufficiently constant.
7788 return false;
7789}
7790
John McCall95007602010-05-10 23:27:23 +00007791/// Retrieves the "underlying object type" of the given expression,
7792/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007793static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007794 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7795 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007796 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007797 } else if (const Expr *E = B.get<const Expr*>()) {
7798 if (isa<CompoundLiteralExpr>(E))
7799 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007800 }
7801
7802 return QualType();
7803}
7804
George Burgess IV3a03fab2015-09-04 21:28:13 +00007805/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007806/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007807/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007808/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7809///
7810/// Always returns an RValue with a pointer representation.
7811static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7812 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7813
7814 auto *NoParens = E->IgnoreParens();
7815 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007816 if (Cast == nullptr)
7817 return NoParens;
7818
7819 // We only conservatively allow a few kinds of casts, because this code is
7820 // inherently a simple solution that seeks to support the common case.
7821 auto CastKind = Cast->getCastKind();
7822 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7823 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007824 return NoParens;
7825
7826 auto *SubExpr = Cast->getSubExpr();
7827 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7828 return NoParens;
7829 return ignorePointerCastsAndParens(SubExpr);
7830}
7831
George Burgess IVa51c4072015-10-16 01:49:01 +00007832/// Checks to see if the given LValue's Designator is at the end of the LValue's
7833/// record layout. e.g.
7834/// struct { struct { int a, b; } fst, snd; } obj;
7835/// obj.fst // no
7836/// obj.snd // yes
7837/// obj.fst.a // no
7838/// obj.fst.b // no
7839/// obj.snd.a // no
7840/// obj.snd.b // yes
7841///
7842/// Please note: this function is specialized for how __builtin_object_size
7843/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007844///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007845/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7846/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007847static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7848 assert(!LVal.Designator.Invalid);
7849
George Burgess IV4168d752016-06-27 19:40:41 +00007850 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7851 const RecordDecl *Parent = FD->getParent();
7852 Invalid = Parent->isInvalidDecl();
7853 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007854 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007855 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007856 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7857 };
7858
7859 auto &Base = LVal.getLValueBase();
7860 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7861 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007862 bool Invalid;
7863 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7864 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007865 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007866 for (auto *FD : IFD->chain()) {
7867 bool Invalid;
7868 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7869 return Invalid;
7870 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007871 }
7872 }
7873
George Burgess IVe3763372016-12-22 02:50:20 +00007874 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007875 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007876 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007877 // If we don't know the array bound, conservatively assume we're looking at
7878 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007879 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007880 if (BaseType->isIncompleteArrayType())
7881 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7882 else
7883 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007884 }
7885
7886 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7887 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007888 if (BaseType->isArrayType()) {
7889 // Because __builtin_object_size treats arrays as objects, we can ignore
7890 // the index iff this is the last array in the Designator.
7891 if (I + 1 == E)
7892 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007893 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7894 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007895 if (Index + 1 != CAT->getSize())
7896 return false;
7897 BaseType = CAT->getElementType();
7898 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007899 const auto *CT = BaseType->castAs<ComplexType>();
7900 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007901 if (Index != 1)
7902 return false;
7903 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007904 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007905 bool Invalid;
7906 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7907 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007908 BaseType = FD->getType();
7909 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007910 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007911 return false;
7912 }
7913 }
7914 return true;
7915}
7916
George Burgess IVe3763372016-12-22 02:50:20 +00007917/// Tests to see if the LValue has a user-specified designator (that isn't
7918/// necessarily valid). Note that this always returns 'true' if the LValue has
7919/// an unsized array as its first designator entry, because there's currently no
7920/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007921static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007922 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007923 return false;
7924
George Burgess IVe3763372016-12-22 02:50:20 +00007925 if (!LVal.Designator.Entries.empty())
7926 return LVal.Designator.isMostDerivedAnUnsizedArray();
7927
George Burgess IVa51c4072015-10-16 01:49:01 +00007928 if (!LVal.InvalidBase)
7929 return true;
7930
George Burgess IVe3763372016-12-22 02:50:20 +00007931 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7932 // the LValueBase.
7933 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7934 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007935}
7936
George Burgess IVe3763372016-12-22 02:50:20 +00007937/// Attempts to detect a user writing into a piece of memory that's impossible
7938/// to figure out the size of by just using types.
7939static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7940 const SubobjectDesignator &Designator = LVal.Designator;
7941 // Notes:
7942 // - Users can only write off of the end when we have an invalid base. Invalid
7943 // bases imply we don't know where the memory came from.
7944 // - We used to be a bit more aggressive here; we'd only be conservative if
7945 // the array at the end was flexible, or if it had 0 or 1 elements. This
7946 // broke some common standard library extensions (PR30346), but was
7947 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7948 // with some sort of whitelist. OTOH, it seems that GCC is always
7949 // conservative with the last element in structs (if it's an array), so our
7950 // current behavior is more compatible than a whitelisting approach would
7951 // be.
7952 return LVal.InvalidBase &&
7953 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7954 Designator.MostDerivedIsArrayElement &&
7955 isDesignatorAtObjectEnd(Ctx, LVal);
7956}
7957
7958/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7959/// Fails if the conversion would cause loss of precision.
7960static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7961 CharUnits &Result) {
7962 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7963 if (Int.ugt(CharUnitsMax))
7964 return false;
7965 Result = CharUnits::fromQuantity(Int.getZExtValue());
7966 return true;
7967}
7968
7969/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7970/// determine how many bytes exist from the beginning of the object to either
7971/// the end of the current subobject, or the end of the object itself, depending
7972/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007973///
George Burgess IVe3763372016-12-22 02:50:20 +00007974/// If this returns false, the value of Result is undefined.
7975static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7976 unsigned Type, const LValue &LVal,
7977 CharUnits &EndOffset) {
7978 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007979
George Burgess IV7fb7e362017-01-03 23:35:19 +00007980 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7981 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7982 return false;
7983 return HandleSizeof(Info, ExprLoc, Ty, Result);
7984 };
7985
George Burgess IVe3763372016-12-22 02:50:20 +00007986 // We want to evaluate the size of the entire object. This is a valid fallback
7987 // for when Type=1 and the designator is invalid, because we're asked for an
7988 // upper-bound.
7989 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7990 // Type=3 wants a lower bound, so we can't fall back to this.
7991 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007992 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007993
7994 llvm::APInt APEndOffset;
7995 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7996 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7997 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7998
7999 if (LVal.InvalidBase)
8000 return false;
8001
8002 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008003 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008004 }
8005
George Burgess IVe3763372016-12-22 02:50:20 +00008006 // We want to evaluate the size of a subobject.
8007 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008008
8009 // The following is a moderately common idiom in C:
8010 //
8011 // struct Foo { int a; char c[1]; };
8012 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8013 // strcpy(&F->c[0], Bar);
8014 //
George Burgess IVe3763372016-12-22 02:50:20 +00008015 // In order to not break too much legacy code, we need to support it.
8016 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8017 // If we can resolve this to an alloc_size call, we can hand that back,
8018 // because we know for certain how many bytes there are to write to.
8019 llvm::APInt APEndOffset;
8020 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8021 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8022 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8023
8024 // If we cannot determine the size of the initial allocation, then we can't
8025 // given an accurate upper-bound. However, we are still able to give
8026 // conservative lower-bounds for Type=3.
8027 if (Type == 1)
8028 return false;
8029 }
8030
8031 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008032 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008033 return false;
8034
George Burgess IVe3763372016-12-22 02:50:20 +00008035 // According to the GCC documentation, we want the size of the subobject
8036 // denoted by the pointer. But that's not quite right -- what we actually
8037 // want is the size of the immediately-enclosing array, if there is one.
8038 int64_t ElemsRemaining;
8039 if (Designator.MostDerivedIsArrayElement &&
8040 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8041 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8042 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8043 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8044 } else {
8045 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8046 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008047
George Burgess IVe3763372016-12-22 02:50:20 +00008048 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8049 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008050}
8051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008052/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008053/// returns true and stores the result in @p Size.
8054///
8055/// If @p WasError is non-null, this will report whether the failure to evaluate
8056/// is to be treated as an Error in IntExprEvaluator.
8057static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8058 EvalInfo &Info, uint64_t &Size) {
8059 // Determine the denoted object.
8060 LValue LVal;
8061 {
8062 // The operand of __builtin_object_size is never evaluated for side-effects.
8063 // If there are any, but we can determine the pointed-to object anyway, then
8064 // ignore the side-effects.
8065 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008066 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008067
8068 if (E->isGLValue()) {
8069 // It's possible for us to be given GLValues if we're called via
8070 // Expr::tryEvaluateObjectSize.
8071 APValue RVal;
8072 if (!EvaluateAsRValue(Info, E, RVal))
8073 return false;
8074 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008075 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8076 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008077 return false;
8078 }
8079
8080 // If we point to before the start of the object, there are no accessible
8081 // bytes.
8082 if (LVal.getLValueOffset().isNegative()) {
8083 Size = 0;
8084 return true;
8085 }
8086
8087 CharUnits EndOffset;
8088 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8089 return false;
8090
8091 // If we've fallen outside of the end offset, just pretend there's nothing to
8092 // write to/read from.
8093 if (EndOffset <= LVal.getLValueOffset())
8094 Size = 0;
8095 else
8096 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8097 return true;
John McCall95007602010-05-10 23:27:23 +00008098}
8099
Fangrui Song407659a2018-11-30 23:41:18 +00008100bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8101 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8102 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8103}
8104
Peter Collingbournee9200682011-05-13 03:29:01 +00008105bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008106 if (unsigned BuiltinOp = E->getBuiltinCallee())
8107 return VisitBuiltinCallExpr(E, BuiltinOp);
8108
8109 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8110}
8111
8112bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8113 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008114 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008115 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008116 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008117
8118 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008119 // The type was checked when we built the expression.
8120 unsigned Type =
8121 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8122 assert(Type <= 3 && "unexpected type");
8123
George Burgess IVe3763372016-12-22 02:50:20 +00008124 uint64_t Size;
8125 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8126 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008127
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008128 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008129 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008130
Richard Smith01ade172012-05-23 04:13:20 +00008131 // Expression had no side effects, but we couldn't statically determine the
8132 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008133 switch (Info.EvalMode) {
8134 case EvalInfo::EM_ConstantExpression:
8135 case EvalInfo::EM_PotentialConstantExpression:
8136 case EvalInfo::EM_ConstantFold:
8137 case EvalInfo::EM_EvaluateForOverflow:
8138 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008139 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008140 return Error(E);
8141 case EvalInfo::EM_ConstantExpressionUnevaluated:
8142 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008143 // Reduce it to a constant now.
8144 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008145 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008146
8147 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008148 }
8149
Tim Northover314fbfa2018-11-02 13:14:11 +00008150 case Builtin::BI__builtin_os_log_format_buffer_size: {
8151 analyze_os_log::OSLogBufferLayout Layout;
8152 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8153 return Success(Layout.size().getQuantity(), E);
8154 }
8155
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008156 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008157 case Builtin::BI__builtin_bswap32:
8158 case Builtin::BI__builtin_bswap64: {
8159 APSInt Val;
8160 if (!EvaluateInteger(E->getArg(0), Val, Info))
8161 return false;
8162
8163 return Success(Val.byteSwap(), E);
8164 }
8165
Richard Smith8889a3d2013-06-13 06:26:32 +00008166 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008167 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008168
Craig Topperf95a6d92018-08-08 22:31:12 +00008169 case Builtin::BI__builtin_clrsb:
8170 case Builtin::BI__builtin_clrsbl:
8171 case Builtin::BI__builtin_clrsbll: {
8172 APSInt Val;
8173 if (!EvaluateInteger(E->getArg(0), Val, Info))
8174 return false;
8175
8176 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8177 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008178
Richard Smith80b3c8e2013-06-13 05:04:16 +00008179 case Builtin::BI__builtin_clz:
8180 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008181 case Builtin::BI__builtin_clzll:
8182 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008183 APSInt Val;
8184 if (!EvaluateInteger(E->getArg(0), Val, Info))
8185 return false;
8186 if (!Val)
8187 return Error(E);
8188
8189 return Success(Val.countLeadingZeros(), E);
8190 }
8191
Fangrui Song407659a2018-11-30 23:41:18 +00008192 case Builtin::BI__builtin_constant_p: {
8193 auto Arg = E->getArg(0);
8194 if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8195 return Success(true, E);
8196 auto ArgTy = Arg->IgnoreImplicit()->getType();
8197 if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8198 !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8199 // We can delay calculation of __builtin_constant_p until after
8200 // inlining. Note: This diagnostic won't be shown to the user.
8201 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Bill Wendling2a81f662018-12-01 08:29:36 +00008202 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008203 }
8204 return Success(false, E);
8205 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008206
Richard Smith80b3c8e2013-06-13 05:04:16 +00008207 case Builtin::BI__builtin_ctz:
8208 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008209 case Builtin::BI__builtin_ctzll:
8210 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008211 APSInt Val;
8212 if (!EvaluateInteger(E->getArg(0), Val, Info))
8213 return false;
8214 if (!Val)
8215 return Error(E);
8216
8217 return Success(Val.countTrailingZeros(), E);
8218 }
8219
Richard Smith8889a3d2013-06-13 06:26:32 +00008220 case Builtin::BI__builtin_eh_return_data_regno: {
8221 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8222 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8223 return Success(Operand, E);
8224 }
8225
8226 case Builtin::BI__builtin_expect:
8227 return Visit(E->getArg(0));
8228
8229 case Builtin::BI__builtin_ffs:
8230 case Builtin::BI__builtin_ffsl:
8231 case Builtin::BI__builtin_ffsll: {
8232 APSInt Val;
8233 if (!EvaluateInteger(E->getArg(0), Val, Info))
8234 return false;
8235
8236 unsigned N = Val.countTrailingZeros();
8237 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8238 }
8239
8240 case Builtin::BI__builtin_fpclassify: {
8241 APFloat Val(0.0);
8242 if (!EvaluateFloat(E->getArg(5), Val, Info))
8243 return false;
8244 unsigned Arg;
8245 switch (Val.getCategory()) {
8246 case APFloat::fcNaN: Arg = 0; break;
8247 case APFloat::fcInfinity: Arg = 1; break;
8248 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8249 case APFloat::fcZero: Arg = 4; break;
8250 }
8251 return Visit(E->getArg(Arg));
8252 }
8253
8254 case Builtin::BI__builtin_isinf_sign: {
8255 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008256 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008257 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8258 }
8259
Richard Smithea3019d2013-10-15 19:07:14 +00008260 case Builtin::BI__builtin_isinf: {
8261 APFloat Val(0.0);
8262 return EvaluateFloat(E->getArg(0), Val, Info) &&
8263 Success(Val.isInfinity() ? 1 : 0, E);
8264 }
8265
8266 case Builtin::BI__builtin_isfinite: {
8267 APFloat Val(0.0);
8268 return EvaluateFloat(E->getArg(0), Val, Info) &&
8269 Success(Val.isFinite() ? 1 : 0, E);
8270 }
8271
8272 case Builtin::BI__builtin_isnan: {
8273 APFloat Val(0.0);
8274 return EvaluateFloat(E->getArg(0), Val, Info) &&
8275 Success(Val.isNaN() ? 1 : 0, E);
8276 }
8277
8278 case Builtin::BI__builtin_isnormal: {
8279 APFloat Val(0.0);
8280 return EvaluateFloat(E->getArg(0), Val, Info) &&
8281 Success(Val.isNormal() ? 1 : 0, E);
8282 }
8283
Richard Smith8889a3d2013-06-13 06:26:32 +00008284 case Builtin::BI__builtin_parity:
8285 case Builtin::BI__builtin_parityl:
8286 case Builtin::BI__builtin_parityll: {
8287 APSInt Val;
8288 if (!EvaluateInteger(E->getArg(0), Val, Info))
8289 return false;
8290
8291 return Success(Val.countPopulation() % 2, E);
8292 }
8293
Richard Smith80b3c8e2013-06-13 05:04:16 +00008294 case Builtin::BI__builtin_popcount:
8295 case Builtin::BI__builtin_popcountl:
8296 case Builtin::BI__builtin_popcountll: {
8297 APSInt Val;
8298 if (!EvaluateInteger(E->getArg(0), Val, Info))
8299 return false;
8300
8301 return Success(Val.countPopulation(), E);
8302 }
8303
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008304 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008305 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008306 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008307 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008308 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008309 << /*isConstexpr*/0 << /*isConstructor*/0
8310 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008311 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008312 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008313 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008314 case Builtin::BI__builtin_strlen:
8315 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008316 // As an extension, we support __builtin_strlen() as a constant expression,
8317 // and support folding strlen() to a constant.
8318 LValue String;
8319 if (!EvaluatePointer(E->getArg(0), String, Info))
8320 return false;
8321
Richard Smith8110c9d2016-11-29 19:45:17 +00008322 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8323
Richard Smithe6c19f22013-11-15 02:10:04 +00008324 // Fast path: if it's a string literal, search the string value.
8325 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8326 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008327 // The string literal may have embedded null characters. Find the first
8328 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008329 StringRef Str = S->getBytes();
8330 int64_t Off = String.Offset.getQuantity();
8331 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008332 S->getCharByteWidth() == 1 &&
8333 // FIXME: Add fast-path for wchar_t too.
8334 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008335 Str = Str.substr(Off);
8336
8337 StringRef::size_type Pos = Str.find(0);
8338 if (Pos != StringRef::npos)
8339 Str = Str.substr(0, Pos);
8340
8341 return Success(Str.size(), E);
8342 }
8343
8344 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008345 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008346
8347 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008348 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8349 APValue Char;
8350 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8351 !Char.isInt())
8352 return false;
8353 if (!Char.getInt())
8354 return Success(Strlen, E);
8355 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8356 return false;
8357 }
8358 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008359
Richard Smithe151bab2016-11-11 23:43:35 +00008360 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008361 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008362 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008363 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008364 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008365 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008366 // A call to strlen is not a constant expression.
8367 if (Info.getLangOpts().CPlusPlus11)
8368 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8369 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008370 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008371 else
8372 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008373 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008374 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008375 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008376 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008377 case Builtin::BI__builtin_wcsncmp:
8378 case Builtin::BI__builtin_memcmp:
8379 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008380 LValue String1, String2;
8381 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8382 !EvaluatePointer(E->getArg(1), String2, Info))
8383 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008384
8385 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8386
Richard Smithe151bab2016-11-11 23:43:35 +00008387 uint64_t MaxLength = uint64_t(-1);
8388 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008389 BuiltinOp != Builtin::BIwcscmp &&
8390 BuiltinOp != Builtin::BI__builtin_strcmp &&
8391 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008392 APSInt N;
8393 if (!EvaluateInteger(E->getArg(2), N, Info))
8394 return false;
8395 MaxLength = N.getExtValue();
8396 }
8397 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008398 BuiltinOp != Builtin::BIwmemcmp &&
8399 BuiltinOp != Builtin::BI__builtin_memcmp &&
8400 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008401 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8402 BuiltinOp == Builtin::BIwcsncmp ||
8403 BuiltinOp == Builtin::BIwmemcmp ||
8404 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8405 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8406 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008407 for (; MaxLength; --MaxLength) {
8408 APValue Char1, Char2;
8409 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8410 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8411 !Char1.isInt() || !Char2.isInt())
8412 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008413 if (Char1.getInt() != Char2.getInt()) {
8414 if (IsWide) // wmemcmp compares with wchar_t signedness.
8415 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8416 // memcmp always compares unsigned chars.
8417 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8418 }
Richard Smithe151bab2016-11-11 23:43:35 +00008419 if (StopAtNull && !Char1.getInt())
8420 return Success(0, E);
8421 assert(!(StopAtNull && !Char2.getInt()));
8422 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8423 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8424 return false;
8425 }
8426 // We hit the strncmp / memcmp limit.
8427 return Success(0, E);
8428 }
8429
Richard Smith01ba47d2012-04-13 00:45:38 +00008430 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008431 case Builtin::BI__atomic_is_lock_free:
8432 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008433 APSInt SizeVal;
8434 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8435 return false;
8436
8437 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8438 // of two less than the maximum inline atomic width, we know it is
8439 // lock-free. If the size isn't a power of two, or greater than the
8440 // maximum alignment where we promote atomics, we know it is not lock-free
8441 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8442 // the answer can only be determined at runtime; for example, 16-byte
8443 // atomics have lock-free implementations on some, but not all,
8444 // x86-64 processors.
8445
8446 // Check power-of-two.
8447 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008448 if (Size.isPowerOfTwo()) {
8449 // Check against inlining width.
8450 unsigned InlineWidthBits =
8451 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8452 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8453 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8454 Size == CharUnits::One() ||
8455 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8456 Expr::NPC_NeverValueDependent))
8457 // OK, we will inline appropriately-aligned operations of this size,
8458 // and _Atomic(T) is appropriately-aligned.
8459 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008460
Richard Smith01ba47d2012-04-13 00:45:38 +00008461 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8462 castAs<PointerType>()->getPointeeType();
8463 if (!PointeeType->isIncompleteType() &&
8464 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8465 // OK, we will inline operations on this object.
8466 return Success(1, E);
8467 }
8468 }
8469 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008470
Richard Smith01ba47d2012-04-13 00:45:38 +00008471 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8472 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008473 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008474 case Builtin::BIomp_is_initial_device:
8475 // We can decide statically which value the runtime would return if called.
8476 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008477 case Builtin::BI__builtin_add_overflow:
8478 case Builtin::BI__builtin_sub_overflow:
8479 case Builtin::BI__builtin_mul_overflow:
8480 case Builtin::BI__builtin_sadd_overflow:
8481 case Builtin::BI__builtin_uadd_overflow:
8482 case Builtin::BI__builtin_uaddl_overflow:
8483 case Builtin::BI__builtin_uaddll_overflow:
8484 case Builtin::BI__builtin_usub_overflow:
8485 case Builtin::BI__builtin_usubl_overflow:
8486 case Builtin::BI__builtin_usubll_overflow:
8487 case Builtin::BI__builtin_umul_overflow:
8488 case Builtin::BI__builtin_umull_overflow:
8489 case Builtin::BI__builtin_umulll_overflow:
8490 case Builtin::BI__builtin_saddl_overflow:
8491 case Builtin::BI__builtin_saddll_overflow:
8492 case Builtin::BI__builtin_ssub_overflow:
8493 case Builtin::BI__builtin_ssubl_overflow:
8494 case Builtin::BI__builtin_ssubll_overflow:
8495 case Builtin::BI__builtin_smul_overflow:
8496 case Builtin::BI__builtin_smull_overflow:
8497 case Builtin::BI__builtin_smulll_overflow: {
8498 LValue ResultLValue;
8499 APSInt LHS, RHS;
8500
8501 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8502 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8503 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8504 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8505 return false;
8506
8507 APSInt Result;
8508 bool DidOverflow = false;
8509
8510 // If the types don't have to match, enlarge all 3 to the largest of them.
8511 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8512 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8513 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8514 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8515 ResultType->isSignedIntegerOrEnumerationType();
8516 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8517 ResultType->isSignedIntegerOrEnumerationType();
8518 uint64_t LHSSize = LHS.getBitWidth();
8519 uint64_t RHSSize = RHS.getBitWidth();
8520 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8521 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8522
8523 // Add an additional bit if the signedness isn't uniformly agreed to. We
8524 // could do this ONLY if there is a signed and an unsigned that both have
8525 // MaxBits, but the code to check that is pretty nasty. The issue will be
8526 // caught in the shrink-to-result later anyway.
8527 if (IsSigned && !AllSigned)
8528 ++MaxBits;
8529
8530 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8531 !IsSigned);
8532 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8533 !IsSigned);
8534 Result = APSInt(MaxBits, !IsSigned);
8535 }
8536
8537 // Find largest int.
8538 switch (BuiltinOp) {
8539 default:
8540 llvm_unreachable("Invalid value for BuiltinOp");
8541 case Builtin::BI__builtin_add_overflow:
8542 case Builtin::BI__builtin_sadd_overflow:
8543 case Builtin::BI__builtin_saddl_overflow:
8544 case Builtin::BI__builtin_saddll_overflow:
8545 case Builtin::BI__builtin_uadd_overflow:
8546 case Builtin::BI__builtin_uaddl_overflow:
8547 case Builtin::BI__builtin_uaddll_overflow:
8548 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8549 : LHS.uadd_ov(RHS, DidOverflow);
8550 break;
8551 case Builtin::BI__builtin_sub_overflow:
8552 case Builtin::BI__builtin_ssub_overflow:
8553 case Builtin::BI__builtin_ssubl_overflow:
8554 case Builtin::BI__builtin_ssubll_overflow:
8555 case Builtin::BI__builtin_usub_overflow:
8556 case Builtin::BI__builtin_usubl_overflow:
8557 case Builtin::BI__builtin_usubll_overflow:
8558 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8559 : LHS.usub_ov(RHS, DidOverflow);
8560 break;
8561 case Builtin::BI__builtin_mul_overflow:
8562 case Builtin::BI__builtin_smul_overflow:
8563 case Builtin::BI__builtin_smull_overflow:
8564 case Builtin::BI__builtin_smulll_overflow:
8565 case Builtin::BI__builtin_umul_overflow:
8566 case Builtin::BI__builtin_umull_overflow:
8567 case Builtin::BI__builtin_umulll_overflow:
8568 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8569 : LHS.umul_ov(RHS, DidOverflow);
8570 break;
8571 }
8572
8573 // In the case where multiple sizes are allowed, truncate and see if
8574 // the values are the same.
8575 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8576 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8577 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8578 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8579 // since it will give us the behavior of a TruncOrSelf in the case where
8580 // its parameter <= its size. We previously set Result to be at least the
8581 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8582 // will work exactly like TruncOrSelf.
8583 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8584 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8585
8586 if (!APSInt::isSameValue(Temp, Result))
8587 DidOverflow = true;
8588 Result = Temp;
8589 }
8590
8591 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008592 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8593 return false;
Erich Keane00958272018-06-13 20:43:27 +00008594 return Success(DidOverflow, E);
8595 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008596 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008597}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008598
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008599/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008600/// object referred to by the lvalue.
8601static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8602 const LValue &LV) {
8603 // A null pointer can be viewed as being "past the end" but we don't
8604 // choose to look at it that way here.
8605 if (!LV.getLValueBase())
8606 return false;
8607
8608 // If the designator is valid and refers to a subobject, we're not pointing
8609 // past the end.
8610 if (!LV.getLValueDesignator().Invalid &&
8611 !LV.getLValueDesignator().isOnePastTheEnd())
8612 return false;
8613
David Majnemerc378ca52015-08-29 08:32:55 +00008614 // A pointer to an incomplete type might be past-the-end if the type's size is
8615 // zero. We cannot tell because the type is incomplete.
8616 QualType Ty = getType(LV.getLValueBase());
8617 if (Ty->isIncompleteType())
8618 return true;
8619
Richard Smithd20f1e62014-10-21 23:01:04 +00008620 // We're a past-the-end pointer if we point to the byte after the object,
8621 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008622 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008623 return LV.getLValueOffset() == Size;
8624}
8625
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008626namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008627
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008628/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008629///
8630/// We use a data recursive algorithm for binary operators so that we are able
8631/// to handle extreme cases of chained binary operators without causing stack
8632/// overflow.
8633class DataRecursiveIntBinOpEvaluator {
8634 struct EvalResult {
8635 APValue Val;
8636 bool Failed;
8637
8638 EvalResult() : Failed(false) { }
8639
8640 void swap(EvalResult &RHS) {
8641 Val.swap(RHS.Val);
8642 Failed = RHS.Failed;
8643 RHS.Failed = false;
8644 }
8645 };
8646
8647 struct Job {
8648 const Expr *E;
8649 EvalResult LHSResult; // meaningful only for binary operator expression.
8650 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008651
David Blaikie73726062015-08-12 23:09:24 +00008652 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008653 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008654
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008655 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008656 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008657 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008658
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008659 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008660 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008661 };
8662
8663 SmallVector<Job, 16> Queue;
8664
8665 IntExprEvaluator &IntEval;
8666 EvalInfo &Info;
8667 APValue &FinalResult;
8668
8669public:
8670 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8671 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008673 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008674 /// data recursively.
8675 /// We handle binary operators that are comma, logical, or that have operands
8676 /// with integral or enumeration type.
8677 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008678 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8679 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008680 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008681 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008682 }
8683
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008684 bool Traverse(const BinaryOperator *E) {
8685 enqueue(E);
8686 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008687 while (!Queue.empty())
8688 process(PrevResult);
8689
8690 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008691
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008692 FinalResult.swap(PrevResult.Val);
8693 return true;
8694 }
8695
8696private:
8697 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8698 return IntEval.Success(Value, E, Result);
8699 }
8700 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8701 return IntEval.Success(Value, E, Result);
8702 }
8703 bool Error(const Expr *E) {
8704 return IntEval.Error(E);
8705 }
8706 bool Error(const Expr *E, diag::kind D) {
8707 return IntEval.Error(E, D);
8708 }
8709
8710 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8711 return Info.CCEDiag(E, D);
8712 }
8713
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008714 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008715 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008716 bool &SuppressRHSDiags);
8717
8718 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8719 const BinaryOperator *E, APValue &Result);
8720
8721 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8722 Result.Failed = !Evaluate(Result.Val, Info, E);
8723 if (Result.Failed)
8724 Result.Val = APValue();
8725 }
8726
Richard Trieuba4d0872012-03-21 23:30:30 +00008727 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008728
8729 void enqueue(const Expr *E) {
8730 E = E->IgnoreParens();
8731 Queue.resize(Queue.size()+1);
8732 Queue.back().E = E;
8733 Queue.back().Kind = Job::AnyExprKind;
8734 }
8735};
8736
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008737}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008738
8739bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008740 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008741 bool &SuppressRHSDiags) {
8742 if (E->getOpcode() == BO_Comma) {
8743 // Ignore LHS but note if we could not evaluate it.
8744 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008745 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008746 return true;
8747 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008748
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008749 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008750 bool LHSAsBool;
8751 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008752 // We were able to evaluate the LHS, see if we can get away with not
8753 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008754 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8755 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008756 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008757 }
8758 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008759 LHSResult.Failed = true;
8760
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008761 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008762 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008763 if (!Info.noteSideEffect())
8764 return false;
8765
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008766 // We can't evaluate the LHS; however, sometimes the result
8767 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8768 // Don't ignore RHS and suppress diagnostics from this arm.
8769 SuppressRHSDiags = true;
8770 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008771
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008772 return true;
8773 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008774
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008775 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8776 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008777
George Burgess IVa145e252016-05-25 22:38:36 +00008778 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008779 return false; // Ignore RHS;
8780
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008781 return true;
8782}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008783
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008784static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8785 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008786 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8787 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8788 // offsets.
8789 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8790 CharUnits &Offset = LVal.getLValueOffset();
8791 uint64_t Offset64 = Offset.getQuantity();
8792 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8793 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8794 : Offset64 + Index64);
8795}
8796
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008797bool DataRecursiveIntBinOpEvaluator::
8798 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8799 const BinaryOperator *E, APValue &Result) {
8800 if (E->getOpcode() == BO_Comma) {
8801 if (RHSResult.Failed)
8802 return false;
8803 Result = RHSResult.Val;
8804 return true;
8805 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008806
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008807 if (E->isLogicalOp()) {
8808 bool lhsResult, rhsResult;
8809 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8810 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008811
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008812 if (LHSIsOK) {
8813 if (RHSIsOK) {
8814 if (E->getOpcode() == BO_LOr)
8815 return Success(lhsResult || rhsResult, E, Result);
8816 else
8817 return Success(lhsResult && rhsResult, E, Result);
8818 }
8819 } else {
8820 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008821 // We can't evaluate the LHS; however, sometimes the result
8822 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8823 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008824 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008825 }
8826 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008827
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008828 return false;
8829 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008830
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008831 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8832 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008833
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008834 if (LHSResult.Failed || RHSResult.Failed)
8835 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008836
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008837 const APValue &LHSVal = LHSResult.Val;
8838 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008839
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008840 // Handle cases like (unsigned long)&a + 4.
8841 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8842 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008843 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008844 return true;
8845 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008846
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008847 // Handle cases like 4 + (unsigned long)&a
8848 if (E->getOpcode() == BO_Add &&
8849 RHSVal.isLValue() && LHSVal.isInt()) {
8850 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008851 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008852 return true;
8853 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008854
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008855 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8856 // Handle (intptr_t)&&A - (intptr_t)&&B.
8857 if (!LHSVal.getLValueOffset().isZero() ||
8858 !RHSVal.getLValueOffset().isZero())
8859 return false;
8860 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8861 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8862 if (!LHSExpr || !RHSExpr)
8863 return false;
8864 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8865 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8866 if (!LHSAddrExpr || !RHSAddrExpr)
8867 return false;
8868 // Make sure both labels come from the same function.
8869 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8870 RHSAddrExpr->getLabel()->getDeclContext())
8871 return false;
8872 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8873 return true;
8874 }
Richard Smith43e77732013-05-07 04:50:00 +00008875
8876 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008877 if (!LHSVal.isInt() || !RHSVal.isInt())
8878 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008879
8880 // Set up the width and signedness manually, in case it can't be deduced
8881 // from the operation we're performing.
8882 // FIXME: Don't do this in the cases where we can deduce it.
8883 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8884 E->getType()->isUnsignedIntegerOrEnumerationType());
8885 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8886 RHSVal.getInt(), Value))
8887 return false;
8888 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008889}
8890
Richard Trieuba4d0872012-03-21 23:30:30 +00008891void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008892 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00008893
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008894 switch (job.Kind) {
8895 case Job::AnyExprKind: {
8896 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8897 if (shouldEnqueue(Bop)) {
8898 job.Kind = Job::BinOpKind;
8899 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008900 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008901 }
8902 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008903
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008904 EvaluateExpr(job.E, Result);
8905 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008906 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008907 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008908
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008909 case Job::BinOpKind: {
8910 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008911 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008912 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008913 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008914 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008915 }
8916 if (SuppressRHSDiags)
8917 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008918 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008919 job.Kind = Job::BinOpVisitedLHSKind;
8920 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008921 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008922 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008923
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008924 case Job::BinOpVisitedLHSKind: {
8925 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8926 EvalResult RHS;
8927 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008928 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008929 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008930 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008931 }
8932 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008933
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008934 llvm_unreachable("Invalid Job::Kind!");
8935}
8936
George Burgess IV8c892b52016-05-25 22:31:54 +00008937namespace {
8938/// Used when we determine that we should fail, but can keep evaluating prior to
8939/// noting that we had a failure.
8940class DelayedNoteFailureRAII {
8941 EvalInfo &Info;
8942 bool NoteFailure;
8943
8944public:
8945 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8946 : Info(Info), NoteFailure(NoteFailure) {}
8947 ~DelayedNoteFailureRAII() {
8948 if (NoteFailure) {
8949 bool ContinueAfterFailure = Info.noteFailure();
8950 (void)ContinueAfterFailure;
8951 assert(ContinueAfterFailure &&
8952 "Shouldn't have kept evaluating on failure.");
8953 }
8954 }
8955};
8956}
8957
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008958template <class SuccessCB, class AfterCB>
8959static bool
8960EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8961 SuccessCB &&Success, AfterCB &&DoAfter) {
8962 assert(E->isComparisonOp() && "expected comparison operator");
8963 assert((E->getOpcode() == BO_Cmp ||
8964 E->getType()->isIntegralOrEnumerationType()) &&
8965 "unsupported binary expression evaluation");
8966 auto Error = [&](const Expr *E) {
8967 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8968 return false;
8969 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008970
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008971 using CCR = ComparisonCategoryResult;
8972 bool IsRelational = E->isRelationalOp();
8973 bool IsEquality = E->isEqualityOp();
8974 if (E->getOpcode() == BO_Cmp) {
8975 const ComparisonCategoryInfo &CmpInfo =
8976 Info.Ctx.CompCategories.getInfoForType(E->getType());
8977 IsRelational = CmpInfo.isOrdered();
8978 IsEquality = CmpInfo.isEquality();
8979 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008980
Anders Carlssonacc79812008-11-16 07:17:21 +00008981 QualType LHSTy = E->getLHS()->getType();
8982 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008983
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008984 if (LHSTy->isIntegralOrEnumerationType() &&
8985 RHSTy->isIntegralOrEnumerationType()) {
8986 APSInt LHS, RHS;
8987 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8988 if (!LHSOK && !Info.noteFailure())
8989 return false;
8990 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8991 return false;
8992 if (LHS < RHS)
8993 return Success(CCR::Less, E);
8994 if (LHS > RHS)
8995 return Success(CCR::Greater, E);
8996 return Success(CCR::Equal, E);
8997 }
8998
Chandler Carruthb29a7432014-10-11 11:03:30 +00008999 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009000 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009001 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009002 if (E->isAssignmentOp()) {
9003 LValue LV;
9004 EvaluateLValue(E->getLHS(), LV, Info);
9005 LHSOK = false;
9006 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009007 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9008 if (LHSOK) {
9009 LHS.makeComplexFloat();
9010 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9011 }
9012 } else {
9013 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9014 }
George Burgess IVa145e252016-05-25 22:38:36 +00009015 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009016 return false;
9017
Chandler Carruthb29a7432014-10-11 11:03:30 +00009018 if (E->getRHS()->getType()->isRealFloatingType()) {
9019 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9020 return false;
9021 RHS.makeComplexFloat();
9022 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9023 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009024 return false;
9025
9026 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009027 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009028 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009029 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009030 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009031 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9032 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009033 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009034 assert(IsEquality && "invalid complex comparison");
9035 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9036 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9037 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009038 }
9039 }
Mike Stump11289f42009-09-09 15:08:12 +00009040
Anders Carlssonacc79812008-11-16 07:17:21 +00009041 if (LHSTy->isRealFloatingType() &&
9042 RHSTy->isRealFloatingType()) {
9043 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009044
Richard Smith253c2a32012-01-27 01:14:48 +00009045 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009046 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009047 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009048
Richard Smith253c2a32012-01-27 01:14:48 +00009049 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009050 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009051
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009052 assert(E->isComparisonOp() && "Invalid binary operator!");
9053 auto GetCmpRes = [&]() {
9054 switch (LHS.compare(RHS)) {
9055 case APFloat::cmpEqual:
9056 return CCR::Equal;
9057 case APFloat::cmpLessThan:
9058 return CCR::Less;
9059 case APFloat::cmpGreaterThan:
9060 return CCR::Greater;
9061 case APFloat::cmpUnordered:
9062 return CCR::Unordered;
9063 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009064 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009065 };
9066 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009067 }
Mike Stump11289f42009-09-09 15:08:12 +00009068
Eli Friedmana38da572009-04-28 19:17:36 +00009069 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009070 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009071
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009072 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9073 if (!LHSOK && !Info.noteFailure())
9074 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009075
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009076 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9077 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009078
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009079 // Reject differing bases from the normal codepath; we special-case
9080 // comparisons to null.
9081 if (!HasSameBase(LHSValue, RHSValue)) {
9082 // Inequalities and subtractions between unrelated pointers have
9083 // unspecified or undefined behavior.
9084 if (!IsEquality)
9085 return Error(E);
9086 // A constant address may compare equal to the address of a symbol.
9087 // The one exception is that address of an object cannot compare equal
9088 // to a null pointer constant.
9089 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9090 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9091 return Error(E);
9092 // It's implementation-defined whether distinct literals will have
9093 // distinct addresses. In clang, the result of such a comparison is
9094 // unspecified, so it is not a constant expression. However, we do know
9095 // that the address of a literal will be non-null.
9096 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9097 LHSValue.Base && RHSValue.Base)
9098 return Error(E);
9099 // We can't tell whether weak symbols will end up pointing to the same
9100 // object.
9101 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9102 return Error(E);
9103 // We can't compare the address of the start of one object with the
9104 // past-the-end address of another object, per C++ DR1652.
9105 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9106 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9107 (RHSValue.Base && RHSValue.Offset.isZero() &&
9108 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9109 return Error(E);
9110 // We can't tell whether an object is at the same address as another
9111 // zero sized object.
9112 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9113 (LHSValue.Base && isZeroSized(RHSValue)))
9114 return Error(E);
9115 return Success(CCR::Nonequal, E);
9116 }
Eli Friedman64004332009-03-23 04:38:34 +00009117
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009118 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9119 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009120
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009121 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9122 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009123
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009124 // C++11 [expr.rel]p3:
9125 // Pointers to void (after pointer conversions) can be compared, with a
9126 // result defined as follows: If both pointers represent the same
9127 // address or are both the null pointer value, the result is true if the
9128 // operator is <= or >= and false otherwise; otherwise the result is
9129 // unspecified.
9130 // We interpret this as applying to pointers to *cv* void.
9131 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9132 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009133
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009134 // C++11 [expr.rel]p2:
9135 // - If two pointers point to non-static data members of the same object,
9136 // or to subobjects or array elements fo such members, recursively, the
9137 // pointer to the later declared member compares greater provided the
9138 // two members have the same access control and provided their class is
9139 // not a union.
9140 // [...]
9141 // - Otherwise pointer comparisons are unspecified.
9142 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9143 bool WasArrayIndex;
9144 unsigned Mismatch = FindDesignatorMismatch(
9145 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9146 // At the point where the designators diverge, the comparison has a
9147 // specified value if:
9148 // - we are comparing array indices
9149 // - we are comparing fields of a union, or fields with the same access
9150 // Otherwise, the result is unspecified and thus the comparison is not a
9151 // constant expression.
9152 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9153 Mismatch < RHSDesignator.Entries.size()) {
9154 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9155 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9156 if (!LF && !RF)
9157 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9158 else if (!LF)
9159 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009160 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9161 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009162 else if (!RF)
9163 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009164 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9165 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009166 else if (!LF->getParent()->isUnion() &&
9167 LF->getAccess() != RF->getAccess())
9168 Info.CCEDiag(E,
9169 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009170 << LF << LF->getAccess() << RF << RF->getAccess()
9171 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009172 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009173 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009174
9175 // The comparison here must be unsigned, and performed with the same
9176 // width as the pointer.
9177 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9178 uint64_t CompareLHS = LHSOffset.getQuantity();
9179 uint64_t CompareRHS = RHSOffset.getQuantity();
9180 assert(PtrSize <= 64 && "Unexpected pointer width");
9181 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9182 CompareLHS &= Mask;
9183 CompareRHS &= Mask;
9184
9185 // If there is a base and this is a relational operator, we can only
9186 // compare pointers within the object in question; otherwise, the result
9187 // depends on where the object is located in memory.
9188 if (!LHSValue.Base.isNull() && IsRelational) {
9189 QualType BaseTy = getType(LHSValue.Base);
9190 if (BaseTy->isIncompleteType())
9191 return Error(E);
9192 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9193 uint64_t OffsetLimit = Size.getQuantity();
9194 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9195 return Error(E);
9196 }
9197
9198 if (CompareLHS < CompareRHS)
9199 return Success(CCR::Less, E);
9200 if (CompareLHS > CompareRHS)
9201 return Success(CCR::Greater, E);
9202 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009203 }
Richard Smith7bb00672012-02-01 01:42:44 +00009204
9205 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009206 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009207 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9208
9209 MemberPtr LHSValue, RHSValue;
9210
9211 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009212 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009213 return false;
9214
9215 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9216 return false;
9217
9218 // C++11 [expr.eq]p2:
9219 // If both operands are null, they compare equal. Otherwise if only one is
9220 // null, they compare unequal.
9221 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9222 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009223 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009224 }
9225
9226 // Otherwise if either is a pointer to a virtual member function, the
9227 // result is unspecified.
9228 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9229 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009230 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009231 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9232 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009233 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009234
9235 // Otherwise they compare equal if and only if they would refer to the
9236 // same member of the same most derived object or the same subobject if
9237 // they were dereferenced with a hypothetical object of the associated
9238 // class type.
9239 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009240 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009241 }
9242
Richard Smithab44d9b2012-02-14 22:35:28 +00009243 if (LHSTy->isNullPtrType()) {
9244 assert(E->isComparisonOp() && "unexpected nullptr operation");
9245 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9246 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9247 // are compared, the result is true of the operator is <=, >= or ==, and
9248 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009249 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009250 }
9251
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009252 return DoAfter();
9253}
9254
9255bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9256 if (!CheckLiteralType(Info, E))
9257 return false;
9258
9259 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9260 const BinaryOperator *E) {
9261 // Evaluation succeeded. Lookup the information for the comparison category
9262 // type and fetch the VarDecl for the result.
9263 const ComparisonCategoryInfo &CmpInfo =
9264 Info.Ctx.CompCategories.getInfoForType(E->getType());
9265 const VarDecl *VD =
9266 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9267 // Check and evaluate the result as a constant expression.
9268 LValue LV;
9269 LV.set(VD);
9270 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9271 return false;
9272 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9273 };
9274 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9275 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9276 });
9277}
9278
9279bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9280 // We don't call noteFailure immediately because the assignment happens after
9281 // we evaluate LHS and RHS.
9282 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9283 return Error(E);
9284
9285 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9286 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9287 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9288
9289 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9290 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009291 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009292
9293 if (E->isComparisonOp()) {
9294 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9295 // comparisons and then translating the result.
9296 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9297 const BinaryOperator *E) {
9298 using CCR = ComparisonCategoryResult;
9299 bool IsEqual = ResKind == CCR::Equal,
9300 IsLess = ResKind == CCR::Less,
9301 IsGreater = ResKind == CCR::Greater;
9302 auto Op = E->getOpcode();
9303 switch (Op) {
9304 default:
9305 llvm_unreachable("unsupported binary operator");
9306 case BO_EQ:
9307 case BO_NE:
9308 return Success(IsEqual == (Op == BO_EQ), E);
9309 case BO_LT: return Success(IsLess, E);
9310 case BO_GT: return Success(IsGreater, E);
9311 case BO_LE: return Success(IsEqual || IsLess, E);
9312 case BO_GE: return Success(IsEqual || IsGreater, E);
9313 }
9314 };
9315 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9316 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9317 });
9318 }
9319
9320 QualType LHSTy = E->getLHS()->getType();
9321 QualType RHSTy = E->getRHS()->getType();
9322
9323 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9324 E->getOpcode() == BO_Sub) {
9325 LValue LHSValue, RHSValue;
9326
9327 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9328 if (!LHSOK && !Info.noteFailure())
9329 return false;
9330
9331 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9332 return false;
9333
9334 // Reject differing bases from the normal codepath; we special-case
9335 // comparisons to null.
9336 if (!HasSameBase(LHSValue, RHSValue)) {
9337 // Handle &&A - &&B.
9338 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9339 return Error(E);
9340 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9341 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9342 if (!LHSExpr || !RHSExpr)
9343 return Error(E);
9344 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9345 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9346 if (!LHSAddrExpr || !RHSAddrExpr)
9347 return Error(E);
9348 // Make sure both labels come from the same function.
9349 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9350 RHSAddrExpr->getLabel()->getDeclContext())
9351 return Error(E);
9352 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9353 }
9354 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9355 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9356
9357 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9358 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9359
9360 // C++11 [expr.add]p6:
9361 // Unless both pointers point to elements of the same array object, or
9362 // one past the last element of the array object, the behavior is
9363 // undefined.
9364 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9365 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9366 RHSDesignator))
9367 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9368
9369 QualType Type = E->getLHS()->getType();
9370 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9371
9372 CharUnits ElementSize;
9373 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9374 return false;
9375
9376 // As an extension, a type may have zero size (empty struct or union in
9377 // C, array of zero length). Pointer subtraction in such cases has
9378 // undefined behavior, so is not constant.
9379 if (ElementSize.isZero()) {
9380 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9381 << ElementType;
9382 return false;
9383 }
9384
9385 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9386 // and produce incorrect results when it overflows. Such behavior
9387 // appears to be non-conforming, but is common, so perhaps we should
9388 // assume the standard intended for such cases to be undefined behavior
9389 // and check for them.
9390
9391 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9392 // overflow in the final conversion to ptrdiff_t.
9393 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9394 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9395 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9396 false);
9397 APSInt TrueResult = (LHS - RHS) / ElemSize;
9398 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9399
9400 if (Result.extend(65) != TrueResult &&
9401 !HandleOverflow(Info, E, TrueResult, E->getType()))
9402 return false;
9403 return Success(Result, E);
9404 }
9405
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009406 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009407}
9408
Peter Collingbournee190dee2011-03-11 19:24:49 +00009409/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9410/// a result as the expression's type.
9411bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9412 const UnaryExprOrTypeTraitExpr *E) {
9413 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009414 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009415 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009416 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009417 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9418 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009419 else
Richard Smith6822bd72018-10-26 19:26:45 +00009420 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9421 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009422 }
Eli Friedman64004332009-03-23 04:38:34 +00009423
Peter Collingbournee190dee2011-03-11 19:24:49 +00009424 case UETT_VecStep: {
9425 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009426
Peter Collingbournee190dee2011-03-11 19:24:49 +00009427 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009428 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009429
Peter Collingbournee190dee2011-03-11 19:24:49 +00009430 // The vec_step built-in functions that take a 3-component
9431 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9432 if (n == 3)
9433 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009434
Peter Collingbournee190dee2011-03-11 19:24:49 +00009435 return Success(n, E);
9436 } else
9437 return Success(1, E);
9438 }
9439
9440 case UETT_SizeOf: {
9441 QualType SrcTy = E->getTypeOfArgument();
9442 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9443 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009444 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9445 SrcTy = Ref->getPointeeType();
9446
Richard Smithd62306a2011-11-10 06:34:14 +00009447 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009448 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009449 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009450 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009451 }
Alexey Bataev00396512015-07-02 03:40:19 +00009452 case UETT_OpenMPRequiredSimdAlign:
9453 assert(E->isArgumentType());
9454 return Success(
9455 Info.Ctx.toCharUnitsFromBits(
9456 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9457 .getQuantity(),
9458 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009459 }
9460
9461 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009462}
9463
Peter Collingbournee9200682011-05-13 03:29:01 +00009464bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009465 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009466 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009467 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009468 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009469 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009470 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009471 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009472 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009473 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009474 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009475 APSInt IdxResult;
9476 if (!EvaluateInteger(Idx, IdxResult, Info))
9477 return false;
9478 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9479 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009480 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009481 CurrentType = AT->getElementType();
9482 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9483 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009484 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009485 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009486
James Y Knight7281c352015-12-29 22:31:18 +00009487 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009488 FieldDecl *MemberDecl = ON.getField();
9489 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009490 if (!RT)
9491 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009492 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009493 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009494 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009495 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009496 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009497 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009498 CurrentType = MemberDecl->getType().getNonReferenceType();
9499 break;
9500 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009501
James Y Knight7281c352015-12-29 22:31:18 +00009502 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009503 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009504
James Y Knight7281c352015-12-29 22:31:18 +00009505 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009506 CXXBaseSpecifier *BaseSpec = ON.getBase();
9507 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009508 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009509
9510 // Find the layout of the class whose base we are looking into.
9511 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009512 if (!RT)
9513 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009514 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009515 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009516 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9517
9518 // Find the base class itself.
9519 CurrentType = BaseSpec->getType();
9520 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9521 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009522 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009523
Douglas Gregord1702062010-04-29 00:18:15 +00009524 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009525 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009526 break;
9527 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009528 }
9529 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009530 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009531}
9532
Chris Lattnere13042c2008-07-11 19:10:17 +00009533bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009534 switch (E->getOpcode()) {
9535 default:
9536 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9537 // See C99 6.6p3.
9538 return Error(E);
9539 case UO_Extension:
9540 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9541 // If so, we could clear the diagnostic ID.
9542 return Visit(E->getSubExpr());
9543 case UO_Plus:
9544 // The result is just the value.
9545 return Visit(E->getSubExpr());
9546 case UO_Minus: {
9547 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009548 return false;
9549 if (!Result.isInt()) return Error(E);
9550 const APSInt &Value = Result.getInt();
9551 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9552 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9553 E->getType()))
9554 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009555 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009556 }
9557 case UO_Not: {
9558 if (!Visit(E->getSubExpr()))
9559 return false;
9560 if (!Result.isInt()) return Error(E);
9561 return Success(~Result.getInt(), E);
9562 }
9563 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009564 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009565 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009566 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009567 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009568 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009569 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009570}
Mike Stump11289f42009-09-09 15:08:12 +00009571
Chris Lattner477c4be2008-07-12 01:15:53 +00009572/// HandleCast - This is used to evaluate implicit or explicit casts where the
9573/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009574bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9575 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009576 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009577 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009578
Eli Friedmanc757de22011-03-25 00:43:55 +00009579 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009580 case CK_BaseToDerived:
9581 case CK_DerivedToBase:
9582 case CK_UncheckedDerivedToBase:
9583 case CK_Dynamic:
9584 case CK_ToUnion:
9585 case CK_ArrayToPointerDecay:
9586 case CK_FunctionToPointerDecay:
9587 case CK_NullToPointer:
9588 case CK_NullToMemberPointer:
9589 case CK_BaseToDerivedMemberPointer:
9590 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009591 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009592 case CK_ConstructorConversion:
9593 case CK_IntegralToPointer:
9594 case CK_ToVoid:
9595 case CK_VectorSplat:
9596 case CK_IntegralToFloating:
9597 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009598 case CK_CPointerToObjCPointerCast:
9599 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009600 case CK_AnyPointerToBlockPointerCast:
9601 case CK_ObjCObjectLValueCast:
9602 case CK_FloatingRealToComplex:
9603 case CK_FloatingComplexToReal:
9604 case CK_FloatingComplexCast:
9605 case CK_FloatingComplexToIntegralComplex:
9606 case CK_IntegralRealToComplex:
9607 case CK_IntegralComplexCast:
9608 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009609 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009610 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009611 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009612 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009613 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009614 case CK_FixedPointCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009615 llvm_unreachable("invalid cast kind for integral value");
9616
Eli Friedman9faf2f92011-03-25 19:07:11 +00009617 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009618 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009619 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009620 case CK_ARCProduceObject:
9621 case CK_ARCConsumeObject:
9622 case CK_ARCReclaimReturnedObject:
9623 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009624 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009625 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009626
Richard Smith4ef685b2012-01-17 21:17:26 +00009627 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009628 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009629 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009630 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009631 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009632
9633 case CK_MemberPointerToBoolean:
9634 case CK_PointerToBoolean:
9635 case CK_IntegralToBoolean:
9636 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009637 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009638 case CK_FloatingComplexToBoolean:
9639 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009640 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009641 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009642 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009643 uint64_t IntResult = BoolResult;
9644 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9645 IntResult = (uint64_t)-1;
9646 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009647 }
9648
Leonard Chanb4ba4672018-10-23 17:55:35 +00009649 case CK_FixedPointToBoolean: {
9650 // Unsigned padding does not affect this.
9651 APValue Val;
9652 if (!Evaluate(Val, Info, SubExpr))
9653 return false;
9654 return Success(Val.getInt().getBoolValue(), E);
9655 }
9656
Eli Friedmanc757de22011-03-25 00:43:55 +00009657 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009658 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009659 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009660
Eli Friedman742421e2009-02-20 01:15:07 +00009661 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009662 // Allow casts of address-of-label differences if they are no-ops
9663 // or narrowing. (The narrowing case isn't actually guaranteed to
9664 // be constant-evaluatable except in some narrow cases which are hard
9665 // to detect here. We let it through on the assumption the user knows
9666 // what they are doing.)
9667 if (Result.isAddrLabelDiff())
9668 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009669 // Only allow casts of lvalues if they are lossless.
9670 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9671 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009672
Richard Smith911e1422012-01-30 22:27:01 +00009673 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9674 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009675 }
Mike Stump11289f42009-09-09 15:08:12 +00009676
Eli Friedmanc757de22011-03-25 00:43:55 +00009677 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009678 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9679
John McCall45d55e42010-05-07 21:00:08 +00009680 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009681 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009682 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009683
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009684 if (LV.getLValueBase()) {
9685 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009686 // FIXME: Allow a larger integer size than the pointer size, and allow
9687 // narrowing back down to pointer width in subsequent integral casts.
9688 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009689 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009690 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009691
Richard Smithcf74da72011-11-16 07:18:12 +00009692 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009693 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009694 return true;
9695 }
9696
Yaxun Liu402804b2016-12-15 08:09:08 +00009697 uint64_t V;
9698 if (LV.isNullPointer())
9699 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9700 else
9701 V = LV.getLValueOffset().getQuantity();
9702
9703 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009704 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009705 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009706
Eli Friedmanc757de22011-03-25 00:43:55 +00009707 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009708 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009709 if (!EvaluateComplex(SubExpr, C, Info))
9710 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009711 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009712 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009713
Eli Friedmanc757de22011-03-25 00:43:55 +00009714 case CK_FloatingToIntegral: {
9715 APFloat F(0.0);
9716 if (!EvaluateFloat(SubExpr, F, Info))
9717 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009718
Richard Smith357362d2011-12-13 06:39:58 +00009719 APSInt Value;
9720 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9721 return false;
9722 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009723 }
9724 }
Mike Stump11289f42009-09-09 15:08:12 +00009725
Eli Friedmanc757de22011-03-25 00:43:55 +00009726 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009727}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009728
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009729bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9730 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009731 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009732 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9733 return false;
9734 if (!LV.isComplexInt())
9735 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009736 return Success(LV.getComplexIntReal(), E);
9737 }
9738
9739 return Visit(E->getSubExpr());
9740}
9741
Eli Friedman4e7a2412009-02-27 04:45:43 +00009742bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009743 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009744 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009745 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9746 return false;
9747 if (!LV.isComplexInt())
9748 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009749 return Success(LV.getComplexIntImag(), E);
9750 }
9751
Richard Smith4a678122011-10-24 18:44:57 +00009752 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009753 return Success(0, E);
9754}
9755
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009756bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9757 return Success(E->getPackLength(), E);
9758}
9759
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009760bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9761 return Success(E->getValue(), E);
9762}
9763
Leonard Chandb01c3a2018-06-20 17:19:40 +00009764bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9765 switch (E->getOpcode()) {
9766 default:
9767 // Invalid unary operators
9768 return Error(E);
9769 case UO_Plus:
9770 // The result is just the value.
9771 return Visit(E->getSubExpr());
9772 case UO_Minus: {
9773 if (!Visit(E->getSubExpr())) return false;
9774 if (!Result.isInt()) return Error(E);
9775 const APSInt &Value = Result.getInt();
9776 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9777 SmallString<64> S;
9778 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009779 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009780 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9781 if (Info.noteUndefinedBehavior()) return false;
9782 }
9783 return Success(-Value, E);
9784 }
9785 case UO_LNot: {
9786 bool bres;
9787 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9788 return false;
9789 return Success(!bres, E);
9790 }
9791 }
9792}
9793
Chris Lattner05706e882008-07-11 18:11:29 +00009794//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009795// Float Evaluation
9796//===----------------------------------------------------------------------===//
9797
9798namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009799class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009800 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009801 APFloat &Result;
9802public:
9803 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009804 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009805
Richard Smith2e312c82012-03-03 22:46:17 +00009806 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009807 Result = V.getFloat();
9808 return true;
9809 }
Eli Friedman24c01542008-08-22 00:06:13 +00009810
Richard Smithfddd3842011-12-30 21:15:51 +00009811 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009812 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9813 return true;
9814 }
9815
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009816 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009817
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009818 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009819 bool VisitBinaryOperator(const BinaryOperator *E);
9820 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009821 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009822
John McCallb1fb0d32010-05-07 22:08:54 +00009823 bool VisitUnaryReal(const UnaryOperator *E);
9824 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009825
Richard Smithfddd3842011-12-30 21:15:51 +00009826 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009827};
9828} // end anonymous namespace
9829
9830static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009831 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009832 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009833}
9834
Jay Foad39c79802011-01-12 09:06:06 +00009835static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009836 QualType ResultTy,
9837 const Expr *Arg,
9838 bool SNaN,
9839 llvm::APFloat &Result) {
9840 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9841 if (!S) return false;
9842
9843 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9844
9845 llvm::APInt fill;
9846
9847 // Treat empty strings as if they were zero.
9848 if (S->getString().empty())
9849 fill = llvm::APInt(32, 0);
9850 else if (S->getString().getAsInteger(0, fill))
9851 return false;
9852
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009853 if (Context.getTargetInfo().isNan2008()) {
9854 if (SNaN)
9855 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9856 else
9857 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9858 } else {
9859 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9860 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9861 // a different encoding to what became a standard in 2008, and for pre-
9862 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9863 // sNaN. This is now known as "legacy NaN" encoding.
9864 if (SNaN)
9865 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9866 else
9867 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9868 }
9869
John McCall16291492010-02-28 13:00:19 +00009870 return true;
9871}
9872
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009873bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009874 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009875 default:
9876 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9877
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009878 case Builtin::BI__builtin_huge_val:
9879 case Builtin::BI__builtin_huge_valf:
9880 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009881 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009882 case Builtin::BI__builtin_inf:
9883 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009884 case Builtin::BI__builtin_infl:
9885 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009886 const llvm::fltSemantics &Sem =
9887 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009888 Result = llvm::APFloat::getInf(Sem);
9889 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009890 }
Mike Stump11289f42009-09-09 15:08:12 +00009891
John McCall16291492010-02-28 13:00:19 +00009892 case Builtin::BI__builtin_nans:
9893 case Builtin::BI__builtin_nansf:
9894 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009895 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009896 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9897 true, Result))
9898 return Error(E);
9899 return true;
John McCall16291492010-02-28 13:00:19 +00009900
Chris Lattner0b7282e2008-10-06 06:31:58 +00009901 case Builtin::BI__builtin_nan:
9902 case Builtin::BI__builtin_nanf:
9903 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009904 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009905 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009906 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009907 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9908 false, Result))
9909 return Error(E);
9910 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009911
9912 case Builtin::BI__builtin_fabs:
9913 case Builtin::BI__builtin_fabsf:
9914 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009915 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009916 if (!EvaluateFloat(E->getArg(0), Result, Info))
9917 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009918
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009919 if (Result.isNegative())
9920 Result.changeSign();
9921 return true;
9922
Richard Smith8889a3d2013-06-13 06:26:32 +00009923 // FIXME: Builtin::BI__builtin_powi
9924 // FIXME: Builtin::BI__builtin_powif
9925 // FIXME: Builtin::BI__builtin_powil
9926
Mike Stump11289f42009-09-09 15:08:12 +00009927 case Builtin::BI__builtin_copysign:
9928 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009929 case Builtin::BI__builtin_copysignl:
9930 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009931 APFloat RHS(0.);
9932 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9933 !EvaluateFloat(E->getArg(1), RHS, Info))
9934 return false;
9935 Result.copySign(RHS);
9936 return true;
9937 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009938 }
9939}
9940
John McCallb1fb0d32010-05-07 22:08:54 +00009941bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009942 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9943 ComplexValue CV;
9944 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9945 return false;
9946 Result = CV.FloatReal;
9947 return true;
9948 }
9949
9950 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009951}
9952
9953bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009954 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9955 ComplexValue CV;
9956 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9957 return false;
9958 Result = CV.FloatImag;
9959 return true;
9960 }
9961
Richard Smith4a678122011-10-24 18:44:57 +00009962 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009963 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9964 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009965 return true;
9966}
9967
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009968bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009969 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009970 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009971 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009972 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009973 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009974 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9975 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009976 Result.changeSign();
9977 return true;
9978 }
9979}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009980
Eli Friedman24c01542008-08-22 00:06:13 +00009981bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009982 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9983 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009984
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009985 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009986 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009987 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009988 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009989 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9990 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009991}
9992
9993bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9994 Result = E->getValue();
9995 return true;
9996}
9997
Peter Collingbournee9200682011-05-13 03:29:01 +00009998bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9999 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010000
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010001 switch (E->getCastKind()) {
10002 default:
Richard Smith11562c52011-10-28 17:51:58 +000010003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010004
10005 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010006 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010007 return EvaluateInteger(SubExpr, IntResult, Info) &&
10008 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10009 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010010 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010011
10012 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010013 if (!Visit(SubExpr))
10014 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010015 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10016 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010017 }
John McCalld7646252010-11-14 08:17:51 +000010018
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010019 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010020 ComplexValue V;
10021 if (!EvaluateComplex(SubExpr, V, Info))
10022 return false;
10023 Result = V.getComplexFloatReal();
10024 return true;
10025 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010026 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010027}
10028
Eli Friedman24c01542008-08-22 00:06:13 +000010029//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010030// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010031//===----------------------------------------------------------------------===//
10032
10033namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010034class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010035 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010036 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010037
Anders Carlsson537969c2008-11-16 20:27:53 +000010038public:
John McCall93d91dc2010-05-07 17:22:02 +000010039 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010040 : ExprEvaluatorBaseTy(info), Result(Result) {}
10041
Richard Smith2e312c82012-03-03 22:46:17 +000010042 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010043 Result.setFrom(V);
10044 return true;
10045 }
Mike Stump11289f42009-09-09 15:08:12 +000010046
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010047 bool ZeroInitialization(const Expr *E);
10048
Anders Carlsson537969c2008-11-16 20:27:53 +000010049 //===--------------------------------------------------------------------===//
10050 // Visitor Methods
10051 //===--------------------------------------------------------------------===//
10052
Peter Collingbournee9200682011-05-13 03:29:01 +000010053 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010054 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010055 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010056 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010057 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010058};
10059} // end anonymous namespace
10060
John McCall93d91dc2010-05-07 17:22:02 +000010061static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10062 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010063 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010064 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010065}
10066
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010067bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010068 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010069 if (ElemTy->isRealFloatingType()) {
10070 Result.makeComplexFloat();
10071 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10072 Result.FloatReal = Zero;
10073 Result.FloatImag = Zero;
10074 } else {
10075 Result.makeComplexInt();
10076 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10077 Result.IntReal = Zero;
10078 Result.IntImag = Zero;
10079 }
10080 return true;
10081}
10082
Peter Collingbournee9200682011-05-13 03:29:01 +000010083bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10084 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010085
10086 if (SubExpr->getType()->isRealFloatingType()) {
10087 Result.makeComplexFloat();
10088 APFloat &Imag = Result.FloatImag;
10089 if (!EvaluateFloat(SubExpr, Imag, Info))
10090 return false;
10091
10092 Result.FloatReal = APFloat(Imag.getSemantics());
10093 return true;
10094 } else {
10095 assert(SubExpr->getType()->isIntegerType() &&
10096 "Unexpected imaginary literal.");
10097
10098 Result.makeComplexInt();
10099 APSInt &Imag = Result.IntImag;
10100 if (!EvaluateInteger(SubExpr, Imag, Info))
10101 return false;
10102
10103 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10104 return true;
10105 }
10106}
10107
Peter Collingbournee9200682011-05-13 03:29:01 +000010108bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010109
John McCallfcef3cf2010-12-14 17:51:41 +000010110 switch (E->getCastKind()) {
10111 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010112 case CK_BaseToDerived:
10113 case CK_DerivedToBase:
10114 case CK_UncheckedDerivedToBase:
10115 case CK_Dynamic:
10116 case CK_ToUnion:
10117 case CK_ArrayToPointerDecay:
10118 case CK_FunctionToPointerDecay:
10119 case CK_NullToPointer:
10120 case CK_NullToMemberPointer:
10121 case CK_BaseToDerivedMemberPointer:
10122 case CK_DerivedToBaseMemberPointer:
10123 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010124 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010125 case CK_ConstructorConversion:
10126 case CK_IntegralToPointer:
10127 case CK_PointerToIntegral:
10128 case CK_PointerToBoolean:
10129 case CK_ToVoid:
10130 case CK_VectorSplat:
10131 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010132 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010133 case CK_IntegralToBoolean:
10134 case CK_IntegralToFloating:
10135 case CK_FloatingToIntegral:
10136 case CK_FloatingToBoolean:
10137 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010138 case CK_CPointerToObjCPointerCast:
10139 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010140 case CK_AnyPointerToBlockPointerCast:
10141 case CK_ObjCObjectLValueCast:
10142 case CK_FloatingComplexToReal:
10143 case CK_FloatingComplexToBoolean:
10144 case CK_IntegralComplexToReal:
10145 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010146 case CK_ARCProduceObject:
10147 case CK_ARCConsumeObject:
10148 case CK_ARCReclaimReturnedObject:
10149 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010150 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010151 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010152 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010153 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010154 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010155 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010156 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010157 case CK_FixedPointToBoolean:
John McCallfcef3cf2010-12-14 17:51:41 +000010158 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010159
John McCallfcef3cf2010-12-14 17:51:41 +000010160 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010161 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010162 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010164
10165 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010166 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010167 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010168 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010169
10170 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010171 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010172 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010173 return false;
10174
John McCallfcef3cf2010-12-14 17:51:41 +000010175 Result.makeComplexFloat();
10176 Result.FloatImag = APFloat(Real.getSemantics());
10177 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010178 }
10179
John McCallfcef3cf2010-12-14 17:51:41 +000010180 case CK_FloatingComplexCast: {
10181 if (!Visit(E->getSubExpr()))
10182 return false;
10183
10184 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10185 QualType From
10186 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10187
Richard Smith357362d2011-12-13 06:39:58 +000010188 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10189 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010190 }
10191
10192 case CK_FloatingComplexToIntegralComplex: {
10193 if (!Visit(E->getSubExpr()))
10194 return false;
10195
10196 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10197 QualType From
10198 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10199 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010200 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10201 To, Result.IntReal) &&
10202 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10203 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010204 }
10205
10206 case CK_IntegralRealToComplex: {
10207 APSInt &Real = Result.IntReal;
10208 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10209 return false;
10210
10211 Result.makeComplexInt();
10212 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10213 return true;
10214 }
10215
10216 case CK_IntegralComplexCast: {
10217 if (!Visit(E->getSubExpr()))
10218 return false;
10219
10220 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10221 QualType From
10222 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10223
Richard Smith911e1422012-01-30 22:27:01 +000010224 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10225 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010226 return true;
10227 }
10228
10229 case CK_IntegralComplexToFloatingComplex: {
10230 if (!Visit(E->getSubExpr()))
10231 return false;
10232
Ted Kremenek28831752012-08-23 20:46:57 +000010233 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010234 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010235 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010236 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010237 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10238 To, Result.FloatReal) &&
10239 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10240 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010241 }
10242 }
10243
10244 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010245}
10246
John McCall93d91dc2010-05-07 17:22:02 +000010247bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010248 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010249 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10250
Chandler Carrutha216cad2014-10-11 00:57:18 +000010251 // Track whether the LHS or RHS is real at the type system level. When this is
10252 // the case we can simplify our evaluation strategy.
10253 bool LHSReal = false, RHSReal = false;
10254
10255 bool LHSOK;
10256 if (E->getLHS()->getType()->isRealFloatingType()) {
10257 LHSReal = true;
10258 APFloat &Real = Result.FloatReal;
10259 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10260 if (LHSOK) {
10261 Result.makeComplexFloat();
10262 Result.FloatImag = APFloat(Real.getSemantics());
10263 }
10264 } else {
10265 LHSOK = Visit(E->getLHS());
10266 }
George Burgess IVa145e252016-05-25 22:38:36 +000010267 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010268 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010269
John McCall93d91dc2010-05-07 17:22:02 +000010270 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010271 if (E->getRHS()->getType()->isRealFloatingType()) {
10272 RHSReal = true;
10273 APFloat &Real = RHS.FloatReal;
10274 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10275 return false;
10276 RHS.makeComplexFloat();
10277 RHS.FloatImag = APFloat(Real.getSemantics());
10278 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010279 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010280
Chandler Carrutha216cad2014-10-11 00:57:18 +000010281 assert(!(LHSReal && RHSReal) &&
10282 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010283 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010284 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010285 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010286 if (Result.isComplexFloat()) {
10287 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10288 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010289 if (LHSReal)
10290 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10291 else if (!RHSReal)
10292 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10293 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010294 } else {
10295 Result.getComplexIntReal() += RHS.getComplexIntReal();
10296 Result.getComplexIntImag() += RHS.getComplexIntImag();
10297 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010298 break;
John McCalle3027922010-08-25 11:45:40 +000010299 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010300 if (Result.isComplexFloat()) {
10301 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10302 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010303 if (LHSReal) {
10304 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10305 Result.getComplexFloatImag().changeSign();
10306 } else if (!RHSReal) {
10307 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10308 APFloat::rmNearestTiesToEven);
10309 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010310 } else {
10311 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10312 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10313 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010314 break;
John McCalle3027922010-08-25 11:45:40 +000010315 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010316 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010317 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010318 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010319 // following naming scheme:
10320 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010321 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010322 APFloat &A = LHS.getComplexFloatReal();
10323 APFloat &B = LHS.getComplexFloatImag();
10324 APFloat &C = RHS.getComplexFloatReal();
10325 APFloat &D = RHS.getComplexFloatImag();
10326 APFloat &ResR = Result.getComplexFloatReal();
10327 APFloat &ResI = Result.getComplexFloatImag();
10328 if (LHSReal) {
10329 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10330 ResR = A * C;
10331 ResI = A * D;
10332 } else if (RHSReal) {
10333 ResR = C * A;
10334 ResI = C * B;
10335 } else {
10336 // In the fully general case, we need to handle NaNs and infinities
10337 // robustly.
10338 APFloat AC = A * C;
10339 APFloat BD = B * D;
10340 APFloat AD = A * D;
10341 APFloat BC = B * C;
10342 ResR = AC - BD;
10343 ResI = AD + BC;
10344 if (ResR.isNaN() && ResI.isNaN()) {
10345 bool Recalc = false;
10346 if (A.isInfinity() || B.isInfinity()) {
10347 A = APFloat::copySign(
10348 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10349 B = APFloat::copySign(
10350 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10351 if (C.isNaN())
10352 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10353 if (D.isNaN())
10354 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10355 Recalc = true;
10356 }
10357 if (C.isInfinity() || D.isInfinity()) {
10358 C = APFloat::copySign(
10359 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10360 D = APFloat::copySign(
10361 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10362 if (A.isNaN())
10363 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10364 if (B.isNaN())
10365 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10366 Recalc = true;
10367 }
10368 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10369 AD.isInfinity() || BC.isInfinity())) {
10370 if (A.isNaN())
10371 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10372 if (B.isNaN())
10373 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10374 if (C.isNaN())
10375 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10376 if (D.isNaN())
10377 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10378 Recalc = true;
10379 }
10380 if (Recalc) {
10381 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10382 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10383 }
10384 }
10385 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010386 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010387 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010388 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010389 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10390 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010391 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010392 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10393 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10394 }
10395 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010396 case BO_Div:
10397 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010398 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010399 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010400 // following naming scheme:
10401 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010402 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010403 APFloat &A = LHS.getComplexFloatReal();
10404 APFloat &B = LHS.getComplexFloatImag();
10405 APFloat &C = RHS.getComplexFloatReal();
10406 APFloat &D = RHS.getComplexFloatImag();
10407 APFloat &ResR = Result.getComplexFloatReal();
10408 APFloat &ResI = Result.getComplexFloatImag();
10409 if (RHSReal) {
10410 ResR = A / C;
10411 ResI = B / C;
10412 } else {
10413 if (LHSReal) {
10414 // No real optimizations we can do here, stub out with zero.
10415 B = APFloat::getZero(A.getSemantics());
10416 }
10417 int DenomLogB = 0;
10418 APFloat MaxCD = maxnum(abs(C), abs(D));
10419 if (MaxCD.isFinite()) {
10420 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010421 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10422 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010423 }
10424 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010425 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10426 APFloat::rmNearestTiesToEven);
10427 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10428 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010429 if (ResR.isNaN() && ResI.isNaN()) {
10430 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10431 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10432 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10433 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10434 D.isFinite()) {
10435 A = APFloat::copySign(
10436 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10437 B = APFloat::copySign(
10438 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10439 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10440 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10441 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10442 C = APFloat::copySign(
10443 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10444 D = APFloat::copySign(
10445 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10446 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10447 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10448 }
10449 }
10450 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010451 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010452 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10453 return Error(E, diag::note_expr_divide_by_zero);
10454
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010455 ComplexValue LHS = Result;
10456 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10457 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10458 Result.getComplexIntReal() =
10459 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10460 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10461 Result.getComplexIntImag() =
10462 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10463 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10464 }
10465 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010466 }
10467
John McCall93d91dc2010-05-07 17:22:02 +000010468 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010469}
10470
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010471bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10472 // Get the operand value into 'Result'.
10473 if (!Visit(E->getSubExpr()))
10474 return false;
10475
10476 switch (E->getOpcode()) {
10477 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010478 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010479 case UO_Extension:
10480 return true;
10481 case UO_Plus:
10482 // The result is always just the subexpr.
10483 return true;
10484 case UO_Minus:
10485 if (Result.isComplexFloat()) {
10486 Result.getComplexFloatReal().changeSign();
10487 Result.getComplexFloatImag().changeSign();
10488 }
10489 else {
10490 Result.getComplexIntReal() = -Result.getComplexIntReal();
10491 Result.getComplexIntImag() = -Result.getComplexIntImag();
10492 }
10493 return true;
10494 case UO_Not:
10495 if (Result.isComplexFloat())
10496 Result.getComplexFloatImag().changeSign();
10497 else
10498 Result.getComplexIntImag() = -Result.getComplexIntImag();
10499 return true;
10500 }
10501}
10502
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010503bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10504 if (E->getNumInits() == 2) {
10505 if (E->getType()->isComplexType()) {
10506 Result.makeComplexFloat();
10507 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10508 return false;
10509 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10510 return false;
10511 } else {
10512 Result.makeComplexInt();
10513 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10514 return false;
10515 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10516 return false;
10517 }
10518 return true;
10519 }
10520 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10521}
10522
Anders Carlsson537969c2008-11-16 20:27:53 +000010523//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010524// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10525// implicit conversion.
10526//===----------------------------------------------------------------------===//
10527
10528namespace {
10529class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010530 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010531 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010532 APValue &Result;
10533public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010534 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10535 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010536
10537 bool Success(const APValue &V, const Expr *E) {
10538 Result = V;
10539 return true;
10540 }
10541
10542 bool ZeroInitialization(const Expr *E) {
10543 ImplicitValueInitExpr VIE(
10544 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010545 // For atomic-qualified class (and array) types in C++, initialize the
10546 // _Atomic-wrapped subobject directly, in-place.
10547 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10548 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010549 }
10550
10551 bool VisitCastExpr(const CastExpr *E) {
10552 switch (E->getCastKind()) {
10553 default:
10554 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10555 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010556 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10557 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010558 }
10559 }
10560};
10561} // end anonymous namespace
10562
Richard Smith64cb9ca2017-02-22 22:09:50 +000010563static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10564 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010565 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010566 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010567}
10568
10569//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010570// Void expression evaluation, primarily for a cast to void on the LHS of a
10571// comma operator
10572//===----------------------------------------------------------------------===//
10573
10574namespace {
10575class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010576 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010577public:
10578 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10579
Richard Smith2e312c82012-03-03 22:46:17 +000010580 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010581
Richard Smith7cd577b2017-08-17 19:35:50 +000010582 bool ZeroInitialization(const Expr *E) { return true; }
10583
Richard Smith42d3af92011-12-07 00:43:50 +000010584 bool VisitCastExpr(const CastExpr *E) {
10585 switch (E->getCastKind()) {
10586 default:
10587 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10588 case CK_ToVoid:
10589 VisitIgnoredValue(E->getSubExpr());
10590 return true;
10591 }
10592 }
Hal Finkela8443c32014-07-17 14:49:58 +000010593
10594 bool VisitCallExpr(const CallExpr *E) {
10595 switch (E->getBuiltinCallee()) {
10596 default:
10597 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10598 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010599 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010600 // The argument is not evaluated!
10601 return true;
10602 }
10603 }
Richard Smith42d3af92011-12-07 00:43:50 +000010604};
10605} // end anonymous namespace
10606
10607static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10608 assert(E->isRValue() && E->getType()->isVoidType());
10609 return VoidExprEvaluator(Info).Visit(E);
10610}
10611
10612//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010613// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010614//===----------------------------------------------------------------------===//
10615
Richard Smith2e312c82012-03-03 22:46:17 +000010616static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010617 // In C, function designators are not lvalues, but we evaluate them as if they
10618 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010619 QualType T = E->getType();
10620 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010621 LValue LV;
10622 if (!EvaluateLValue(E, LV, Info))
10623 return false;
10624 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010625 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010626 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010627 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010628 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010629 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010630 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010631 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010632 LValue LV;
10633 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010634 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010635 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010636 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010637 llvm::APFloat F(0.0);
10638 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010639 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010640 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010641 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010642 ComplexValue C;
10643 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010644 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010645 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010646 } else if (T->isFixedPointType()) {
10647 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010648 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010649 MemberPtr P;
10650 if (!EvaluateMemberPointer(E, P, Info))
10651 return false;
10652 P.moveInto(Result);
10653 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010654 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010655 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010656 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010657 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010658 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010659 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010660 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010661 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010662 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010663 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010664 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010665 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010666 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010667 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010668 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010669 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010670 if (!EvaluateVoid(E, Info))
10671 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010672 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010673 QualType Unqual = T.getAtomicUnqualifiedType();
10674 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10675 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010676 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010677 if (!EvaluateAtomic(E, &LV, Value, Info))
10678 return false;
10679 } else {
10680 if (!EvaluateAtomic(E, nullptr, Result, Info))
10681 return false;
10682 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010683 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010684 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010685 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010686 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010688 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010689 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010690
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010691 return true;
10692}
10693
Richard Smithb228a862012-02-15 02:18:13 +000010694/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10695/// cases, the in-place evaluation is essential, since later initializers for
10696/// an object can indirectly refer to subobjects which were initialized earlier.
10697static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010698 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010699 assert(!E->isValueDependent());
10700
Richard Smith7525ff62013-05-09 07:14:00 +000010701 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010702 return false;
10703
10704 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010705 // Evaluate arrays and record types in-place, so that later initializers can
10706 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010707 QualType T = E->getType();
10708 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010709 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010710 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010711 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010712 else if (T->isAtomicType()) {
10713 QualType Unqual = T.getAtomicUnqualifiedType();
10714 if (Unqual->isArrayType() || Unqual->isRecordType())
10715 return EvaluateAtomic(E, &This, Result, Info);
10716 }
Richard Smithed5165f2011-11-04 05:33:44 +000010717 }
10718
10719 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010720 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010721}
10722
Richard Smithf57d8cb2011-12-09 22:58:01 +000010723/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10724/// lvalue-to-rvalue cast if it is an lvalue.
10725static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010726 if (E->getType().isNull())
10727 return false;
10728
Nick Lewyckyc190f962017-05-02 01:06:16 +000010729 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010730 return false;
10731
Richard Smith2e312c82012-03-03 22:46:17 +000010732 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010733 return false;
10734
10735 if (E->isGLValue()) {
10736 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010737 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010738 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010739 return false;
10740 }
10741
Richard Smith2e312c82012-03-03 22:46:17 +000010742 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010743 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010744}
Richard Smith11562c52011-10-28 17:51:58 +000010745
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010746static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010747 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010748 // Fast-path evaluations of integer literals, since we sometimes see files
10749 // containing vast quantities of these.
10750 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10751 Result.Val = APValue(APSInt(L->getValue(),
10752 L->getType()->isUnsignedIntegerType()));
10753 IsConst = true;
10754 return true;
10755 }
James Dennett0492ef02014-03-14 17:44:10 +000010756
10757 // This case should be rare, but we need to check it before we check on
10758 // the type below.
10759 if (Exp->getType().isNull()) {
10760 IsConst = false;
10761 return true;
10762 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010763
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010764 // FIXME: Evaluating values of large array and record types can cause
10765 // performance problems. Only do so in C++11 for now.
10766 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10767 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010768 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010769 IsConst = false;
10770 return true;
10771 }
10772 return false;
10773}
10774
Fangrui Song407659a2018-11-30 23:41:18 +000010775static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10776 Expr::SideEffectsKind SEK) {
10777 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10778 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10779}
10780
10781static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10782 const ASTContext &Ctx, EvalInfo &Info) {
10783 bool IsConst;
10784 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10785 return IsConst;
10786
10787 return EvaluateAsRValue(Info, E, Result.Val);
10788}
10789
10790static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10791 const ASTContext &Ctx,
10792 Expr::SideEffectsKind AllowSideEffects,
10793 EvalInfo &Info) {
10794 if (!E->getType()->isIntegralOrEnumerationType())
10795 return false;
10796
10797 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
10798 !ExprResult.Val.isInt() ||
10799 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10800 return false;
10801
10802 return true;
10803}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010804
Richard Smith7b553f12011-10-29 00:50:52 +000010805/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010806/// any crazy technique (that has nothing to do with language standards) that
10807/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010808/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10809/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000010810bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
10811 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010812 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000010813 Info.InConstantContext = InConstantContext;
10814 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000010815}
10816
Jay Foad39c79802011-01-12 09:06:06 +000010817bool Expr::EvaluateAsBooleanCondition(bool &Result,
10818 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010819 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010820 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010821 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010822}
10823
Fangrui Song407659a2018-11-30 23:41:18 +000010824bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000010825 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000010826 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10827 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000010828}
10829
Richard Trieube234c32016-04-21 21:04:55 +000010830bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10831 SideEffectsKind AllowSideEffects) const {
10832 if (!getType()->isRealFloatingType())
10833 return false;
10834
10835 EvalResult ExprResult;
10836 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010837 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010838 return false;
10839
10840 Result = ExprResult.Val.getFloat();
10841 return true;
10842}
10843
Jay Foad39c79802011-01-12 09:06:06 +000010844bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010845 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010846
John McCall45d55e42010-05-07 21:00:08 +000010847 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010848 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10849 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010850 Ctx.getLValueReferenceType(getType()), LV,
10851 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010852 return false;
10853
Richard Smith2e312c82012-03-03 22:46:17 +000010854 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010855 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010856}
10857
Reid Kleckner1a840d22018-05-10 18:57:35 +000010858bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10859 const ASTContext &Ctx) const {
10860 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10861 EvalInfo Info(Ctx, Result, EM);
10862 if (!::Evaluate(Result.Val, Info, this))
10863 return false;
10864
10865 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10866 Usage);
10867}
10868
Richard Smithd0b4dd62011-12-19 06:19:21 +000010869bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10870 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010871 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010872 // FIXME: Evaluating initializers for large array and record types can cause
10873 // performance problems. Only do so in C++11 for now.
10874 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010875 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010876 return false;
10877
Richard Smithd0b4dd62011-12-19 06:19:21 +000010878 Expr::EvalStatus EStatus;
10879 EStatus.Diag = &Notes;
10880
Richard Smith0c6124b2015-12-03 01:36:22 +000010881 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10882 ? EvalInfo::EM_ConstantExpression
10883 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010884 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000010885 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000010886
10887 LValue LVal;
10888 LVal.set(VD);
10889
Richard Smithfddd3842011-12-30 21:15:51 +000010890 // C++11 [basic.start.init]p2:
10891 // Variables with static storage duration or thread storage duration shall be
10892 // zero-initialized before any other initialization takes place.
10893 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010894 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010895 !VD->getType()->isReferenceType()) {
10896 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010897 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010898 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010899 return false;
10900 }
10901
Richard Smith7525ff62013-05-09 07:14:00 +000010902 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10903 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010904 EStatus.HasSideEffects)
10905 return false;
10906
10907 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10908 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010909}
10910
Richard Smith7b553f12011-10-29 00:50:52 +000010911/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10912/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010913bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010914 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000010915 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000010916 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010917}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010918
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010919APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010920 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000010921 EvalResult EVResult;
10922 EVResult.Diag = Diag;
10923 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
10924 Info.InConstantContext = true;
10925
10926 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010927 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010928 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000010929 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010930
Fangrui Song407659a2018-11-30 23:41:18 +000010931 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010932}
John McCall864e3962010-05-07 05:32:02 +000010933
David Bolvansky3b6ae572018-10-18 20:49:06 +000010934APSInt Expr::EvaluateKnownConstIntCheckOverflow(
10935 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000010936 EvalResult EVResult;
10937 EVResult.Diag = Diag;
10938 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
10939 Info.InConstantContext = true;
10940
10941 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000010942 (void)Result;
10943 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000010944 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000010945
Fangrui Song407659a2018-11-30 23:41:18 +000010946 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000010947}
10948
Richard Smithe9ff7702013-11-05 22:23:30 +000010949void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010950 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000010951 EvalResult EVResult;
10952 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
10953 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
10954 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010955 }
10956}
10957
Richard Smithe6c01442013-06-05 00:46:14 +000010958bool Expr::EvalResult::isGlobalLValue() const {
10959 assert(Val.isLValue());
10960 return IsGlobalLValue(Val.getLValueBase());
10961}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010962
10963
John McCall864e3962010-05-07 05:32:02 +000010964/// isIntegerConstantExpr - this recursive routine will test if an expression is
10965/// an integer constant expression.
10966
10967/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10968/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010969
10970// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010971// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10972// and a (possibly null) SourceLocation indicating the location of the problem.
10973//
John McCall864e3962010-05-07 05:32:02 +000010974// Note that to reduce code duplication, this helper does no evaluation
10975// itself; the caller checks whether the expression is evaluatable, and
10976// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010977// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010978
Dan Gohman28ade552010-07-26 21:25:24 +000010979namespace {
10980
Richard Smith9e575da2012-12-28 13:25:52 +000010981enum ICEKind {
10982 /// This expression is an ICE.
10983 IK_ICE,
10984 /// This expression is not an ICE, but if it isn't evaluated, it's
10985 /// a legal subexpression for an ICE. This return value is used to handle
10986 /// the comma operator in C99 mode, and non-constant subexpressions.
10987 IK_ICEIfUnevaluated,
10988 /// This expression is not an ICE, and is not a legal subexpression for one.
10989 IK_NotICE
10990};
10991
John McCall864e3962010-05-07 05:32:02 +000010992struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010993 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010994 SourceLocation Loc;
10995
Richard Smith9e575da2012-12-28 13:25:52 +000010996 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010997};
10998
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010999}
Dan Gohman28ade552010-07-26 21:25:24 +000011000
Richard Smith9e575da2012-12-28 13:25:52 +000011001static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11002
11003static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011004
Craig Toppera31a8822013-08-22 07:09:37 +000011005static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011006 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011007 Expr::EvalStatus Status;
11008 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11009
11010 Info.InConstantContext = true;
11011 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011012 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011013 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011014
John McCall864e3962010-05-07 05:32:02 +000011015 return NoDiag();
11016}
11017
Craig Toppera31a8822013-08-22 07:09:37 +000011018static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011019 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011020 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011021 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011022
11023 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011024#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011025#define STMT(Node, Base) case Expr::Node##Class:
11026#define EXPR(Node, Base)
11027#include "clang/AST/StmtNodes.inc"
11028 case Expr::PredefinedExprClass:
11029 case Expr::FloatingLiteralClass:
11030 case Expr::ImaginaryLiteralClass:
11031 case Expr::StringLiteralClass:
11032 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011033 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011034 case Expr::MemberExprClass:
11035 case Expr::CompoundAssignOperatorClass:
11036 case Expr::CompoundLiteralExprClass:
11037 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011038 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011039 case Expr::ArrayInitLoopExprClass:
11040 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011041 case Expr::NoInitExprClass:
11042 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011043 case Expr::ImplicitValueInitExprClass:
11044 case Expr::ParenListExprClass:
11045 case Expr::VAArgExprClass:
11046 case Expr::AddrLabelExprClass:
11047 case Expr::StmtExprClass:
11048 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011049 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011050 case Expr::CXXDynamicCastExprClass:
11051 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011052 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011053 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011054 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011055 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011056 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011057 case Expr::CXXThisExprClass:
11058 case Expr::CXXThrowExprClass:
11059 case Expr::CXXNewExprClass:
11060 case Expr::CXXDeleteExprClass:
11061 case Expr::CXXPseudoDestructorExprClass:
11062 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011063 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011064 case Expr::DependentScopeDeclRefExprClass:
11065 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011066 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011067 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011068 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011069 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011070 case Expr::CXXTemporaryObjectExprClass:
11071 case Expr::CXXUnresolvedConstructExprClass:
11072 case Expr::CXXDependentScopeMemberExprClass:
11073 case Expr::UnresolvedMemberExprClass:
11074 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011075 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011076 case Expr::ObjCArrayLiteralClass:
11077 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011078 case Expr::ObjCEncodeExprClass:
11079 case Expr::ObjCMessageExprClass:
11080 case Expr::ObjCSelectorExprClass:
11081 case Expr::ObjCProtocolExprClass:
11082 case Expr::ObjCIvarRefExprClass:
11083 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011084 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011085 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011086 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011087 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011088 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011089 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011090 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011091 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011092 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011093 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011094 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011095 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011096 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011097 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011098 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011099 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011100 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011101 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011102 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011103 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011104 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011105 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011106
Richard Smithf137f932014-01-25 20:50:08 +000011107 case Expr::InitListExprClass: {
11108 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11109 // form "T x = { a };" is equivalent to "T x = a;".
11110 // Unless we're initializing a reference, T is a scalar as it is known to be
11111 // of integral or enumeration type.
11112 if (E->isRValue())
11113 if (cast<InitListExpr>(E)->getNumInits() == 1)
11114 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011115 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011116 }
11117
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011118 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011119 case Expr::GNUNullExprClass:
11120 // GCC considers the GNU __null value to be an integral constant expression.
11121 return NoDiag();
11122
John McCall7c454bb2011-07-15 05:09:51 +000011123 case Expr::SubstNonTypeTemplateParmExprClass:
11124 return
11125 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11126
Bill Wendling7c44da22018-10-31 03:48:47 +000011127 case Expr::ConstantExprClass:
11128 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11129
John McCall864e3962010-05-07 05:32:02 +000011130 case Expr::ParenExprClass:
11131 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011132 case Expr::GenericSelectionExprClass:
11133 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011134 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011135 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011136 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011137 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011138 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011139 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011140 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011141 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011142 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011143 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011144 return NoDiag();
11145 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011146 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011147 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11148 // constant expressions, but they can never be ICEs because an ICE cannot
11149 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011150 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011151 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011152 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011153 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011154 }
Richard Smith6365c912012-02-24 22:12:32 +000011155 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011156 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11157 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011158 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011159 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011160 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011161 // Parameter variables are never constants. Without this check,
11162 // getAnyInitializer() can find a default argument, which leads
11163 // to chaos.
11164 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011165 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011166
11167 // C++ 7.1.5.1p2
11168 // A variable of non-volatile const-qualified integral or enumeration
11169 // type initialized by an ICE can be used in ICEs.
11170 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011171 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011172 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011173
Richard Smithd0b4dd62011-12-19 06:19:21 +000011174 const VarDecl *VD;
11175 // Look for a declaration of this variable that has an initializer, and
11176 // check whether it is an ICE.
11177 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11178 return NoDiag();
11179 else
Richard Smith9e575da2012-12-28 13:25:52 +000011180 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011181 }
11182 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011183 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011184 }
John McCall864e3962010-05-07 05:32:02 +000011185 case Expr::UnaryOperatorClass: {
11186 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11187 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011188 case UO_PostInc:
11189 case UO_PostDec:
11190 case UO_PreInc:
11191 case UO_PreDec:
11192 case UO_AddrOf:
11193 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011194 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011195 // C99 6.6/3 allows increment and decrement within unevaluated
11196 // subexpressions of constant expressions, but they can never be ICEs
11197 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011198 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011199 case UO_Extension:
11200 case UO_LNot:
11201 case UO_Plus:
11202 case UO_Minus:
11203 case UO_Not:
11204 case UO_Real:
11205 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011206 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011207 }
Reid Klecknere540d972018-11-01 17:51:48 +000011208 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011209 }
11210 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011211 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11212 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11213 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11214 // compliance: we should warn earlier for offsetof expressions with
11215 // array subscripts that aren't ICEs, and if the array subscripts
11216 // are ICEs, the value of the offsetof must be an integer constant.
11217 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011218 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011219 case Expr::UnaryExprOrTypeTraitExprClass: {
11220 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11221 if ((Exp->getKind() == UETT_SizeOf) &&
11222 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011223 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011224 return NoDiag();
11225 }
11226 case Expr::BinaryOperatorClass: {
11227 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11228 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011229 case BO_PtrMemD:
11230 case BO_PtrMemI:
11231 case BO_Assign:
11232 case BO_MulAssign:
11233 case BO_DivAssign:
11234 case BO_RemAssign:
11235 case BO_AddAssign:
11236 case BO_SubAssign:
11237 case BO_ShlAssign:
11238 case BO_ShrAssign:
11239 case BO_AndAssign:
11240 case BO_XorAssign:
11241 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011242 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11243 // constant expressions, but they can never be ICEs because an ICE cannot
11244 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011245 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011246
John McCalle3027922010-08-25 11:45:40 +000011247 case BO_Mul:
11248 case BO_Div:
11249 case BO_Rem:
11250 case BO_Add:
11251 case BO_Sub:
11252 case BO_Shl:
11253 case BO_Shr:
11254 case BO_LT:
11255 case BO_GT:
11256 case BO_LE:
11257 case BO_GE:
11258 case BO_EQ:
11259 case BO_NE:
11260 case BO_And:
11261 case BO_Xor:
11262 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011263 case BO_Comma:
11264 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011265 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11266 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011267 if (Exp->getOpcode() == BO_Div ||
11268 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011269 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011270 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011271 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011272 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011273 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011274 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011275 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011276 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011277 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011278 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011279 }
11280 }
11281 }
John McCalle3027922010-08-25 11:45:40 +000011282 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011283 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011284 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11285 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011286 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011287 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011288 } else {
11289 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011290 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011291 }
11292 }
Richard Smith9e575da2012-12-28 13:25:52 +000011293 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011294 }
John McCalle3027922010-08-25 11:45:40 +000011295 case BO_LAnd:
11296 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011297 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11298 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011299 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011300 // Rare case where the RHS has a comma "side-effect"; we need
11301 // to actually check the condition to see whether the side
11302 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011303 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011304 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011305 return RHSResult;
11306 return NoDiag();
11307 }
11308
Richard Smith9e575da2012-12-28 13:25:52 +000011309 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011310 }
11311 }
Reid Klecknere540d972018-11-01 17:51:48 +000011312 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011313 }
11314 case Expr::ImplicitCastExprClass:
11315 case Expr::CStyleCastExprClass:
11316 case Expr::CXXFunctionalCastExprClass:
11317 case Expr::CXXStaticCastExprClass:
11318 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011319 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011320 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011321 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011322 if (isa<ExplicitCastExpr>(E)) {
11323 if (const FloatingLiteral *FL
11324 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11325 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11326 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11327 APSInt IgnoredVal(DestWidth, !DestSigned);
11328 bool Ignored;
11329 // If the value does not fit in the destination type, the behavior is
11330 // undefined, so we are not required to treat it as a constant
11331 // expression.
11332 if (FL->getValue().convertToInteger(IgnoredVal,
11333 llvm::APFloat::rmTowardZero,
11334 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011335 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011336 return NoDiag();
11337 }
11338 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011339 switch (cast<CastExpr>(E)->getCastKind()) {
11340 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011341 case CK_AtomicToNonAtomic:
11342 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011343 case CK_NoOp:
11344 case CK_IntegralToBoolean:
11345 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011346 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011347 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011348 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011349 }
John McCall864e3962010-05-07 05:32:02 +000011350 }
John McCallc07a0c72011-02-17 10:25:35 +000011351 case Expr::BinaryConditionalOperatorClass: {
11352 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11353 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011354 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011355 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011356 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11357 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11358 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011359 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011360 return FalseResult;
11361 }
John McCall864e3962010-05-07 05:32:02 +000011362 case Expr::ConditionalOperatorClass: {
11363 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11364 // If the condition (ignoring parens) is a __builtin_constant_p call,
11365 // then only the true side is actually considered in an integer constant
11366 // expression, and it is fully evaluated. This is an important GNU
11367 // extension. See GCC PR38377 for discussion.
11368 if (const CallExpr *CallCE
11369 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011370 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011371 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011372 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011373 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011374 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011375
Richard Smithf57d8cb2011-12-09 22:58:01 +000011376 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11377 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011378
Richard Smith9e575da2012-12-28 13:25:52 +000011379 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011380 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011381 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011382 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011383 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011384 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011385 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011386 return NoDiag();
11387 // Rare case where the diagnostics depend on which side is evaluated
11388 // Note that if we get here, CondResult is 0, and at least one of
11389 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011390 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011391 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011392 return TrueResult;
11393 }
11394 case Expr::CXXDefaultArgExprClass:
11395 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011396 case Expr::CXXDefaultInitExprClass:
11397 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011398 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011399 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011400 }
11401 }
11402
David Blaikiee4d798f2012-01-20 21:50:17 +000011403 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011404}
11405
Richard Smithf57d8cb2011-12-09 22:58:01 +000011406/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011407static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011408 const Expr *E,
11409 llvm::APSInt *Value,
11410 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011411 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011412 if (Loc) *Loc = E->getExprLoc();
11413 return false;
11414 }
11415
Richard Smith66e05fe2012-01-18 05:21:49 +000011416 APValue Result;
11417 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011418 return false;
11419
Richard Smith98710fc2014-11-13 23:03:19 +000011420 if (!Result.isInt()) {
11421 if (Loc) *Loc = E->getExprLoc();
11422 return false;
11423 }
11424
Richard Smith66e05fe2012-01-18 05:21:49 +000011425 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011426 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011427}
11428
Craig Toppera31a8822013-08-22 07:09:37 +000011429bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11430 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011431 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011432 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011433
Richard Smith9e575da2012-12-28 13:25:52 +000011434 ICEDiag D = CheckICE(this, Ctx);
11435 if (D.Kind != IK_ICE) {
11436 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011437 return false;
11438 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011439 return true;
11440}
11441
Craig Toppera31a8822013-08-22 07:09:37 +000011442bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011443 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011444 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011445 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11446
11447 if (!isIntegerConstantExpr(Ctx, Loc))
11448 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011449
Richard Smith5c40f092015-12-04 03:00:44 +000011450 // The only possible side-effects here are due to UB discovered in the
11451 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11452 // required to treat the expression as an ICE, so we produce the folded
11453 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011454 EvalResult ExprResult;
11455 Expr::EvalStatus Status;
11456 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11457 Info.InConstantContext = true;
11458
11459 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011460 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011461
11462 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011463 return true;
11464}
Richard Smith66e05fe2012-01-18 05:21:49 +000011465
Craig Toppera31a8822013-08-22 07:09:37 +000011466bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011467 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011468}
11469
Craig Toppera31a8822013-08-22 07:09:37 +000011470bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011471 SourceLocation *Loc) const {
11472 // We support this checking in C++98 mode in order to diagnose compatibility
11473 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011474 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011475
Richard Smith98a0a492012-02-14 21:38:30 +000011476 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011477 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011478 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011479 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011480 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011481
11482 APValue Scratch;
11483 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11484
11485 if (!Diags.empty()) {
11486 IsConstExpr = false;
11487 if (Loc) *Loc = Diags[0].first;
11488 } else if (!IsConstExpr) {
11489 // FIXME: This shouldn't happen.
11490 if (Loc) *Loc = getExprLoc();
11491 }
11492
11493 return IsConstExpr;
11494}
Richard Smith253c2a32012-01-27 01:14:48 +000011495
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011496bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11497 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011498 ArrayRef<const Expr*> Args,
11499 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011500 Expr::EvalStatus Status;
11501 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11502
George Burgess IV177399e2017-01-09 04:12:14 +000011503 LValue ThisVal;
11504 const LValue *ThisPtr = nullptr;
11505 if (This) {
11506#ifndef NDEBUG
11507 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11508 assert(MD && "Don't provide `this` for non-methods.");
11509 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11510#endif
11511 if (EvaluateObjectArgument(Info, This, ThisVal))
11512 ThisPtr = &ThisVal;
11513 if (Info.EvalStatus.HasSideEffects)
11514 return false;
11515 }
11516
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011517 ArgVector ArgValues(Args.size());
11518 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11519 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011520 if ((*I)->isValueDependent() ||
11521 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011522 // If evaluation fails, throw away the argument entirely.
11523 ArgValues[I - Args.begin()] = APValue();
11524 if (Info.EvalStatus.HasSideEffects)
11525 return false;
11526 }
11527
11528 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011529 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011530 ArgValues.data());
11531 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11532}
11533
Richard Smith253c2a32012-01-27 01:14:48 +000011534bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011535 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011536 PartialDiagnosticAt> &Diags) {
11537 // FIXME: It would be useful to check constexpr function templates, but at the
11538 // moment the constant expression evaluator cannot cope with the non-rigorous
11539 // ASTs which we build for dependent expressions.
11540 if (FD->isDependentContext())
11541 return true;
11542
11543 Expr::EvalStatus Status;
11544 Status.Diag = &Diags;
11545
Richard Smith6d4c6582013-11-05 22:18:15 +000011546 EvalInfo Info(FD->getASTContext(), Status,
11547 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011548 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011549
11550 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011551 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011552
Richard Smith7525ff62013-05-09 07:14:00 +000011553 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011554 // is a temporary being used as the 'this' pointer.
11555 LValue This;
11556 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011557 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011558
Richard Smith253c2a32012-01-27 01:14:48 +000011559 ArrayRef<const Expr*> Args;
11560
Richard Smith2e312c82012-03-03 22:46:17 +000011561 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011562 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11563 // Evaluate the call as a constant initializer, to allow the construction
11564 // of objects of non-literal types.
11565 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011566 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11567 } else {
11568 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011569 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011570 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011571 }
Richard Smith253c2a32012-01-27 01:14:48 +000011572
11573 return Diags.empty();
11574}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011575
11576bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11577 const FunctionDecl *FD,
11578 SmallVectorImpl<
11579 PartialDiagnosticAt> &Diags) {
11580 Expr::EvalStatus Status;
11581 Status.Diag = &Diags;
11582
11583 EvalInfo Info(FD->getASTContext(), Status,
11584 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11585
11586 // Fabricate a call stack frame to give the arguments a plausible cover story.
11587 ArrayRef<const Expr*> Args;
11588 ArgVector ArgValues(0);
11589 bool Success = EvaluateArgs(Args, ArgValues, Info);
11590 (void)Success;
11591 assert(Success &&
11592 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011593 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011594
11595 APValue ResultScratch;
11596 Evaluate(ResultScratch, Info, E);
11597 return Diags.empty();
11598}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011599
11600bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11601 unsigned Type) const {
11602 if (!getType()->isPointerType())
11603 return false;
11604
11605 Expr::EvalStatus Status;
11606 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011607 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011608}