blob: c0c807b11c9506a86e745c3a6e4450b7a53e0ec2 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000037#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000038#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000040#include "clang/AST/CurrentSourceLocExprScope.h"
Richard Smith921f1322019-05-13 23:35:21 +000041#include "clang/AST/CXXInheritance.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000042#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000043#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000044#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000045#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000046#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000048#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000049#include "clang/Basic/TargetInfo.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000050#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000051#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000052#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000053#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000054#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000055
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000056#define DEBUG_TYPE "exprconstant"
57
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000059using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000060using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062static bool IsGlobalLValue(APValue::LValueBase B);
63
John McCall93d91dc2010-05-07 17:22:02 +000064namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000065 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000066 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000067 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000068
Eric Fiselier708afb52019-05-16 21:04:15 +000069 using SourceLocExprScopeGuard =
70 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
71
Richard Smithb228a862012-02-15 02:18:13 +000072 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000073 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000074 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000075 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000076 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000077 //
78 // extern int arr[]; void f() { extern int arr[3]; };
79 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000080 //
81 // For now, we take the array bound from the most recent declaration.
82 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
83 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
84 QualType T = Redecl->getType();
85 if (!T->isIncompleteArrayType())
86 return T;
87 }
88 return D->getType();
89 }
Richard Smith84401042013-06-03 05:03:02 +000090
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000091 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000092 return B.getTypeInfoType();
93
Richard Smith84401042013-06-03 05:03:02 +000094 const Expr *Base = B.get<const Expr*>();
95
96 // For a materialized temporary, the type of the temporary we materialized
97 // may not be the type of the expression.
98 if (const MaterializeTemporaryExpr *MTE =
99 dyn_cast<MaterializeTemporaryExpr>(Base)) {
100 SmallVector<const Expr *, 2> CommaLHSs;
101 SmallVector<SubobjectAdjustment, 2> Adjustments;
102 const Expr *Temp = MTE->GetTemporaryExpr();
103 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
104 Adjustments);
105 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000106 // for it directly. Otherwise use the type after adjustment.
107 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000108 return Inner->getType();
109 }
110
111 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000112 }
113
Richard Smithd62306a2011-11-10 06:34:14 +0000114 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000117 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().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) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000122 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().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 Smith5b5e27a2019-05-10 20:05:31 +0000127 return E.getAsBaseOrMember().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 Smithdebad642019-05-12 09:39:08 +0000225 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 Smith31c69a32019-05-21 23:15:20 +0000294 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
295 unsigned NewLength) {
296 if (Invalid)
297 return;
298
299 assert(Base && "cannot truncate path for null pointer");
300 assert(NewLength <= Entries.size() && "not a truncation");
301
302 if (NewLength == Entries.size())
303 return;
304 Entries.resize(NewLength);
305
306 bool IsArray = false;
307 bool FirstIsUnsizedArray = false;
308 MostDerivedPathLength = findMostDerivedSubobject(
309 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
310 FirstIsUnsizedArray);
311 MostDerivedIsArrayElement = IsArray;
312 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
313 }
314
Richard Smith96e0c102011-11-04 02:25:55 +0000315 void setInvalid() {
316 Invalid = true;
317 Entries.clear();
318 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000319
George Burgess IVe3763372016-12-22 02:50:20 +0000320 /// Determine whether the most derived subobject is an array without a
321 /// known bound.
322 bool isMostDerivedAnUnsizedArray() const {
323 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000324 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000325 }
326
327 /// Determine what the most derived array's size is. Results in an assertion
328 /// failure if the most derived array lacks a size.
329 uint64_t getMostDerivedArraySize() const {
330 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
331 return MostDerivedArraySize;
332 }
333
Richard Smitha8105bc2012-01-06 16:39:00 +0000334 /// Determine whether this is a one-past-the-end pointer.
335 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000336 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000337 if (IsOnePastTheEnd)
338 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000339 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000340 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
341 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000342 return true;
343 return false;
344 }
345
Richard Smith06f71b52018-08-04 00:57:17 +0000346 /// Get the range of valid index adjustments in the form
347 /// {maximum value that can be subtracted from this pointer,
348 /// maximum value that can be added to this pointer}
349 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
350 if (Invalid || isMostDerivedAnUnsizedArray())
351 return {0, 0};
352
353 // [expr.add]p4: For the purposes of these operators, a pointer to a
354 // nonarray object behaves the same as a pointer to the first element of
355 // an array of length one with the type of the object as its element type.
356 bool IsArray = MostDerivedPathLength == Entries.size() &&
357 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000358 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
359 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000360 uint64_t ArraySize =
361 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
362 return {ArrayIndex, ArraySize - ArrayIndex};
363 }
364
Richard Smitha8105bc2012-01-06 16:39:00 +0000365 /// Check that this refers to a valid subobject.
366 bool isValidSubobject() const {
367 if (Invalid)
368 return false;
369 return !isOnePastTheEnd();
370 }
371 /// Check that this refers to a valid subobject, and if not, produce a
372 /// relevant diagnostic and set the designator as invalid.
373 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
374
Richard Smith06f71b52018-08-04 00:57:17 +0000375 /// Get the type of the designated object.
376 QualType getType(ASTContext &Ctx) const {
377 assert(!Invalid && "invalid designator has no subobject type");
378 return MostDerivedPathLength == Entries.size()
379 ? MostDerivedType
380 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
381 }
382
Richard Smitha8105bc2012-01-06 16:39:00 +0000383 /// Update this designator to refer to the first element within this array.
384 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000385 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000386
387 // This is a most-derived object.
388 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000389 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 MostDerivedArraySize = CAT->getSize().getZExtValue();
391 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000392 }
George Burgess IVe3763372016-12-22 02:50:20 +0000393 /// Update this designator to refer to the first element within the array of
394 /// elements of type T. This is an array of unknown size.
395 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000396 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000397
398 MostDerivedType = ElemTy;
399 MostDerivedIsArrayElement = true;
400 // The value in MostDerivedArraySize is undefined in this case. So, set it
401 // to an arbitrary value that's likely to loudly break things if it's
402 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000403 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000404 MostDerivedPathLength = Entries.size();
405 }
Richard Smith96e0c102011-11-04 02:25:55 +0000406 /// Update this designator to refer to the given base or member of this
407 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000408 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000409 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000410
411 // If this isn't a base class, it's a new most-derived object.
412 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
413 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000414 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000415 MostDerivedArraySize = 0;
416 MostDerivedPathLength = Entries.size();
417 }
Richard Smith96e0c102011-11-04 02:25:55 +0000418 }
Richard Smith66c96992012-02-18 22:04:06 +0000419 /// Update this designator to refer to the given complex component.
420 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000421 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000422
423 // This is technically a most-derived object, though in practice this
424 // is unlikely to matter.
425 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000426 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000427 MostDerivedArraySize = 2;
428 MostDerivedPathLength = Entries.size();
429 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000430 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000431 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
432 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000433 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000434 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
435 if (Invalid || !N) return;
436 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
437 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000438 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000439 // Can't verify -- trust that the user is doing the right thing (or if
440 // not, trust that the caller will catch the bad behavior).
441 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000442 Entries.back() = PathEntry::ArrayIndex(
443 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000444 return;
445 }
446
447 // [expr.add]p4: For the purposes of these operators, a pointer to a
448 // nonarray object behaves the same as a pointer to the first element of
449 // an array of length one with the type of the object as its element type.
450 bool IsArray = MostDerivedPathLength == Entries.size() &&
451 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000452 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
453 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000454 uint64_t ArraySize =
455 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
456
457 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
458 // Calculate the actual index in a wide enough type, so we can include
459 // it in the note.
460 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
461 (llvm::APInt&)N += ArrayIndex;
462 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
463 diagnosePointerArithmetic(Info, E, N);
464 setInvalid();
465 return;
466 }
467
468 ArrayIndex += TruncatedN;
469 assert(ArrayIndex <= ArraySize &&
470 "bounds check succeeded for out-of-bounds index");
471
472 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000473 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000474 else
475 IsOnePastTheEnd = (ArrayIndex != 0);
476 }
Richard Smith96e0c102011-11-04 02:25:55 +0000477 };
478
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// A stack frame in the constexpr call stack.
480 struct CallStackFrame {
481 EvalInfo &Info;
482
483 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000484 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000485
Richard Smithf6f003a2011-12-16 19:06:07 +0000486 /// Callee - The function which was called.
487 const FunctionDecl *Callee;
488
Richard Smithd62306a2011-11-10 06:34:14 +0000489 /// This - The binding for the this pointer in this call, if any.
490 const LValue *This;
491
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000492 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000493 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000494 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000495
Eric Fiselier708afb52019-05-16 21:04:15 +0000496 /// Source location information about the default argument or default
497 /// initializer expression we're evaluating, if any.
498 CurrentSourceLocExprScope CurSourceLocExprScope;
499
Eli Friedman4830ec82012-06-25 21:21:08 +0000500 // Note that we intentionally use std::map here so that references to
501 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000502 typedef std::pair<const void *, unsigned> MapKeyTy;
503 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000504 /// Temporaries - Temporary lvalues materialized within this stack frame.
505 MapTy Temporaries;
506
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000507 /// CallLoc - The location of the call expression for this call.
508 SourceLocation CallLoc;
509
510 /// Index - The call index of this call.
511 unsigned Index;
512
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000513 /// The stack of integers for tracking version numbers for temporaries.
514 SmallVector<unsigned, 2> TempVersionStack = {1};
515 unsigned CurTempVersion = TempVersionStack.back();
516
517 unsigned getTempVersion() const { return TempVersionStack.back(); }
518
519 void pushTempVersion() {
520 TempVersionStack.push_back(++CurTempVersion);
521 }
522
523 void popTempVersion() {
524 TempVersionStack.pop_back();
525 }
526
Faisal Vali051e3a22017-02-16 04:12:21 +0000527 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000528 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000529 // (We should cache this map rather than recomputing it repeatedly.)
530 // But let's try this and see how it goes; we can look into caching the map
531 // as a later change.
532
533 /// LambdaCaptureFields - Mapping from captured variables/this to
534 /// corresponding data members in the closure class.
535 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
536 FieldDecl *LambdaThisCaptureField;
537
Richard Smithf6f003a2011-12-16 19:06:07 +0000538 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
539 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000540 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000541 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000542
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000543 // Return the temporary for Key whose version number is Version.
544 APValue *getTemporary(const void *Key, unsigned Version) {
545 MapKeyTy KV(Key, Version);
546 auto LB = Temporaries.lower_bound(KV);
547 if (LB != Temporaries.end() && LB->first == KV)
548 return &LB->second;
549 // Pair (Key,Version) wasn't found in the map. Check that no elements
550 // in the map have 'Key' as their key.
551 assert((LB == Temporaries.end() || LB->first.first != Key) &&
552 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
553 "Element with key 'Key' found in map");
554 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000556
557 // Return the current temporary for Key in the map.
558 APValue *getCurrentTemporary(const void *Key) {
559 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
560 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
561 return &std::prev(UB)->second;
562 return nullptr;
563 }
564
565 // Return the version number of the current temporary for Key.
566 unsigned getCurrentTemporaryVersion(const void *Key) const {
567 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
568 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
569 return std::prev(UB)->first.second;
570 return 0;
571 }
572
Richard Smith08d6a2c2013-07-24 07:11:57 +0000573 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000574 };
575
Richard Smith852c9db2013-04-20 22:23:05 +0000576 /// Temporarily override 'this'.
577 class ThisOverrideRAII {
578 public:
579 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
580 : Frame(Frame), OldThis(Frame.This) {
581 if (Enable)
582 Frame.This = NewThis;
583 }
584 ~ThisOverrideRAII() {
585 Frame.This = OldThis;
586 }
587 private:
588 CallStackFrame &Frame;
589 const LValue *OldThis;
590 };
591
Richard Smith92b1ce02011-12-12 09:28:41 +0000592 /// A partial diagnostic which we might know in advance that we are not going
593 /// to emit.
594 class OptionalDiagnostic {
595 PartialDiagnostic *Diag;
596
597 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000598 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
599 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000600
601 template<typename T>
602 OptionalDiagnostic &operator<<(const T &v) {
603 if (Diag)
604 *Diag << v;
605 return *this;
606 }
Richard Smithfe800032012-01-31 04:08:20 +0000607
608 OptionalDiagnostic &operator<<(const APSInt &I) {
609 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000611 I.toString(Buffer);
612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
616
617 OptionalDiagnostic &operator<<(const APFloat &F) {
618 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000619 // FIXME: Force the precision of the source value down so we don't
620 // print digits which are usually useless (we don't really care here if
621 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000622 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000623 // representation which rounds to the correct value, but it's a bit
624 // tricky to implement.
625 unsigned precision =
626 llvm::APFloat::semanticsPrecision(F.getSemantics());
627 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000628 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000629 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000630 *Diag << StringRef(Buffer.data(), Buffer.size());
631 }
632 return *this;
633 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000634
635 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
636 if (Diag) {
637 SmallVector<char, 32> Buffer;
638 FX.toString(Buffer);
639 *Diag << StringRef(Buffer.data(), Buffer.size());
640 }
641 return *this;
642 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000643 };
644
Richard Smith08d6a2c2013-07-24 07:11:57 +0000645 /// A cleanup, and a flag indicating whether it is lifetime-extended.
646 class Cleanup {
647 llvm::PointerIntPair<APValue*, 1, bool> Value;
648
649 public:
650 Cleanup(APValue *Val, bool IsLifetimeExtended)
651 : Value(Val, IsLifetimeExtended) {}
652
653 bool isLifetimeExtended() const { return Value.getInt(); }
654 void endLifetime() {
655 *Value.getPointer() = APValue();
656 }
657 };
658
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000659 /// A reference to an object whose construction we are currently evaluating.
660 struct ObjectUnderConstruction {
661 APValue::LValueBase Base;
662 ArrayRef<APValue::LValuePathEntry> Path;
663 friend bool operator==(const ObjectUnderConstruction &LHS,
664 const ObjectUnderConstruction &RHS) {
665 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
666 }
667 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
668 return llvm::hash_combine(Obj.Base, Obj.Path);
669 }
670 };
671 enum class ConstructionPhase { None, Bases, AfterBases };
672}
673
674namespace llvm {
675template<> struct DenseMapInfo<ObjectUnderConstruction> {
676 using Base = DenseMapInfo<APValue::LValueBase>;
677 static ObjectUnderConstruction getEmptyKey() {
678 return {Base::getEmptyKey(), {}}; }
679 static ObjectUnderConstruction getTombstoneKey() {
680 return {Base::getTombstoneKey(), {}};
681 }
682 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
683 return hash_value(Object);
684 }
685 static bool isEqual(const ObjectUnderConstruction &LHS,
686 const ObjectUnderConstruction &RHS) {
687 return LHS == RHS;
688 }
689};
690}
691
692namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000693 /// EvalInfo - This is a private struct used by the evaluator to capture
694 /// information about a subexpression as it is folded. It retains information
695 /// about the AST context, but also maintains information about the folded
696 /// expression.
697 ///
698 /// If an expression could be evaluated, it is still possible it is not a C
699 /// "integer constant expression" or constant expression. If not, this struct
700 /// captures information about how and why not.
701 ///
702 /// One bit of information passed *into* the request for constant folding
703 /// indicates whether the subexpression is "evaluated" or not according to C
704 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
705 /// evaluate the expression regardless of what the RHS is, but C only allows
706 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000707 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000708 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000709
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000710 /// EvalStatus - Contains information about the evaluation.
711 Expr::EvalStatus &EvalStatus;
712
713 /// CurrentCall - The top of the constexpr call stack.
714 CallStackFrame *CurrentCall;
715
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000716 /// CallStackDepth - The number of calls in the call stack right now.
717 unsigned CallStackDepth;
718
Richard Smithb228a862012-02-15 02:18:13 +0000719 /// NextCallIndex - The next call index to assign.
720 unsigned NextCallIndex;
721
Richard Smitha3d3bd22013-05-08 02:12:03 +0000722 /// StepsLeft - The remaining number of evaluation steps we're permitted
723 /// to perform. This is essentially a limit for the number of statements
724 /// we will evaluate.
725 unsigned StepsLeft;
726
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000727 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000728 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000729 CallStackFrame BottomFrame;
730
Richard Smith08d6a2c2013-07-24 07:11:57 +0000731 /// A stack of values whose lifetimes end at the end of some surrounding
732 /// evaluation frame.
733 llvm::SmallVector<Cleanup, 16> CleanupStack;
734
Richard Smithd62306a2011-11-10 06:34:14 +0000735 /// EvaluatingDecl - This is the declaration whose initializer is being
736 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000737 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000738
739 /// EvaluatingDeclValue - This is the value being constructed for the
740 /// declaration whose initializer is being evaluated, if any.
741 APValue *EvaluatingDeclValue;
742
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000743 /// Set of objects that are currently being constructed.
744 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
745 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000746
747 struct EvaluatingConstructorRAII {
748 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000749 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000750 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000751 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
752 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000753 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000754 DidInsert =
755 EI.ObjectsUnderConstruction
756 .insert({Object, HasBases ? ConstructionPhase::Bases
757 : ConstructionPhase::AfterBases})
758 .second;
759 }
760 void finishedConstructingBases() {
761 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000762 }
763 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000764 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000765 }
766 };
767
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000768 ConstructionPhase
769 isEvaluatingConstructor(APValue::LValueBase Base,
770 ArrayRef<APValue::LValuePathEntry> Path) {
771 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000772 }
773
Richard Smith37be3362019-05-04 04:00:45 +0000774 /// If we're currently speculatively evaluating, the outermost call stack
775 /// depth at which we can mutate state, otherwise 0.
776 unsigned SpeculativeEvaluationDepth = 0;
777
Richard Smith410306b2016-12-12 02:53:20 +0000778 /// The current array initialization index, if we're performing array
779 /// initialization.
780 uint64_t ArrayInitIndex = -1;
781
Richard Smith357362d2011-12-13 06:39:58 +0000782 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
783 /// notes attached to it will also be stored, otherwise they will not be.
784 bool HasActiveDiagnostic;
785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000786 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000787 /// fold (not just why it's not strictly a constant expression)?
788 bool HasFoldFailureDiagnostic;
789
Fangrui Song407659a2018-11-30 23:41:18 +0000790 /// Whether or not we're in a context where the front end requires a
791 /// constant value.
792 bool InConstantContext;
793
Richard Smith6d4c6582013-11-05 22:18:15 +0000794 enum EvaluationMode {
795 /// Evaluate as a constant expression. Stop if we find that the expression
796 /// is not a constant expression.
797 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000798
Richard Smith6d4c6582013-11-05 22:18:15 +0000799 /// Evaluate as a potential constant expression. Keep going if we hit a
800 /// construct that we can't evaluate yet (because we don't yet know the
801 /// value of something) but stop if we hit something that could never be
802 /// a constant expression.
803 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000804
Richard Smith6d4c6582013-11-05 22:18:15 +0000805 /// Fold the expression to a constant. Stop if we hit a side-effect that
806 /// we can't model.
807 EM_ConstantFold,
808
809 /// Evaluate the expression looking for integer overflow and similar
810 /// issues. Don't worry about side-effects, and try to visit all
811 /// subexpressions.
812 EM_EvaluateForOverflow,
813
814 /// Evaluate in any way we know how. Don't worry about side-effects that
815 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000816 EM_IgnoreSideEffects,
817
818 /// Evaluate as a constant expression. Stop if we find that the expression
819 /// is not a constant expression. Some expressions can be retried in the
820 /// optimizer if we don't constant fold them here, but in an unevaluated
821 /// context we try to fold them immediately since the optimizer never
822 /// gets a chance to look at it.
823 EM_ConstantExpressionUnevaluated,
824
825 /// Evaluate as a potential constant expression. Keep going if we hit a
826 /// construct that we can't evaluate yet (because we don't yet know the
827 /// value of something) but stop if we hit something that could never be
828 /// a constant expression. Some expressions can be retried in the
829 /// optimizer if we don't constant fold them here, but in an unevaluated
830 /// context we try to fold them immediately since the optimizer never
831 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000832 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 } EvalMode;
834
835 /// Are we checking whether the expression is a potential constant
836 /// expression?
837 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000838 return EvalMode == EM_PotentialConstantExpression ||
839 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 }
841
842 /// Are we checking an expression for overflow?
843 // FIXME: We should check for any kind of undefined or suspicious behavior
844 // in such constructs, not just overflow.
845 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
846
847 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000848 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000849 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000850 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000851 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
852 EvaluatingDecl((const ValueDecl *)nullptr),
853 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000854 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000855 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000856
Richard Smith7525ff62013-05-09 07:14:00 +0000857 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
858 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000859 EvaluatingDeclValue = &Value;
860 }
861
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000863
Richard Smith357362d2011-12-13 06:39:58 +0000864 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000865 // Don't perform any constexpr calls (other than the call we're checking)
866 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000867 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000868 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000869 if (NextCallIndex == 0) {
870 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000871 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000872 return false;
873 }
Richard Smith357362d2011-12-13 06:39:58 +0000874 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
875 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000876 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000877 << getLangOpts().ConstexprCallDepth;
878 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000879 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000880
Richard Smith37be3362019-05-04 04:00:45 +0000881 std::pair<CallStackFrame *, unsigned>
882 getCallFrameAndDepth(unsigned CallIndex) {
883 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000884 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
885 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000886 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000887 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000888 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000889 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000890 --Depth;
891 }
892 if (Frame->Index == CallIndex)
893 return {Frame, Depth};
894 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000895 }
896
Richard Smitha3d3bd22013-05-08 02:12:03 +0000897 bool nextStep(const Stmt *S) {
898 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000899 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000900 return false;
901 }
902 --StepsLeft;
903 return true;
904 }
905
Richard Smith357362d2011-12-13 06:39:58 +0000906 private:
907 /// Add a diagnostic to the diagnostics list.
908 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
909 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
910 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
911 return EvalStatus.Diag->back().second;
912 }
913
Richard Smithf6f003a2011-12-16 19:06:07 +0000914 /// Add notes containing a call stack to the current point of evaluation.
915 void addCallStack(unsigned Limit);
916
Faisal Valie690b7a2016-07-02 22:34:24 +0000917 private:
918 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
919 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000920
Richard Smith92b1ce02011-12-12 09:28:41 +0000921 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000922 // If we have a prior diagnostic, it will be noting that the expression
923 // isn't a constant expression. This diagnostic is more important,
924 // unless we require this evaluation to produce a constant expression.
925 //
926 // FIXME: We might want to show both diagnostics to the user in
927 // EM_ConstantFold mode.
928 if (!EvalStatus.Diag->empty()) {
929 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000930 case EM_ConstantFold:
931 case EM_IgnoreSideEffects:
932 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000933 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000934 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000935 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000936 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 case EM_ConstantExpression:
938 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000939 case EM_ConstantExpressionUnevaluated:
940 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 HasActiveDiagnostic = false;
942 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 }
944 }
945
Richard Smithf6f003a2011-12-16 19:06:07 +0000946 unsigned CallStackNotes = CallStackDepth - 1;
947 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
948 if (Limit)
949 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000950 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000951 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000952
Richard Smith357362d2011-12-13 06:39:58 +0000953 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000954 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000955 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000956 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
957 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000958 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000959 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000960 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000961 }
Richard Smith357362d2011-12-13 06:39:58 +0000962 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000963 return OptionalDiagnostic();
964 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000965 public:
966 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
967 OptionalDiagnostic
968 FFDiag(SourceLocation Loc,
969 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
970 unsigned ExtraNotes = 0) {
971 return Diag(Loc, DiagId, ExtraNotes, false);
972 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000973
Faisal Valie690b7a2016-07-02 22:34:24 +0000974 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000975 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000976 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000977 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000978 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000979 HasActiveDiagnostic = false;
980 return OptionalDiagnostic();
981 }
982
Richard Smith92b1ce02011-12-12 09:28:41 +0000983 /// Diagnose that the evaluation does not produce a C++11 core constant
984 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000985 ///
986 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
987 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000988 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000989 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000990 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000991 // Don't override a previous diagnostic. Don't bother collecting
992 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000993 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000994 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000995 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000996 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000997 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000998 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000999 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1000 = diag::note_invalid_subexpr_in_const_expr,
1001 unsigned ExtraNotes = 0) {
1002 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1003 }
Richard Smith357362d2011-12-13 06:39:58 +00001004 /// Add a note to a prior diagnostic.
1005 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1006 if (!HasActiveDiagnostic)
1007 return OptionalDiagnostic();
1008 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +00001009 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00001010
1011 /// Add a stack of notes to a prior diagnostic.
1012 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1013 if (HasActiveDiagnostic) {
1014 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1015 Diags.begin(), Diags.end());
1016 }
1017 }
Richard Smith253c2a32012-01-27 01:14:48 +00001018
Richard Smith6d4c6582013-11-05 22:18:15 +00001019 /// Should we continue evaluation after encountering a side-effect that we
1020 /// couldn't model?
1021 bool keepEvaluatingAfterSideEffect() {
1022 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00001023 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001024 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001025 case EM_EvaluateForOverflow:
1026 case EM_IgnoreSideEffects:
1027 return true;
1028
Richard Smith6d4c6582013-11-05 22:18:15 +00001029 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001030 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001031 case EM_ConstantFold:
1032 return false;
1033 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001034 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001035 }
1036
1037 /// Note that we have had a side-effect, and determine whether we should
1038 /// keep evaluating.
1039 bool noteSideEffect() {
1040 EvalStatus.HasSideEffects = true;
1041 return keepEvaluatingAfterSideEffect();
1042 }
1043
Richard Smithce8eca52015-12-08 03:21:47 +00001044 /// Should we continue evaluation after encountering undefined behavior?
1045 bool keepEvaluatingAfterUndefinedBehavior() {
1046 switch (EvalMode) {
1047 case EM_EvaluateForOverflow:
1048 case EM_IgnoreSideEffects:
1049 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001050 return true;
1051
1052 case EM_PotentialConstantExpression:
1053 case EM_PotentialConstantExpressionUnevaluated:
1054 case EM_ConstantExpression:
1055 case EM_ConstantExpressionUnevaluated:
1056 return false;
1057 }
1058 llvm_unreachable("Missed EvalMode case");
1059 }
1060
1061 /// Note that we hit something that was technically undefined behavior, but
1062 /// that we can evaluate past it (such as signed overflow or floating-point
1063 /// division by zero.)
1064 bool noteUndefinedBehavior() {
1065 EvalStatus.HasUndefinedBehavior = true;
1066 return keepEvaluatingAfterUndefinedBehavior();
1067 }
1068
Richard Smith253c2a32012-01-27 01:14:48 +00001069 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001070 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001071 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001072 if (!StepsLeft)
1073 return false;
1074
1075 switch (EvalMode) {
1076 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001077 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001078 case EM_EvaluateForOverflow:
1079 return true;
1080
1081 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001082 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001083 case EM_ConstantFold:
1084 case EM_IgnoreSideEffects:
1085 return false;
1086 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001087 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001088 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089
George Burgess IV8c892b52016-05-25 22:31:54 +00001090 /// Notes that we failed to evaluate an expression that other expressions
1091 /// directly depend on, and determine if we should keep evaluating. This
1092 /// should only be called if we actually intend to keep evaluating.
1093 ///
1094 /// Call noteSideEffect() instead if we may be able to ignore the value that
1095 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1096 ///
1097 /// (Foo(), 1) // use noteSideEffect
1098 /// (Foo() || true) // use noteSideEffect
1099 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001100 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001101 // Failure when evaluating some expression often means there is some
1102 // subexpression whose evaluation was skipped. Therefore, (because we
1103 // don't track whether we skipped an expression when unwinding after an
1104 // evaluation failure) every evaluation failure that bubbles up from a
1105 // subexpression implies that a side-effect has potentially happened. We
1106 // skip setting the HasSideEffects flag to true until we decide to
1107 // continue evaluating after that point, which happens here.
1108 bool KeepGoing = keepEvaluatingAfterFailure();
1109 EvalStatus.HasSideEffects |= KeepGoing;
1110 return KeepGoing;
1111 }
1112
Richard Smith410306b2016-12-12 02:53:20 +00001113 class ArrayInitLoopIndex {
1114 EvalInfo &Info;
1115 uint64_t OuterIndex;
1116
1117 public:
1118 ArrayInitLoopIndex(EvalInfo &Info)
1119 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1120 Info.ArrayInitIndex = 0;
1121 }
1122 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1123
1124 operator uint64_t&() { return Info.ArrayInitIndex; }
1125 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001126 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001127
1128 /// Object used to treat all foldable expressions as constant expressions.
1129 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001130 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001131 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001132 bool HadNoPriorDiags;
1133 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001134
Richard Smith6d4c6582013-11-05 22:18:15 +00001135 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1136 : Info(Info),
1137 Enabled(Enabled),
1138 HadNoPriorDiags(Info.EvalStatus.Diag &&
1139 Info.EvalStatus.Diag->empty() &&
1140 !Info.EvalStatus.HasSideEffects),
1141 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001142 if (Enabled &&
1143 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1144 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001145 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001146 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001147 void keepDiagnostics() { Enabled = false; }
1148 ~FoldConstant() {
1149 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001150 !Info.EvalStatus.HasSideEffects)
1151 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001152 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001153 }
1154 };
Richard Smith17100ba2012-02-16 02:46:34 +00001155
James Y Knight892b09b2018-10-10 02:53:43 +00001156 /// RAII object used to set the current evaluation mode to ignore
1157 /// side-effects.
1158 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001159 EvalInfo &Info;
1160 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001161 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001162 : Info(Info), OldMode(Info.EvalMode) {
1163 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001164 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001165 }
1166
James Y Knight892b09b2018-10-10 02:53:43 +00001167 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001168 };
1169
George Burgess IV8c892b52016-05-25 22:31:54 +00001170 /// RAII object used to optionally suppress diagnostics and side-effects from
1171 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001172 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001173 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001174 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001175 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001176
George Burgess IV8c892b52016-05-25 22:31:54 +00001177 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001178 Info = Other.Info;
1179 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001180 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001181 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001182 }
1183
1184 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001185 if (!Info)
1186 return;
1187
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001188 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001189 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001190 }
1191
Richard Smith17100ba2012-02-16 02:46:34 +00001192 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001193 SpeculativeEvaluationRAII() = default;
1194
1195 SpeculativeEvaluationRAII(
1196 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001197 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001198 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001199 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001200 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001201 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001202
1203 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1204 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1205 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001206 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001207
1208 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1209 maybeRestoreState();
1210 moveFromAndCancel(std::move(Other));
1211 return *this;
1212 }
1213
1214 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001215 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001216
1217 /// RAII object wrapping a full-expression or block scope, and handling
1218 /// the ending of the lifetime of temporaries created within it.
1219 template<bool IsFullExpression>
1220 class ScopeRAII {
1221 EvalInfo &Info;
1222 unsigned OldStackSize;
1223 public:
1224 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001225 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1226 // Push a new temporary version. This is needed to distinguish between
1227 // temporaries created in different iterations of a loop.
1228 Info.CurrentCall->pushTempVersion();
1229 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001230 ~ScopeRAII() {
1231 // Body moved to a static method to encourage the compiler to inline away
1232 // instances of this class.
1233 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001234 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001235 }
1236 private:
1237 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1238 unsigned NewEnd = OldStackSize;
1239 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1240 I != N; ++I) {
1241 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1242 // Full-expression cleanup of a lifetime-extended temporary: nothing
1243 // to do, just move this cleanup to the right place in the stack.
1244 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1245 ++NewEnd;
1246 } else {
1247 // End the lifetime of the object.
1248 Info.CleanupStack[I].endLifetime();
1249 }
1250 }
1251 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1252 Info.CleanupStack.end());
1253 }
1254 };
1255 typedef ScopeRAII<false> BlockScopeRAII;
1256 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001257}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001258
Richard Smitha8105bc2012-01-06 16:39:00 +00001259bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1260 CheckSubobjectKind CSK) {
1261 if (Invalid)
1262 return false;
1263 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001264 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001265 << CSK;
1266 setInvalid();
1267 return false;
1268 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001269 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1270 // must actually be at least one array element; even a VLA cannot have a
1271 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 return true;
1273}
1274
Richard Smith6f4f0f12017-10-20 22:56:25 +00001275void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1276 const Expr *E) {
1277 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1278 // Do not set the designator as invalid: we can represent this situation,
1279 // and correct handling of __builtin_object_size requires us to do so.
1280}
1281
Richard Smitha8105bc2012-01-06 16:39:00 +00001282void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001283 const Expr *E,
1284 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001285 // If we're complaining, we must be able to statically determine the size of
1286 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001287 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001288 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001289 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001290 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001292 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001293 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001294 setInvalid();
1295}
1296
Richard Smithf6f003a2011-12-16 19:06:07 +00001297CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1298 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001299 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001300 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1301 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001302 Info.CurrentCall = this;
1303 ++Info.CallStackDepth;
1304}
1305
1306CallStackFrame::~CallStackFrame() {
1307 assert(Info.CurrentCall == this && "calls retired out of order");
1308 --Info.CallStackDepth;
1309 Info.CurrentCall = Caller;
1310}
1311
Richard Smith08d6a2c2013-07-24 07:11:57 +00001312APValue &CallStackFrame::createTemporary(const void *Key,
1313 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001314 unsigned Version = Info.CurrentCall->getTempVersion();
1315 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001316 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001317 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1318 return Result;
1319}
1320
Richard Smith84401042013-06-03 05:03:02 +00001321static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001322
1323void EvalInfo::addCallStack(unsigned Limit) {
1324 // Determine which calls to skip, if any.
1325 unsigned ActiveCalls = CallStackDepth - 1;
1326 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1327 if (Limit && Limit < ActiveCalls) {
1328 SkipStart = Limit / 2 + Limit % 2;
1329 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001330 }
1331
Richard Smithf6f003a2011-12-16 19:06:07 +00001332 // Walk the call stack and add the diagnostics.
1333 unsigned CallIdx = 0;
1334 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1335 Frame = Frame->Caller, ++CallIdx) {
1336 // Skip this call?
1337 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1338 if (CallIdx == SkipStart) {
1339 // Note that we're skipping calls.
1340 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1341 << unsigned(ActiveCalls - Limit);
1342 }
1343 continue;
1344 }
1345
Richard Smith5179eb72016-06-28 19:03:57 +00001346 // Use a different note for an inheriting constructor, because from the
1347 // user's perspective it's not really a function at all.
1348 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1349 if (CD->isInheritingConstructor()) {
1350 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1351 << CD->getParent();
1352 continue;
1353 }
1354 }
1355
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001356 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001357 llvm::raw_svector_ostream Out(Buffer);
1358 describeCall(Frame, Out);
1359 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1360 }
1361}
1362
Richard Smithdebad642019-05-12 09:39:08 +00001363/// Kinds of access we can perform on an object, for diagnostics. Note that
1364/// we consider a member function call to be a kind of access, even though
1365/// it is not formally an access of the object, because it has (largely) the
1366/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001367enum AccessKinds {
1368 AK_Read,
1369 AK_Assign,
1370 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001371 AK_Decrement,
1372 AK_MemberCall,
Richard Smith7bd54ab2019-05-15 20:22:21 +00001373 AK_DynamicCast,
Richard Smitha9330302019-05-17 19:19:28 +00001374 AK_TypeId,
Hubert Tong147b7432018-12-12 16:53:43 +00001375};
1376
Richard Smithdebad642019-05-12 09:39:08 +00001377static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001378 switch (AK) {
1379 case AK_Read:
1380 case AK_MemberCall:
1381 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001382 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001383 return false;
1384 case AK_Assign:
1385 case AK_Increment:
1386 case AK_Decrement:
1387 return true;
1388 }
1389 llvm_unreachable("unknown access kind");
1390}
1391
1392/// Is this an access per the C++ definition?
1393static bool isFormalAccess(AccessKinds AK) {
1394 return AK == AK_Read || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001395}
1396
Richard Smithf6f003a2011-12-16 19:06:07 +00001397namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001398 struct ComplexValue {
1399 private:
1400 bool IsInt;
1401
1402 public:
1403 APSInt IntReal, IntImag;
1404 APFloat FloatReal, FloatImag;
1405
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001406 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001407
1408 void makeComplexFloat() { IsInt = false; }
1409 bool isComplexFloat() const { return !IsInt; }
1410 APFloat &getComplexFloatReal() { return FloatReal; }
1411 APFloat &getComplexFloatImag() { return FloatImag; }
1412
1413 void makeComplexInt() { IsInt = true; }
1414 bool isComplexInt() const { return IsInt; }
1415 APSInt &getComplexIntReal() { return IntReal; }
1416 APSInt &getComplexIntImag() { return IntImag; }
1417
Richard Smith2e312c82012-03-03 22:46:17 +00001418 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001419 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001420 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001421 else
Richard Smith2e312c82012-03-03 22:46:17 +00001422 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001423 }
Richard Smith2e312c82012-03-03 22:46:17 +00001424 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001425 assert(v.isComplexFloat() || v.isComplexInt());
1426 if (v.isComplexFloat()) {
1427 makeComplexFloat();
1428 FloatReal = v.getComplexFloatReal();
1429 FloatImag = v.getComplexFloatImag();
1430 } else {
1431 makeComplexInt();
1432 IntReal = v.getComplexIntReal();
1433 IntImag = v.getComplexIntImag();
1434 }
1435 }
John McCall93d91dc2010-05-07 17:22:02 +00001436 };
John McCall45d55e42010-05-07 21:00:08 +00001437
1438 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001439 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001440 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001441 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001442 bool IsNullPtr : 1;
1443 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001444
Richard Smithce40ad62011-11-12 22:28:03 +00001445 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001446 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001447 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001448 SubobjectDesignator &getLValueDesignator() { return Designator; }
1449 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001450 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001451
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001452 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1453 unsigned getLValueVersion() const { return Base.getVersion(); }
1454
Richard Smith2e312c82012-03-03 22:46:17 +00001455 void moveInto(APValue &V) const {
1456 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001457 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001458 else {
1459 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001460 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001461 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001462 }
John McCall45d55e42010-05-07 21:00:08 +00001463 }
Richard Smith2e312c82012-03-03 22:46:17 +00001464 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001465 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001466 Base = V.getLValueBase();
1467 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001468 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001469 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001470 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001471 }
1472
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001473 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001474#ifndef NDEBUG
1475 // We only allow a few types of invalid bases. Enforce that here.
1476 if (BInvalid) {
1477 const auto *E = B.get<const Expr *>();
1478 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1479 "Unexpected type of invalid base");
1480 }
1481#endif
1482
Richard Smithce40ad62011-11-12 22:28:03 +00001483 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001484 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001485 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001486 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001487 IsNullPtr = false;
1488 }
1489
1490 void setNull(QualType PointerTy, uint64_t TargetVal) {
1491 Base = (Expr *)nullptr;
1492 Offset = CharUnits::fromQuantity(TargetVal);
1493 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001494 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1495 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001496 }
1497
George Burgess IV3a03fab2015-09-04 21:28:13 +00001498 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001499 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001500 }
1501
Hubert Tong147b7432018-12-12 16:53:43 +00001502 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001503 // Check that this LValue is not based on a null pointer. If it is, produce
1504 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001505 template <typename GenDiagType>
1506 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001507 if (Designator.Invalid)
1508 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001509 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001510 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001511 Designator.setInvalid();
1512 return false;
1513 }
1514 return true;
1515 }
1516
Hubert Tong147b7432018-12-12 16:53:43 +00001517 public:
1518 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1519 CheckSubobjectKind CSK) {
1520 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1521 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1522 });
1523 }
1524
1525 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1526 AccessKinds AK) {
1527 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1528 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1529 });
1530 }
1531
Richard Smitha8105bc2012-01-06 16:39:00 +00001532 // Check this LValue refers to an object. If not, set the designator to be
1533 // invalid and emit a diagnostic.
1534 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001535 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001536 Designator.checkSubobject(Info, E, CSK);
1537 }
1538
1539 void addDecl(EvalInfo &Info, const Expr *E,
1540 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001541 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1542 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001543 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001544 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1545 if (!Designator.Entries.empty()) {
1546 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1547 Designator.setInvalid();
1548 return;
1549 }
Richard Smithefdb5032017-11-15 03:03:56 +00001550 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1551 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1552 Designator.FirstEntryIsAnUnsizedArray = true;
1553 Designator.addUnsizedArrayUnchecked(ElemTy);
1554 }
George Burgess IVe3763372016-12-22 02:50:20 +00001555 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001556 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001557 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1558 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001559 }
Richard Smith66c96992012-02-18 22:04:06 +00001560 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001561 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1562 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001563 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001564 void clearIsNullPointer() {
1565 IsNullPtr = false;
1566 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001567 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1568 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001569 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1570 // but we're not required to diagnose it and it's valid in C++.)
1571 if (!Index)
1572 return;
1573
1574 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1575 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1576 // offsets.
1577 uint64_t Offset64 = Offset.getQuantity();
1578 uint64_t ElemSize64 = ElementSize.getQuantity();
1579 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1580 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1581
1582 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001583 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001584 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001585 }
1586 void adjustOffset(CharUnits N) {
1587 Offset += N;
1588 if (N.getQuantity())
1589 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001590 }
John McCall45d55e42010-05-07 21:00:08 +00001591 };
Richard Smith027bf112011-11-17 22:56:20 +00001592
1593 struct MemberPtr {
1594 MemberPtr() {}
1595 explicit MemberPtr(const ValueDecl *Decl) :
1596 DeclAndIsDerivedMember(Decl, false), Path() {}
1597
1598 /// The member or (direct or indirect) field referred to by this member
1599 /// pointer, or 0 if this is a null member pointer.
1600 const ValueDecl *getDecl() const {
1601 return DeclAndIsDerivedMember.getPointer();
1602 }
1603 /// Is this actually a member of some type derived from the relevant class?
1604 bool isDerivedMember() const {
1605 return DeclAndIsDerivedMember.getInt();
1606 }
1607 /// Get the class which the declaration actually lives in.
1608 const CXXRecordDecl *getContainingRecord() const {
1609 return cast<CXXRecordDecl>(
1610 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1611 }
1612
Richard Smith2e312c82012-03-03 22:46:17 +00001613 void moveInto(APValue &V) const {
1614 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001615 }
Richard Smith2e312c82012-03-03 22:46:17 +00001616 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001617 assert(V.isMemberPointer());
1618 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1619 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1620 Path.clear();
1621 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1622 Path.insert(Path.end(), P.begin(), P.end());
1623 }
1624
1625 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1626 /// whether the member is a member of some class derived from the class type
1627 /// of the member pointer.
1628 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1629 /// Path - The path of base/derived classes from the member declaration's
1630 /// class (exclusive) to the class type of the member pointer (inclusive).
1631 SmallVector<const CXXRecordDecl*, 4> Path;
1632
1633 /// Perform a cast towards the class of the Decl (either up or down the
1634 /// hierarchy).
1635 bool castBack(const CXXRecordDecl *Class) {
1636 assert(!Path.empty());
1637 const CXXRecordDecl *Expected;
1638 if (Path.size() >= 2)
1639 Expected = Path[Path.size() - 2];
1640 else
1641 Expected = getContainingRecord();
1642 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1643 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1644 // if B does not contain the original member and is not a base or
1645 // derived class of the class containing the original member, the result
1646 // of the cast is undefined.
1647 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1648 // (D::*). We consider that to be a language defect.
1649 return false;
1650 }
1651 Path.pop_back();
1652 return true;
1653 }
1654 /// Perform a base-to-derived member pointer cast.
1655 bool castToDerived(const CXXRecordDecl *Derived) {
1656 if (!getDecl())
1657 return true;
1658 if (!isDerivedMember()) {
1659 Path.push_back(Derived);
1660 return true;
1661 }
1662 if (!castBack(Derived))
1663 return false;
1664 if (Path.empty())
1665 DeclAndIsDerivedMember.setInt(false);
1666 return true;
1667 }
1668 /// Perform a derived-to-base member pointer cast.
1669 bool castToBase(const CXXRecordDecl *Base) {
1670 if (!getDecl())
1671 return true;
1672 if (Path.empty())
1673 DeclAndIsDerivedMember.setInt(true);
1674 if (isDerivedMember()) {
1675 Path.push_back(Base);
1676 return true;
1677 }
1678 return castBack(Base);
1679 }
1680 };
Richard Smith357362d2011-12-13 06:39:58 +00001681
Richard Smith7bb00672012-02-01 01:42:44 +00001682 /// Compare two member pointers, which are assumed to be of the same type.
1683 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1684 if (!LHS.getDecl() || !RHS.getDecl())
1685 return !LHS.getDecl() && !RHS.getDecl();
1686 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1687 return false;
1688 return LHS.Path == RHS.Path;
1689 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001690}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001691
Richard Smith2e312c82012-03-03 22:46:17 +00001692static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001693static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1694 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001695 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001696static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1697 bool InvalidBaseOK = false);
1698static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1699 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001700static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1701 EvalInfo &Info);
1702static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001703static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001704static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001705 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001706static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001707static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001708static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1709 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001710static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001711
Leonard Chand3f3e162019-01-18 21:04:25 +00001712/// Evaluate an integer or fixed point expression into an APResult.
1713static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1714 EvalInfo &Info);
1715
1716/// Evaluate only a fixed point expression into an APResult.
1717static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1718 EvalInfo &Info);
1719
Chris Lattner05706e882008-07-11 18:11:29 +00001720//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001721// Misc utilities
1722//===----------------------------------------------------------------------===//
1723
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001724/// A helper function to create a temporary and set an LValue.
1725template <class KeyTy>
1726static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1727 LValue &LV, CallStackFrame &Frame) {
1728 LV.set({Key, Frame.Info.CurrentCall->Index,
1729 Frame.Info.CurrentCall->getTempVersion()});
1730 return Frame.createTemporary(Key, IsLifetimeExtended);
1731}
1732
Richard Smithd6cc1982017-01-31 02:23:02 +00001733/// Negate an APSInt in place, converting it to a signed form if necessary, and
1734/// preserving its value (by extending by up to one bit as needed).
1735static void negateAsSigned(APSInt &Int) {
1736 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1737 Int = Int.extend(Int.getBitWidth() + 1);
1738 Int.setIsSigned(true);
1739 }
1740 Int = -Int;
1741}
1742
Richard Smith84401042013-06-03 05:03:02 +00001743/// Produce a string describing the given constexpr call.
1744static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1745 unsigned ArgIndex = 0;
1746 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1747 !isa<CXXConstructorDecl>(Frame->Callee) &&
1748 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1749
1750 if (!IsMemberCall)
1751 Out << *Frame->Callee << '(';
1752
1753 if (Frame->This && IsMemberCall) {
1754 APValue Val;
1755 Frame->This->moveInto(Val);
1756 Val.printPretty(Out, Frame->Info.Ctx,
1757 Frame->This->Designator.MostDerivedType);
1758 // FIXME: Add parens around Val if needed.
1759 Out << "->" << *Frame->Callee << '(';
1760 IsMemberCall = false;
1761 }
1762
1763 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1764 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1765 if (ArgIndex > (unsigned)IsMemberCall)
1766 Out << ", ";
1767
1768 const ParmVarDecl *Param = *I;
1769 const APValue &Arg = Frame->Arguments[ArgIndex];
1770 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1771
1772 if (ArgIndex == 0 && IsMemberCall)
1773 Out << "->" << *Frame->Callee << '(';
1774 }
1775
1776 Out << ')';
1777}
1778
Richard Smithd9f663b2013-04-22 15:31:51 +00001779/// Evaluate an expression to see if it had side-effects, and discard its
1780/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001781/// \return \c true if the caller should keep evaluating.
1782static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001783 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001784 if (!Evaluate(Scratch, Info, E))
1785 // We don't need the value, but we might have skipped a side effect here.
1786 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001787 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001788}
1789
Richard Smithd62306a2011-11-10 06:34:14 +00001790/// Should this call expression be treated as a string literal?
1791static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001792 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001793 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1794 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1795}
1796
Richard Smithce40ad62011-11-12 22:28:03 +00001797static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001798 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1799 // constant expression of pointer type that evaluates to...
1800
1801 // ... a null pointer value, or a prvalue core constant expression of type
1802 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001803 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001804
Richard Smithce40ad62011-11-12 22:28:03 +00001805 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1806 // ... the address of an object with static storage duration,
1807 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1808 return VD->hasGlobalStorage();
1809 // ... the address of a function,
1810 return isa<FunctionDecl>(D);
1811 }
1812
Richard Smithee0ce3022019-05-17 07:06:46 +00001813 if (B.is<TypeInfoLValue>())
1814 return true;
1815
Richard Smithce40ad62011-11-12 22:28:03 +00001816 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001817 switch (E->getStmtClass()) {
1818 default:
1819 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001820 case Expr::CompoundLiteralExprClass: {
1821 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1822 return CLE->isFileScope() && CLE->isLValue();
1823 }
Richard Smithe6c01442013-06-05 00:46:14 +00001824 case Expr::MaterializeTemporaryExprClass:
1825 // A materialized temporary might have been lifetime-extended to static
1826 // storage duration.
1827 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001828 // A string literal has static storage duration.
1829 case Expr::StringLiteralClass:
1830 case Expr::PredefinedExprClass:
1831 case Expr::ObjCStringLiteralClass:
1832 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001833 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001834 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001835 case Expr::ObjCBoxedExprClass:
1836 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001837 case Expr::CallExprClass:
1838 return IsStringLiteralCall(cast<CallExpr>(E));
1839 // For GCC compatibility, &&label has static storage duration.
1840 case Expr::AddrLabelExprClass:
1841 return true;
1842 // A Block literal expression may be used as the initialization value for
1843 // Block variables at global or local static scope.
1844 case Expr::BlockExprClass:
1845 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001846 case Expr::ImplicitValueInitExprClass:
1847 // FIXME:
1848 // We can never form an lvalue with an implicit value initialization as its
1849 // base through expression evaluation, so these only appear in one case: the
1850 // implicit variable declaration we invent when checking whether a constexpr
1851 // constructor can produce a constant expression. We must assume that such
1852 // an expression might be a global lvalue.
1853 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001854 }
John McCall95007602010-05-10 23:27:23 +00001855}
1856
Richard Smith06f71b52018-08-04 00:57:17 +00001857static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1858 return LVal.Base.dyn_cast<const ValueDecl*>();
1859}
1860
1861static bool IsLiteralLValue(const LValue &Value) {
1862 if (Value.getLValueCallIndex())
1863 return false;
1864 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1865 return E && !isa<MaterializeTemporaryExpr>(E);
1866}
1867
1868static bool IsWeakLValue(const LValue &Value) {
1869 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1870 return Decl && Decl->isWeak();
1871}
1872
1873static bool isZeroSized(const LValue &Value) {
1874 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1875 if (Decl && isa<VarDecl>(Decl)) {
1876 QualType Ty = Decl->getType();
1877 if (Ty->isArrayType())
1878 return Ty->isIncompleteType() ||
1879 Decl->getASTContext().getTypeSize(Ty) == 0;
1880 }
1881 return false;
1882}
1883
1884static bool HasSameBase(const LValue &A, const LValue &B) {
1885 if (!A.getLValueBase())
1886 return !B.getLValueBase();
1887 if (!B.getLValueBase())
1888 return false;
1889
1890 if (A.getLValueBase().getOpaqueValue() !=
1891 B.getLValueBase().getOpaqueValue()) {
1892 const Decl *ADecl = GetLValueBaseDecl(A);
1893 if (!ADecl)
1894 return false;
1895 const Decl *BDecl = GetLValueBaseDecl(B);
1896 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1897 return false;
1898 }
1899
1900 return IsGlobalLValue(A.getLValueBase()) ||
1901 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1902 A.getLValueVersion() == B.getLValueVersion());
1903}
1904
Richard Smithb228a862012-02-15 02:18:13 +00001905static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1906 assert(Base && "no location for a null lvalue");
1907 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1908 if (VD)
1909 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001910 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1911 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1912 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001913}
1914
Richard Smith80815602011-11-07 05:07:52 +00001915/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001916/// value for an address or reference constant expression. Return true if we
1917/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001918static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 QualType Type, const LValue &LVal,
1920 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001921 bool IsReferenceType = Type->isReferenceType();
1922
Richard Smith357362d2011-12-13 06:39:58 +00001923 APValue::LValueBase Base = LVal.getLValueBase();
1924 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1925
Richard Smith0dea49e2012-02-18 04:58:18 +00001926 // Check that the object is a global. Note that the fake 'this' object we
1927 // manufacture when checking potential constant expressions is conservatively
1928 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001929 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001930 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001931 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001932 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001933 << IsReferenceType << !Designator.Entries.empty()
1934 << !!VD << VD;
1935 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001936 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001937 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001938 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001939 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001940 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001941 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001942 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001943 LVal.getLValueCallIndex() == 0) &&
1944 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001945
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001946 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1947 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001948 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001949 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001950 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001951
Hans Wennborg82dd8772014-06-25 22:19:48 +00001952 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001953 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001954 return false;
1955 }
1956 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1957 // __declspec(dllimport) must be handled very carefully:
1958 // We must never initialize an expression with the thunk in C++.
1959 // Doing otherwise would allow the same id-expression to yield
1960 // different addresses for the same function in different translation
1961 // units. However, this means that we must dynamically initialize the
1962 // expression with the contents of the import address table at runtime.
1963 //
1964 // The C language has no notion of ODR; furthermore, it has no notion of
1965 // dynamic initialization. This means that we are permitted to
1966 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001967 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1968 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001969 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001970 }
1971 }
1972
Richard Smitha8105bc2012-01-06 16:39:00 +00001973 // Allow address constant expressions to be past-the-end pointers. This is
1974 // an extension: the standard requires them to point to an object.
1975 if (!IsReferenceType)
1976 return true;
1977
1978 // A reference constant expression must refer to an object.
1979 if (!Base) {
1980 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001981 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001982 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001983 }
1984
Richard Smith357362d2011-12-13 06:39:58 +00001985 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001986 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001987 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001988 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001989 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001990 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001991 }
1992
Richard Smith80815602011-11-07 05:07:52 +00001993 return true;
1994}
1995
Reid Klecknercd016d82017-07-07 22:04:29 +00001996/// Member pointers are constant expressions unless they point to a
1997/// non-virtual dllimport member function.
1998static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1999 SourceLocation Loc,
2000 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002001 const APValue &Value,
2002 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002003 const ValueDecl *Member = Value.getMemberPointerDecl();
2004 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2005 if (!FD)
2006 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002007 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2008 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002009}
2010
Richard Smithfddd3842011-12-30 21:15:51 +00002011/// Check that this core constant expression is of literal type, and if not,
2012/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002013static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002014 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002015 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002016 return true;
2017
Richard Smith7525ff62013-05-09 07:14:00 +00002018 // C++1y: A constant initializer for an object o [...] may also invoke
2019 // constexpr constructors for o and its subobjects even if those objects
2020 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002021 //
2022 // C++11 missed this detail for aggregates, so classes like this:
2023 // struct foo_t { union { int i; volatile int j; } u; };
2024 // are not (obviously) initializable like so:
2025 // __attribute__((__require_constant_initialization__))
2026 // static const foo_t x = {{0}};
2027 // because "i" is a subobject with non-literal initialization (due to the
2028 // volatile member of the union). See:
2029 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2030 // Therefore, we use the C++1y behavior.
2031 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002032 return true;
2033
Richard Smithfddd3842011-12-30 21:15:51 +00002034 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002035 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002036 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002037 << E->getType();
2038 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002039 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002040 return false;
2041}
2042
Richard Smith0b0a0b62011-10-29 20:57:55 +00002043/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00002044/// constant expression. If not, report an appropriate diagnostic. Does not
2045/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002046static bool
2047CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2048 const APValue &Value,
Richard Smith31c69a32019-05-21 23:15:20 +00002049 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2050 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002051 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002052 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002053 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002054 if (SubobjectLoc.isValid())
2055 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002056 return false;
2057 }
2058
Richard Smith77be48a2014-07-31 06:31:19 +00002059 // We allow _Atomic(T) to be initialized from anything that T can be
2060 // initialized from.
2061 if (const AtomicType *AT = Type->getAs<AtomicType>())
2062 Type = AT->getValueType();
2063
Richard Smithb228a862012-02-15 02:18:13 +00002064 // Core issue 1454: For a literal constant expression of array or class type,
2065 // each subobject of its value shall have been initialized by a constant
2066 // expression.
2067 if (Value.isArray()) {
2068 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2069 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2070 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Richard Smith31c69a32019-05-21 23:15:20 +00002071 Value.getArrayInitializedElt(I), Usage,
2072 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00002073 return false;
2074 }
2075 if (!Value.hasArrayFiller())
2076 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002077 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
Richard Smith31c69a32019-05-21 23:15:20 +00002078 Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00002079 }
Richard Smithb228a862012-02-15 02:18:13 +00002080 if (Value.isUnion() && Value.getUnionField()) {
2081 return CheckConstantExpression(Info, DiagLoc,
2082 Value.getUnionField()->getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002083 Value.getUnionValue(), Usage,
2084 Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00002085 }
2086 if (Value.isStruct()) {
2087 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2088 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2089 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002090 for (const CXXBaseSpecifier &BS : CD->bases()) {
2091 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002092 Value.getStructBase(BaseIndex), Usage,
2093 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00002094 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002095 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002096 }
2097 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002098 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002099 if (I->isUnnamedBitfield())
2100 continue;
2101
David Blaikie2d7c57e2012-04-30 02:36:29 +00002102 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002103 Value.getStructField(I->getFieldIndex()),
Richard Smith31c69a32019-05-21 23:15:20 +00002104 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002105 return false;
2106 }
2107 }
2108
2109 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002110 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002111 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002112 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002113 }
2114
Reid Klecknercd016d82017-07-07 22:04:29 +00002115 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002116 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002117
Richard Smithb228a862012-02-15 02:18:13 +00002118 // Everything else is fine.
2119 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002120}
2121
Richard Smith2e312c82012-03-03 22:46:17 +00002122static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002123 // A null base expression indicates a null pointer. These are always
2124 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002125 if (!Value.getLValueBase()) {
2126 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002127 return true;
2128 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002129
Richard Smith027bf112011-11-17 22:56:20 +00002130 // We have a non-null base. These are generally known to be true, but if it's
2131 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002132 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002133 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002134 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002135}
2136
Richard Smith2e312c82012-03-03 22:46:17 +00002137static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002138 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002139 case APValue::None:
2140 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002141 return false;
2142 case APValue::Int:
2143 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002144 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002145 case APValue::FixedPoint:
2146 Result = Val.getFixedPoint().getBoolValue();
2147 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002148 case APValue::Float:
2149 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002150 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002151 case APValue::ComplexInt:
2152 Result = Val.getComplexIntReal().getBoolValue() ||
2153 Val.getComplexIntImag().getBoolValue();
2154 return true;
2155 case APValue::ComplexFloat:
2156 Result = !Val.getComplexFloatReal().isZero() ||
2157 !Val.getComplexFloatImag().isZero();
2158 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002159 case APValue::LValue:
2160 return EvalPointerValueAsBool(Val, Result);
2161 case APValue::MemberPointer:
2162 Result = Val.getMemberPointerDecl();
2163 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002164 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002165 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002166 case APValue::Struct:
2167 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002168 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002169 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002170 }
2171
Richard Smith11562c52011-10-28 17:51:58 +00002172 llvm_unreachable("unknown APValue kind");
2173}
2174
2175static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2176 EvalInfo &Info) {
2177 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002178 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002179 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002180 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002181 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002182}
2183
Richard Smith357362d2011-12-13 06:39:58 +00002184template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002185static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002186 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002187 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002188 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002189 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002190}
2191
2192static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2193 QualType SrcType, const APFloat &Value,
2194 QualType DestType, APSInt &Result) {
2195 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002196 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002197 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002198
Richard Smith357362d2011-12-13 06:39:58 +00002199 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002200 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002201 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2202 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002203 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002204 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002205}
2206
Richard Smith357362d2011-12-13 06:39:58 +00002207static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2208 QualType SrcType, QualType DestType,
2209 APFloat &Result) {
2210 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002211 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002212 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2213 APFloat::rmNearestTiesToEven, &ignored)
2214 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002215 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002216 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002217}
2218
Richard Smith911e1422012-01-30 22:27:01 +00002219static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2220 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002221 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002222 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002223 // Figure out if this is a truncate, extend or noop cast.
2224 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002225 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002226 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002227 if (DestType->isBooleanType())
2228 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002229 return Result;
2230}
2231
Richard Smith357362d2011-12-13 06:39:58 +00002232static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2233 QualType SrcType, const APSInt &Value,
2234 QualType DestType, APFloat &Result) {
2235 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2236 if (Result.convertFromAPInt(Value, Value.isSigned(),
2237 APFloat::rmNearestTiesToEven)
2238 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002239 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002241}
2242
Richard Smith49ca8aa2013-08-06 07:09:20 +00002243static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2244 APValue &Value, const FieldDecl *FD) {
2245 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2246
2247 if (!Value.isInt()) {
2248 // Trying to store a pointer-cast-to-integer into a bitfield.
2249 // FIXME: In this case, we should provide the diagnostic for casting
2250 // a pointer to an integer.
2251 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002252 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002253 return false;
2254 }
2255
2256 APSInt &Int = Value.getInt();
2257 unsigned OldBitWidth = Int.getBitWidth();
2258 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2259 if (NewBitWidth < OldBitWidth)
2260 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2261 return true;
2262}
2263
Eli Friedman803acb32011-12-22 03:51:45 +00002264static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2265 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002266 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002267 if (!Evaluate(SVal, Info, E))
2268 return false;
2269 if (SVal.isInt()) {
2270 Res = SVal.getInt();
2271 return true;
2272 }
2273 if (SVal.isFloat()) {
2274 Res = SVal.getFloat().bitcastToAPInt();
2275 return true;
2276 }
2277 if (SVal.isVector()) {
2278 QualType VecTy = E->getType();
2279 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2280 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2281 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2282 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2283 Res = llvm::APInt::getNullValue(VecSize);
2284 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2285 APValue &Elt = SVal.getVectorElt(i);
2286 llvm::APInt EltAsInt;
2287 if (Elt.isInt()) {
2288 EltAsInt = Elt.getInt();
2289 } else if (Elt.isFloat()) {
2290 EltAsInt = Elt.getFloat().bitcastToAPInt();
2291 } else {
2292 // Don't try to handle vectors of anything other than int or float
2293 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002294 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002295 return false;
2296 }
2297 unsigned BaseEltSize = EltAsInt.getBitWidth();
2298 if (BigEndian)
2299 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2300 else
2301 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2302 }
2303 return true;
2304 }
2305 // Give up if the input isn't an int, float, or vector. For example, we
2306 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002307 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002308 return false;
2309}
2310
Richard Smith43e77732013-05-07 04:50:00 +00002311/// Perform the given integer operation, which is known to need at most BitWidth
2312/// bits, and check for overflow in the original type (if that type was not an
2313/// unsigned type).
2314template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002315static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2316 const APSInt &LHS, const APSInt &RHS,
2317 unsigned BitWidth, Operation Op,
2318 APSInt &Result) {
2319 if (LHS.isUnsigned()) {
2320 Result = Op(LHS, RHS);
2321 return true;
2322 }
Richard Smith43e77732013-05-07 04:50:00 +00002323
2324 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002325 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002326 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002327 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002328 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002329 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002330 << Result.toString(10) << E->getType();
2331 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002332 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002333 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002334 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002335}
2336
2337/// Perform the given binary integer operation.
2338static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2339 BinaryOperatorKind Opcode, APSInt RHS,
2340 APSInt &Result) {
2341 switch (Opcode) {
2342 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002343 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002344 return false;
2345 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002346 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2347 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002348 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002349 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2350 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002351 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002352 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2353 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002354 case BO_And: Result = LHS & RHS; return true;
2355 case BO_Xor: Result = LHS ^ RHS; return true;
2356 case BO_Or: Result = LHS | RHS; return true;
2357 case BO_Div:
2358 case BO_Rem:
2359 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002360 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002361 return false;
2362 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002363 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2364 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2365 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002366 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2367 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002368 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2369 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002370 return true;
2371 case BO_Shl: {
2372 if (Info.getLangOpts().OpenCL)
2373 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2374 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2375 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2376 RHS.isUnsigned());
2377 else if (RHS.isSigned() && RHS.isNegative()) {
2378 // During constant-folding, a negative shift is an opposite shift. Such
2379 // a shift is not a constant expression.
2380 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2381 RHS = -RHS;
2382 goto shift_right;
2383 }
2384 shift_left:
2385 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2386 // the shifted type.
2387 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2388 if (SA != RHS) {
2389 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2390 << RHS << E->getType() << LHS.getBitWidth();
2391 } else if (LHS.isSigned()) {
2392 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2393 // operand, and must not overflow the corresponding unsigned type.
2394 if (LHS.isNegative())
2395 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2396 else if (LHS.countLeadingZeros() < SA)
2397 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2398 }
2399 Result = LHS << SA;
2400 return true;
2401 }
2402 case BO_Shr: {
2403 if (Info.getLangOpts().OpenCL)
2404 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2405 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2406 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2407 RHS.isUnsigned());
2408 else if (RHS.isSigned() && RHS.isNegative()) {
2409 // During constant-folding, a negative shift is an opposite shift. Such a
2410 // shift is not a constant expression.
2411 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2412 RHS = -RHS;
2413 goto shift_left;
2414 }
2415 shift_right:
2416 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2417 // shifted type.
2418 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2419 if (SA != RHS)
2420 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2421 << RHS << E->getType() << LHS.getBitWidth();
2422 Result = LHS >> SA;
2423 return true;
2424 }
2425
2426 case BO_LT: Result = LHS < RHS; return true;
2427 case BO_GT: Result = LHS > RHS; return true;
2428 case BO_LE: Result = LHS <= RHS; return true;
2429 case BO_GE: Result = LHS >= RHS; return true;
2430 case BO_EQ: Result = LHS == RHS; return true;
2431 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002432 case BO_Cmp:
2433 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002434 }
2435}
2436
Richard Smith861b5b52013-05-07 23:34:45 +00002437/// Perform the given binary floating-point operation, in-place, on LHS.
2438static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2439 APFloat &LHS, BinaryOperatorKind Opcode,
2440 const APFloat &RHS) {
2441 switch (Opcode) {
2442 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002443 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002444 return false;
2445 case BO_Mul:
2446 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2447 break;
2448 case BO_Add:
2449 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2450 break;
2451 case BO_Sub:
2452 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2453 break;
2454 case BO_Div:
2455 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2456 break;
2457 }
2458
Richard Smith0c6124b2015-12-03 01:36:22 +00002459 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002460 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002461 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002462 }
Richard Smith861b5b52013-05-07 23:34:45 +00002463 return true;
2464}
2465
Richard Smitha8105bc2012-01-06 16:39:00 +00002466/// Cast an lvalue referring to a base subobject to a derived class, by
2467/// truncating the lvalue's path to the given length.
2468static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2469 const RecordDecl *TruncatedType,
2470 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002471 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002472
2473 // Check we actually point to a derived class object.
2474 if (TruncatedElements == D.Entries.size())
2475 return true;
2476 assert(TruncatedElements >= D.MostDerivedPathLength &&
2477 "not casting to a derived class");
2478 if (!Result.checkSubobject(Info, E, CSK_Derived))
2479 return false;
2480
2481 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002482 const RecordDecl *RD = TruncatedType;
2483 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002484 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002485 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2486 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002487 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002488 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002489 else
Richard Smithd62306a2011-11-10 06:34:14 +00002490 Result.Offset -= Layout.getBaseClassOffset(Base);
2491 RD = Base;
2492 }
Richard Smith027bf112011-11-17 22:56:20 +00002493 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002494 return true;
2495}
2496
John McCalld7bca762012-05-01 00:38:49 +00002497static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002498 const CXXRecordDecl *Derived,
2499 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002500 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002501 if (!RL) {
2502 if (Derived->isInvalidDecl()) return false;
2503 RL = &Info.Ctx.getASTRecordLayout(Derived);
2504 }
2505
Richard Smithd62306a2011-11-10 06:34:14 +00002506 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002507 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002508 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002509}
2510
Richard Smitha8105bc2012-01-06 16:39:00 +00002511static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002512 const CXXRecordDecl *DerivedDecl,
2513 const CXXBaseSpecifier *Base) {
2514 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2515
John McCalld7bca762012-05-01 00:38:49 +00002516 if (!Base->isVirtual())
2517 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002518
Richard Smitha8105bc2012-01-06 16:39:00 +00002519 SubobjectDesignator &D = Obj.Designator;
2520 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002521 return false;
2522
Richard Smitha8105bc2012-01-06 16:39:00 +00002523 // Extract most-derived object and corresponding type.
2524 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2525 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2526 return false;
2527
2528 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002529 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002530 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2531 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002532 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002533 return true;
2534}
2535
Richard Smith84401042013-06-03 05:03:02 +00002536static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2537 QualType Type, LValue &Result) {
2538 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2539 PathE = E->path_end();
2540 PathI != PathE; ++PathI) {
2541 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2542 *PathI))
2543 return false;
2544 Type = (*PathI)->getType();
2545 }
2546 return true;
2547}
2548
Richard Smith921f1322019-05-13 23:35:21 +00002549/// Cast an lvalue referring to a derived class to a known base subobject.
2550static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2551 const CXXRecordDecl *DerivedRD,
2552 const CXXRecordDecl *BaseRD) {
2553 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2554 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2555 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2556 llvm_unreachable("Class must be derived from the passed in base class!");
2557
2558 for (CXXBasePathElement &Elem : Paths.front())
2559 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2560 return false;
2561 return true;
2562}
2563
Richard Smithd62306a2011-11-10 06:34:14 +00002564/// Update LVal to refer to the given field, which must be a member of the type
2565/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002566static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002567 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002568 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002569 if (!RL) {
2570 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002571 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002572 }
Richard Smithd62306a2011-11-10 06:34:14 +00002573
2574 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002575 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002576 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002577 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002578}
2579
Richard Smith1b78b3d2012-01-25 22:15:11 +00002580/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002581static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002582 LValue &LVal,
2583 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002584 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002585 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002586 return false;
2587 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002588}
2589
Richard Smithd62306a2011-11-10 06:34:14 +00002590/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002591static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2592 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002593 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2594 // extension.
2595 if (Type->isVoidType() || Type->isFunctionType()) {
2596 Size = CharUnits::One();
2597 return true;
2598 }
2599
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002600 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002601 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002602 return false;
2603 }
2604
Richard Smithd62306a2011-11-10 06:34:14 +00002605 if (!Type->isConstantSizeType()) {
2606 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002607 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002608 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002609 return false;
2610 }
2611
2612 Size = Info.Ctx.getTypeSizeInChars(Type);
2613 return true;
2614}
2615
2616/// Update a pointer value to model pointer arithmetic.
2617/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002618/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002619/// \param LVal - The pointer value to be updated.
2620/// \param EltTy - The pointee type represented by LVal.
2621/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002622static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2623 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002624 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002625 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002626 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002627 return false;
2628
Yaxun Liu402804b2016-12-15 08:09:08 +00002629 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002630 return true;
2631}
2632
Richard Smithd6cc1982017-01-31 02:23:02 +00002633static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2634 LValue &LVal, QualType EltTy,
2635 int64_t Adjustment) {
2636 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2637 APSInt::get(Adjustment));
2638}
2639
Richard Smith66c96992012-02-18 22:04:06 +00002640/// Update an lvalue to refer to a component of a complex number.
2641/// \param Info - Information about the ongoing evaluation.
2642/// \param LVal - The lvalue to be updated.
2643/// \param EltTy - The complex number's component type.
2644/// \param Imag - False for the real component, true for the imaginary.
2645static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2646 LValue &LVal, QualType EltTy,
2647 bool Imag) {
2648 if (Imag) {
2649 CharUnits SizeOfComponent;
2650 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2651 return false;
2652 LVal.Offset += SizeOfComponent;
2653 }
2654 LVal.addComplex(Info, E, EltTy, Imag);
2655 return true;
2656}
2657
Faisal Vali051e3a22017-02-16 04:12:21 +00002658static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2659 QualType Type, const LValue &LVal,
2660 APValue &RVal);
2661
Richard Smith27908702011-10-24 17:54:18 +00002662/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002663///
2664/// \param Info Information about the ongoing evaluation.
2665/// \param E An expression to be used when printing diagnostics.
2666/// \param VD The variable whose initializer should be obtained.
2667/// \param Frame The frame in which the variable was created. Must be null
2668/// if this variable is not local to the evaluation.
2669/// \param Result Filled in with a pointer to the value of the variable.
2670static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2671 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002672 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002673
Richard Smith254a73d2011-10-28 22:34:42 +00002674 // If this is a parameter to an active constexpr function call, perform
2675 // argument substitution.
2676 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002677 // Assume arguments of a potential constant expression are unknown
2678 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002679 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002681 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002683 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002684 }
Richard Smith3229b742013-05-05 21:17:10 +00002685 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002686 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002687 }
Richard Smith27908702011-10-24 17:54:18 +00002688
Richard Smithd9f663b2013-04-22 15:31:51 +00002689 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002690 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002691 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2692 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002693 if (!Result) {
2694 // Assume variables referenced within a lambda's call operator that were
2695 // not declared within the call operator are captures and during checking
2696 // of a potential constant expression, assume they are unknown constant
2697 // expressions.
2698 assert(isLambdaCallOperator(Frame->Callee) &&
2699 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2700 "missing value for local variable");
2701 if (Info.checkingPotentialConstantExpression())
2702 return false;
2703 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002704 Info.FFDiag(E->getBeginLoc(),
2705 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002706 << "captures not currently allowed";
2707 return false;
2708 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002709 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002710 }
2711
Richard Smithd0b4dd62011-12-19 06:19:21 +00002712 // Dig out the initializer, and use the declaration which it's attached to.
2713 const Expr *Init = VD->getAnyInitializer(VD);
2714 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002715 // If we're checking a potential constant expression, the variable could be
2716 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002717 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002718 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002719 return false;
2720 }
2721
Richard Smithd62306a2011-11-10 06:34:14 +00002722 // If we're currently evaluating the initializer of this declaration, use that
2723 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002724 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002725 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002726 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002727 }
2728
Richard Smithcecf1842011-11-01 21:06:14 +00002729 // Never evaluate the initializer of a weak variable. We can't be sure that
2730 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002731 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002732 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002733 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002734 }
Richard Smithcecf1842011-11-01 21:06:14 +00002735
Richard Smithd0b4dd62011-12-19 06:19:21 +00002736 // Check that we can fold the initializer. In C++, we will have already done
2737 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002738 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002739 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002740 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002741 Notes.size() + 1) << VD;
2742 Info.Note(VD->getLocation(), diag::note_declared_at);
2743 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002744 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002745 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002746 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002747 Notes.size() + 1) << VD;
2748 Info.Note(VD->getLocation(), diag::note_declared_at);
2749 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002750 }
Richard Smith27908702011-10-24 17:54:18 +00002751
Richard Smith3229b742013-05-05 21:17:10 +00002752 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002753 return true;
Richard Smith27908702011-10-24 17:54:18 +00002754}
2755
Richard Smith11562c52011-10-28 17:51:58 +00002756static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002757 Qualifiers Quals = T.getQualifiers();
2758 return Quals.hasConst() && !Quals.hasVolatile();
2759}
2760
Richard Smithe97cbd72011-11-11 04:05:33 +00002761/// Get the base index of the given base class within an APValue representing
2762/// the given derived class.
2763static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2764 const CXXRecordDecl *Base) {
2765 Base = Base->getCanonicalDecl();
2766 unsigned Index = 0;
2767 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2768 E = Derived->bases_end(); I != E; ++I, ++Index) {
2769 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2770 return Index;
2771 }
2772
2773 llvm_unreachable("base class missing from derived class's bases list");
2774}
2775
Richard Smith3da88fa2013-04-26 14:36:30 +00002776/// Extract the value of a character from a string literal.
2777static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2778 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002779 assert(!isa<SourceLocExpr>(Lit) &&
2780 "SourceLocExpr should have already been converted to a StringLiteral");
2781
Akira Hatanakabc332642017-01-31 02:31:39 +00002782 // FIXME: Support MakeStringConstant
2783 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2784 std::string Str;
2785 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2786 assert(Index <= Str.size() && "Index too large");
2787 return APSInt::getUnsigned(Str.c_str()[Index]);
2788 }
2789
Alexey Bataevec474782014-10-09 08:45:04 +00002790 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2791 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002792 const StringLiteral *S = cast<StringLiteral>(Lit);
2793 const ConstantArrayType *CAT =
2794 Info.Ctx.getAsConstantArrayType(S->getType());
2795 assert(CAT && "string literal isn't an array");
2796 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002797 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002798
2799 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002800 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002801 if (Index < S->getLength())
2802 Value = S->getCodeUnit(Index);
2803 return Value;
2804}
2805
Richard Smith3da88fa2013-04-26 14:36:30 +00002806// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002807//
2808// FIXME: This is inefficient; we should probably introduce something similar
2809// to the LLVM ConstantDataArray to make this cheaper.
2810static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002811 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 const ConstantArrayType *CAT =
2813 Info.Ctx.getAsConstantArrayType(S->getType());
2814 assert(CAT && "string literal isn't an array");
2815 QualType CharType = CAT->getElementType();
2816 assert(CharType->isIntegerType() && "unexpected character type");
2817
2818 unsigned Elts = CAT->getSize().getZExtValue();
2819 Result = APValue(APValue::UninitArray(),
2820 std::min(S->getLength(), Elts), Elts);
2821 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2822 CharType->isUnsignedIntegerType());
2823 if (Result.hasArrayFiller())
2824 Result.getArrayFiller() = APValue(Value);
2825 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2826 Value = S->getCodeUnit(I);
2827 Result.getArrayInitializedElt(I) = APValue(Value);
2828 }
2829}
2830
2831// Expand an array so that it has more than Index filled elements.
2832static void expandArray(APValue &Array, unsigned Index) {
2833 unsigned Size = Array.getArraySize();
2834 assert(Index < Size);
2835
2836 // Always at least double the number of elements for which we store a value.
2837 unsigned OldElts = Array.getArrayInitializedElts();
2838 unsigned NewElts = std::max(Index+1, OldElts * 2);
2839 NewElts = std::min(Size, std::max(NewElts, 8u));
2840
2841 // Copy the data across.
2842 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2843 for (unsigned I = 0; I != OldElts; ++I)
2844 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2845 for (unsigned I = OldElts; I != NewElts; ++I)
2846 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2847 if (NewValue.hasArrayFiller())
2848 NewValue.getArrayFiller() = Array.getArrayFiller();
2849 Array.swap(NewValue);
2850}
2851
Richard Smithb01fe402014-09-16 01:24:02 +00002852/// Determine whether a type would actually be read by an lvalue-to-rvalue
2853/// conversion. If it's of class type, we may assume that the copy operation
2854/// is trivial. Note that this is never true for a union type with fields
2855/// (because the copy always "reads" the active member) and always true for
2856/// a non-class type.
2857static bool isReadByLvalueToRvalueConversion(QualType T) {
2858 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2859 if (!RD || (RD->isUnion() && !RD->field_empty()))
2860 return true;
2861 if (RD->isEmpty())
2862 return false;
2863
2864 for (auto *Field : RD->fields())
2865 if (isReadByLvalueToRvalueConversion(Field->getType()))
2866 return true;
2867
2868 for (auto &BaseSpec : RD->bases())
2869 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2870 return true;
2871
2872 return false;
2873}
2874
2875/// Diagnose an attempt to read from any unreadable field within the specified
2876/// type, which might be a class type.
2877static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2878 QualType T) {
2879 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2880 if (!RD)
2881 return false;
2882
2883 if (!RD->hasMutableFields())
2884 return false;
2885
2886 for (auto *Field : RD->fields()) {
2887 // If we're actually going to read this field in some way, then it can't
2888 // be mutable. If we're in a union, then assigning to a mutable field
2889 // (even an empty one) can change the active member, so that's not OK.
2890 // FIXME: Add core issue number for the union case.
2891 if (Field->isMutable() &&
2892 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002893 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002894 Info.Note(Field->getLocation(), diag::note_declared_at);
2895 return true;
2896 }
2897
2898 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2899 return true;
2900 }
2901
2902 for (auto &BaseSpec : RD->bases())
2903 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2904 return true;
2905
2906 // All mutable fields were empty, and thus not actually read.
2907 return false;
2908}
2909
Richard Smithdebad642019-05-12 09:39:08 +00002910static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2911 APValue::LValueBase Base) {
2912 // A temporary we created.
2913 if (Base.getCallIndex())
2914 return true;
2915
2916 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2917 if (!Evaluating)
2918 return false;
2919
2920 // The variable whose initializer we're evaluating.
2921 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2922 if (declaresSameEntity(Evaluating, BaseD))
2923 return true;
2924
2925 // A temporary lifetime-extended by the variable whose initializer we're
2926 // evaluating.
2927 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2928 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2929 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2930 return true;
2931
2932 return false;
2933}
2934
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002935namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002936/// A handle to a complete object (an object that is not a subobject of
2937/// another object).
2938struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002939 /// The identity of the object.
2940 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002941 /// The value of the complete object.
2942 APValue *Value;
2943 /// The type of the complete object.
2944 QualType Type;
2945
Craig Topper36250ad2014-05-12 05:36:57 +00002946 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002947 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2948 : Base(Base), Value(Value), Type(Type) {}
2949
2950 bool mayReadMutableMembers(EvalInfo &Info) const {
2951 // In C++14 onwards, it is permitted to read a mutable member whose
2952 // lifetime began within the evaluation.
2953 // FIXME: Should we also allow this in C++11?
2954 if (!Info.getLangOpts().CPlusPlus14)
2955 return false;
2956 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002957 }
2958
Richard Smithdebad642019-05-12 09:39:08 +00002959 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002960};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002961} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002962
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002963static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2964 bool IsMutable = false) {
2965 // C++ [basic.type.qualifier]p1:
2966 // - A const object is an object of type const T or a non-mutable subobject
2967 // of a const object.
2968 if (ObjType.isConstQualified() && !IsMutable)
2969 SubobjType.addConst();
2970 // - A volatile object is an object of type const T or a subobject of a
2971 // volatile object.
2972 if (ObjType.isVolatileQualified())
2973 SubobjType.addVolatile();
2974 return SubobjType;
2975}
2976
Richard Smith3da88fa2013-04-26 14:36:30 +00002977/// Find the designated sub-object of an rvalue.
2978template<typename SubobjectHandler>
2979typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002980findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002981 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002982 if (Sub.Invalid)
2983 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002984 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002985 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002986 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002987 Info.FFDiag(E, Sub.isOnePastTheEnd()
2988 ? diag::note_constexpr_access_past_end
2989 : diag::note_constexpr_access_unsized_array)
2990 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002991 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002993 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002994 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002995
Richard Smith3229b742013-05-05 21:17:10 +00002996 APValue *O = Obj.Value;
2997 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002998 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002999 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003000
Richard Smithd62306a2011-11-10 06:34:14 +00003001 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003002 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003003 // Reading an indeterminate value is undefined, but assigning over one is OK.
3004 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003005 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003006 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003007 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003008 return handler.failed();
3009 }
3010
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003011 // C++ [class.ctor]p5:
3012 // const and volatile semantics are not applied on an object under
3013 // construction.
3014 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3015 ObjType->isRecordType() &&
3016 Info.isEvaluatingConstructor(
3017 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3018 Sub.Entries.begin() + I)) !=
3019 ConstructionPhase::None) {
3020 ObjType = Info.Ctx.getCanonicalType(ObjType);
3021 ObjType.removeLocalConst();
3022 ObjType.removeLocalVolatile();
3023 }
3024
3025 // If this is our last pass, check that the final object type is OK.
3026 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3027 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003028 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003029 if (Info.getLangOpts().CPlusPlus) {
3030 int DiagKind;
3031 SourceLocation Loc;
3032 const NamedDecl *Decl = nullptr;
3033 if (VolatileField) {
3034 DiagKind = 2;
3035 Loc = VolatileField->getLocation();
3036 Decl = VolatileField;
3037 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3038 DiagKind = 1;
3039 Loc = VD->getLocation();
3040 Decl = VD;
3041 } else {
3042 DiagKind = 0;
3043 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3044 Loc = E->getExprLoc();
3045 }
3046 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3047 << handler.AccessKind << DiagKind << Decl;
3048 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3049 } else {
3050 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3051 }
3052 return handler.failed();
3053 }
3054
Richard Smithb01fe402014-09-16 01:24:02 +00003055 // If we are reading an object of class type, there may still be more
3056 // things we need to check: if there are any mutable subobjects, we
3057 // cannot perform this read. (This only happens when performing a trivial
3058 // copy or assignment.)
3059 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003060 !Obj.mayReadMutableMembers(Info) &&
3061 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003062 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003063 }
Richard Smithb01fe402014-09-16 01:24:02 +00003064
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003065 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003066 if (!handler.found(*O, ObjType))
3067 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003068
Richard Smith49ca8aa2013-08-06 07:09:20 +00003069 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003070 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003071 LastField && LastField->isBitField() &&
3072 !truncateBitfieldValue(Info, E, *O, LastField))
3073 return false;
3074
3075 return true;
3076 }
3077
Craig Topper36250ad2014-05-12 05:36:57 +00003078 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003079 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003080 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003081 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003082 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003083 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003084 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003085 // Note, it should not be possible to form a pointer with a valid
3086 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003087 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003088 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003089 << handler.AccessKind;
3090 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003091 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003092 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003093 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003094
3095 ObjType = CAT->getElementType();
3096
Richard Smith3da88fa2013-04-26 14:36:30 +00003097 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003098 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003099 else if (handler.AccessKind != AK_Read) {
3100 expandArray(*O, Index);
3101 O = &O->getArrayInitializedElt(Index);
3102 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003103 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003104 } else if (ObjType->isAnyComplexType()) {
3105 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003106 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003107 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003108 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003109 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003110 << handler.AccessKind;
3111 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003112 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003113 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003114 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003115
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003116 ObjType = getSubobjectType(
3117 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003118
Richard Smith66c96992012-02-18 22:04:06 +00003119 assert(I == N - 1 && "extracting subobject of scalar?");
3120 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003121 return handler.found(Index ? O->getComplexIntImag()
3122 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003123 } else {
3124 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003125 return handler.found(Index ? O->getComplexFloatImag()
3126 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003127 }
Richard Smithd62306a2011-11-10 06:34:14 +00003128 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003129 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003130 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003131 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003132 << Field;
3133 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003134 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003135 }
3136
Richard Smithd62306a2011-11-10 06:34:14 +00003137 // Next subobject is a class, struct or union field.
3138 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3139 if (RD->isUnion()) {
3140 const FieldDecl *UnionField = O->getUnionField();
3141 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003142 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003143 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003144 << handler.AccessKind << Field << !UnionField << UnionField;
3145 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003146 }
Richard Smithd62306a2011-11-10 06:34:14 +00003147 O = &O->getUnionValue();
3148 } else
3149 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003150
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003151 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003152 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003153 if (Field->getType().isVolatileQualified())
3154 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003155 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003156 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003157 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3158 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3159 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003160
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003161 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003162 }
3163 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003164}
3165
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003166namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003167struct ExtractSubobjectHandler {
3168 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003169 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003170
3171 static const AccessKinds AccessKind = AK_Read;
3172
3173 typedef bool result_type;
3174 bool failed() { return false; }
3175 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003176 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003177 return true;
3178 }
3179 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003180 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003181 return true;
3182 }
3183 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003184 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003185 return true;
3186 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003187};
Richard Smith3229b742013-05-05 21:17:10 +00003188} // end anonymous namespace
3189
Richard Smith3da88fa2013-04-26 14:36:30 +00003190const AccessKinds ExtractSubobjectHandler::AccessKind;
3191
3192/// Extract the designated sub-object of an rvalue.
3193static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003194 const CompleteObject &Obj,
3195 const SubobjectDesignator &Sub,
3196 APValue &Result) {
3197 ExtractSubobjectHandler Handler = { Info, Result };
3198 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003199}
3200
Richard Smith3229b742013-05-05 21:17:10 +00003201namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003202struct ModifySubobjectHandler {
3203 EvalInfo &Info;
3204 APValue &NewVal;
3205 const Expr *E;
3206
3207 typedef bool result_type;
3208 static const AccessKinds AccessKind = AK_Assign;
3209
3210 bool checkConst(QualType QT) {
3211 // Assigning to a const object has undefined behavior.
3212 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003213 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003214 return false;
3215 }
3216 return true;
3217 }
3218
3219 bool failed() { return false; }
3220 bool found(APValue &Subobj, QualType SubobjType) {
3221 if (!checkConst(SubobjType))
3222 return false;
3223 // We've been given ownership of NewVal, so just swap it in.
3224 Subobj.swap(NewVal);
3225 return true;
3226 }
3227 bool found(APSInt &Value, QualType SubobjType) {
3228 if (!checkConst(SubobjType))
3229 return false;
3230 if (!NewVal.isInt()) {
3231 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003232 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003233 return false;
3234 }
3235 Value = NewVal.getInt();
3236 return true;
3237 }
3238 bool found(APFloat &Value, QualType SubobjType) {
3239 if (!checkConst(SubobjType))
3240 return false;
3241 Value = NewVal.getFloat();
3242 return true;
3243 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003244};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003245} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003246
Richard Smith3229b742013-05-05 21:17:10 +00003247const AccessKinds ModifySubobjectHandler::AccessKind;
3248
Richard Smith3da88fa2013-04-26 14:36:30 +00003249/// Update the designated sub-object of an rvalue to the given value.
3250static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003251 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003252 const SubobjectDesignator &Sub,
3253 APValue &NewVal) {
3254 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003255 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003256}
3257
Richard Smith84f6dcf2012-02-02 01:16:57 +00003258/// Find the position where two subobject designators diverge, or equivalently
3259/// the length of the common initial subsequence.
3260static unsigned FindDesignatorMismatch(QualType ObjType,
3261 const SubobjectDesignator &A,
3262 const SubobjectDesignator &B,
3263 bool &WasArrayIndex) {
3264 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3265 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003266 if (!ObjType.isNull() &&
3267 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003268 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003269 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003270 WasArrayIndex = true;
3271 return I;
3272 }
Richard Smith66c96992012-02-18 22:04:06 +00003273 if (ObjType->isAnyComplexType())
3274 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3275 else
3276 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003277 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003278 if (A.Entries[I].getAsBaseOrMember() !=
3279 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003280 WasArrayIndex = false;
3281 return I;
3282 }
3283 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3284 // Next subobject is a field.
3285 ObjType = FD->getType();
3286 else
3287 // Next subobject is a base class.
3288 ObjType = QualType();
3289 }
3290 }
3291 WasArrayIndex = false;
3292 return I;
3293}
3294
3295/// Determine whether the given subobject designators refer to elements of the
3296/// same array object.
3297static bool AreElementsOfSameArray(QualType ObjType,
3298 const SubobjectDesignator &A,
3299 const SubobjectDesignator &B) {
3300 if (A.Entries.size() != B.Entries.size())
3301 return false;
3302
George Burgess IVa51c4072015-10-16 01:49:01 +00003303 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003304 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3305 // A is a subobject of the array element.
3306 return false;
3307
3308 // If A (and B) designates an array element, the last entry will be the array
3309 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3310 // of length 1' case, and the entire path must match.
3311 bool WasArrayIndex;
3312 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3313 return CommonLength >= A.Entries.size() - IsArray;
3314}
3315
Richard Smith3229b742013-05-05 21:17:10 +00003316/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003317static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3318 AccessKinds AK, const LValue &LVal,
3319 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003320 if (LVal.InvalidBase) {
3321 Info.FFDiag(E);
3322 return CompleteObject();
3323 }
3324
Richard Smith3229b742013-05-05 21:17:10 +00003325 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003326 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003327 return CompleteObject();
3328 }
3329
Craig Topper36250ad2014-05-12 05:36:57 +00003330 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003331 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003332 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003333 std::tie(Frame, Depth) =
3334 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003335 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003336 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003337 << AK << LVal.Base.is<const ValueDecl*>();
3338 NoteLValueLocation(Info, LVal.Base);
3339 return CompleteObject();
3340 }
Richard Smith3229b742013-05-05 21:17:10 +00003341 }
3342
Richard Smith7bd54ab2019-05-15 20:22:21 +00003343 bool IsAccess = isFormalAccess(AK);
3344
Richard Smith3229b742013-05-05 21:17:10 +00003345 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3346 // is not a constant expression (even if the object is non-volatile). We also
3347 // apply this rule to C++98, in order to conform to the expected 'volatile'
3348 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003349 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003350 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003351 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003352 << AK << LValType;
3353 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003354 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003355 return CompleteObject();
3356 }
3357
3358 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003359 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003360 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003361
3362 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3363 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3364 // In C++11, constexpr, non-volatile variables initialized with constant
3365 // expressions are constant expressions too. Inside constexpr functions,
3366 // parameters are constant expressions even if they're non-const.
3367 // In C++1y, objects local to a constant expression (those with a Frame) are
3368 // both readable and writable inside constant expressions.
3369 // In C, such things can also be folded, although they are not ICEs.
3370 const VarDecl *VD = dyn_cast<VarDecl>(D);
3371 if (VD) {
3372 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3373 VD = VDef;
3374 }
3375 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003376 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003377 return CompleteObject();
3378 }
3379
Richard Smith3229b742013-05-05 21:17:10 +00003380 // Unless we're looking at a local variable or argument in a constexpr call,
3381 // the variable we're reading must be const.
3382 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003383 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003384 declaresSameEntity(
3385 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003386 // OK, we can read and modify an object if we're in the process of
3387 // evaluating its initializer, because its lifetime began in this
3388 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003389 } else if (isModification(AK)) {
3390 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003391 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003392 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003393 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003394 // OK, we can read this variable.
3395 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003396 // In OpenCL if a variable is in constant address space it is a const
3397 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003398 if (!(BaseType.isConstQualified() ||
3399 (Info.getLangOpts().OpenCL &&
3400 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003401 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003402 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003403 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003404 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003405 Info.Note(VD->getLocation(), diag::note_declared_at);
3406 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003407 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003408 }
3409 return CompleteObject();
3410 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003411 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003412 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003413 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3414 // We support folding of const floating-point types, in order to make
3415 // static const data members of such types (supported as an extension)
3416 // more useful.
3417 if (Info.getLangOpts().CPlusPlus11) {
3418 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3419 Info.Note(VD->getLocation(), diag::note_declared_at);
3420 } else {
3421 Info.CCEDiag(E);
3422 }
George Burgess IVb5316982016-12-27 05:33:20 +00003423 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3424 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3425 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003426 } else {
3427 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003428 if (Info.checkingPotentialConstantExpression() &&
3429 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3430 // The definition of this variable could be constexpr. We can't
3431 // access it right now, but may be able to in future.
3432 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003433 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003434 Info.Note(VD->getLocation(), diag::note_declared_at);
3435 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003436 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003437 }
3438 return CompleteObject();
3439 }
3440 }
3441
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003442 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003443 return CompleteObject();
3444 } else {
3445 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3446
3447 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003448 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003449 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003450 assert(MTE->getStorageDuration() == SD_Static &&
3451 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003452
Richard Smithe6c01442013-06-05 00:46:14 +00003453 // Per C++1y [expr.const]p2:
3454 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3455 // - a [...] glvalue of integral or enumeration type that refers to
3456 // a non-volatile const object [...]
3457 // [...]
3458 // - a [...] glvalue of literal type that refers to a non-volatile
3459 // object whose lifetime began within the evaluation of e.
3460 //
3461 // C++11 misses the 'began within the evaluation of e' check and
3462 // instead allows all temporaries, including things like:
3463 // int &&r = 1;
3464 // int x = ++r;
3465 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003466 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003467 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3468 const ValueDecl *ED = MTE->getExtendingDecl();
3469 if (!(BaseType.isConstQualified() &&
3470 BaseType->isIntegralOrEnumerationType()) &&
3471 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003472 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003473 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003474 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003475 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3476 return CompleteObject();
3477 }
3478
3479 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3480 assert(BaseVal && "got reference to unevaluated temporary");
3481 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003482 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003483 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003484 APValue Val;
3485 LVal.moveInto(Val);
3486 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3487 << AK
3488 << Val.getAsString(Info.Ctx,
3489 Info.Ctx.getLValueReferenceType(LValType));
3490 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003491 return CompleteObject();
3492 }
3493 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003494 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003495 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003496 }
Richard Smith7525ff62013-05-09 07:14:00 +00003497 }
3498
Richard Smith9defb7d2018-02-21 03:38:30 +00003499 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003500 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003501 //
3502 // FIXME: Not all local state is mutable. Allow local constant subobjects
3503 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003504 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3505 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003506 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003507 return CompleteObject();
3508
Richard Smithdebad642019-05-12 09:39:08 +00003509 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003510}
3511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003512/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003513/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3514/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003515///
3516/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003517/// \param Conv - The expression for which we are performing the conversion.
3518/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003519/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3520/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003521/// \param LVal - The glvalue on which we are attempting to perform this action.
3522/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003523static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003525 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003526 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003527 return false;
3528
Richard Smith3229b742013-05-05 21:17:10 +00003529 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003530 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003531
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003532 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003533 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3534 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3535 // initializer until now for such expressions. Such an expression can't be
3536 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003537 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003538 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003539 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003540 }
Richard Smith3229b742013-05-05 21:17:10 +00003541 APValue Lit;
3542 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3543 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003544 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003545 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003546 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003547 // Special-case character extraction so we don't have to construct an
3548 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003549 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003550 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003551 if (LVal.Designator.Entries.empty()) {
3552 // Fail for now for LValue to RValue conversion of an array.
3553 // (This shouldn't show up in C/C++, but it could be triggered by a
3554 // weird EvaluateAsRValue call from a tool.)
3555 Info.FFDiag(Conv);
3556 return false;
3557 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003558 if (LVal.Designator.isOnePastTheEnd()) {
3559 if (Info.getLangOpts().CPlusPlus11)
3560 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3561 else
3562 Info.FFDiag(Conv);
3563 return false;
3564 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003565 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003566 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3567 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003568 }
Richard Smith11562c52011-10-28 17:51:58 +00003569 }
3570
Richard Smith3229b742013-05-05 21:17:10 +00003571 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3572 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003573}
3574
3575/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003576static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003577 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003578 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003579 return false;
3580
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003581 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003582 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003583 return false;
3584 }
3585
Richard Smith3229b742013-05-05 21:17:10 +00003586 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003587 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3588}
3589
3590namespace {
3591struct CompoundAssignSubobjectHandler {
3592 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003593 const Expr *E;
3594 QualType PromotedLHSType;
3595 BinaryOperatorKind Opcode;
3596 const APValue &RHS;
3597
3598 static const AccessKinds AccessKind = AK_Assign;
3599
3600 typedef bool result_type;
3601
3602 bool checkConst(QualType QT) {
3603 // Assigning to a const object has undefined behavior.
3604 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003605 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003606 return false;
3607 }
3608 return true;
3609 }
3610
3611 bool failed() { return false; }
3612 bool found(APValue &Subobj, QualType SubobjType) {
3613 switch (Subobj.getKind()) {
3614 case APValue::Int:
3615 return found(Subobj.getInt(), SubobjType);
3616 case APValue::Float:
3617 return found(Subobj.getFloat(), SubobjType);
3618 case APValue::ComplexInt:
3619 case APValue::ComplexFloat:
3620 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003621 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003622 return false;
3623 case APValue::LValue:
3624 return foundPointer(Subobj, SubobjType);
3625 default:
3626 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003627 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003628 return false;
3629 }
3630 }
3631 bool found(APSInt &Value, QualType SubobjType) {
3632 if (!checkConst(SubobjType))
3633 return false;
3634
Tan S. B.9f935e82018-12-18 07:38:06 +00003635 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003636 // We don't support compound assignment on integer-cast-to-pointer
3637 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003638 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003639 return false;
3640 }
3641
Tan S. B.9f935e82018-12-18 07:38:06 +00003642 if (RHS.isInt()) {
3643 APSInt LHS =
3644 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3645 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3646 return false;
3647 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3648 return true;
3649 } else if (RHS.isFloat()) {
3650 APFloat FValue(0.0);
3651 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3652 FValue) &&
3653 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3654 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3655 Value);
3656 }
3657
3658 Info.FFDiag(E);
3659 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003660 }
3661 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003662 return checkConst(SubobjType) &&
3663 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3664 Value) &&
3665 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3666 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003667 }
3668 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3669 if (!checkConst(SubobjType))
3670 return false;
3671
3672 QualType PointeeType;
3673 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3674 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003675
3676 if (PointeeType.isNull() || !RHS.isInt() ||
3677 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003678 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003679 return false;
3680 }
3681
Richard Smithd6cc1982017-01-31 02:23:02 +00003682 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003683 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003684 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003685
3686 LValue LVal;
3687 LVal.setFrom(Info.Ctx, Subobj);
3688 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3689 return false;
3690 LVal.moveInto(Subobj);
3691 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003692 }
Richard Smith43e77732013-05-07 04:50:00 +00003693};
3694} // end anonymous namespace
3695
3696const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3697
3698/// Perform a compound assignment of LVal <op>= RVal.
3699static bool handleCompoundAssignment(
3700 EvalInfo &Info, const Expr *E,
3701 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3702 BinaryOperatorKind Opcode, const APValue &RVal) {
3703 if (LVal.Designator.Invalid)
3704 return false;
3705
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003706 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003707 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003708 return false;
3709 }
3710
3711 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3712 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3713 RVal };
3714 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3715}
3716
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003717namespace {
3718struct IncDecSubobjectHandler {
3719 EvalInfo &Info;
3720 const UnaryOperator *E;
3721 AccessKinds AccessKind;
3722 APValue *Old;
3723
Richard Smith243ef902013-05-05 23:31:59 +00003724 typedef bool result_type;
3725
3726 bool checkConst(QualType QT) {
3727 // Assigning to a const object has undefined behavior.
3728 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003729 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003730 return false;
3731 }
3732 return true;
3733 }
3734
3735 bool failed() { return false; }
3736 bool found(APValue &Subobj, QualType SubobjType) {
3737 // Stash the old value. Also clear Old, so we don't clobber it later
3738 // if we're post-incrementing a complex.
3739 if (Old) {
3740 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003741 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003742 }
3743
3744 switch (Subobj.getKind()) {
3745 case APValue::Int:
3746 return found(Subobj.getInt(), SubobjType);
3747 case APValue::Float:
3748 return found(Subobj.getFloat(), SubobjType);
3749 case APValue::ComplexInt:
3750 return found(Subobj.getComplexIntReal(),
3751 SubobjType->castAs<ComplexType>()->getElementType()
3752 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3753 case APValue::ComplexFloat:
3754 return found(Subobj.getComplexFloatReal(),
3755 SubobjType->castAs<ComplexType>()->getElementType()
3756 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3757 case APValue::LValue:
3758 return foundPointer(Subobj, SubobjType);
3759 default:
3760 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003761 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003762 return false;
3763 }
3764 }
3765 bool found(APSInt &Value, QualType SubobjType) {
3766 if (!checkConst(SubobjType))
3767 return false;
3768
3769 if (!SubobjType->isIntegerType()) {
3770 // We don't support increment / decrement on integer-cast-to-pointer
3771 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003772 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003773 return false;
3774 }
3775
3776 if (Old) *Old = APValue(Value);
3777
3778 // bool arithmetic promotes to int, and the conversion back to bool
3779 // doesn't reduce mod 2^n, so special-case it.
3780 if (SubobjType->isBooleanType()) {
3781 if (AccessKind == AK_Increment)
3782 Value = 1;
3783 else
3784 Value = !Value;
3785 return true;
3786 }
3787
3788 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003789 if (AccessKind == AK_Increment) {
3790 ++Value;
3791
3792 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3793 APSInt ActualValue(Value, /*IsUnsigned*/true);
3794 return HandleOverflow(Info, E, ActualValue, SubobjType);
3795 }
3796 } else {
3797 --Value;
3798
3799 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3800 unsigned BitWidth = Value.getBitWidth();
3801 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3802 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003803 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003804 }
3805 }
3806 return true;
3807 }
3808 bool found(APFloat &Value, QualType SubobjType) {
3809 if (!checkConst(SubobjType))
3810 return false;
3811
3812 if (Old) *Old = APValue(Value);
3813
3814 APFloat One(Value.getSemantics(), 1);
3815 if (AccessKind == AK_Increment)
3816 Value.add(One, APFloat::rmNearestTiesToEven);
3817 else
3818 Value.subtract(One, APFloat::rmNearestTiesToEven);
3819 return true;
3820 }
3821 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3822 if (!checkConst(SubobjType))
3823 return false;
3824
3825 QualType PointeeType;
3826 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3827 PointeeType = PT->getPointeeType();
3828 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003829 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003830 return false;
3831 }
3832
3833 LValue LVal;
3834 LVal.setFrom(Info.Ctx, Subobj);
3835 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3836 AccessKind == AK_Increment ? 1 : -1))
3837 return false;
3838 LVal.moveInto(Subobj);
3839 return true;
3840 }
Richard Smith243ef902013-05-05 23:31:59 +00003841};
3842} // end anonymous namespace
3843
3844/// Perform an increment or decrement on LVal.
3845static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3846 QualType LValType, bool IsIncrement, APValue *Old) {
3847 if (LVal.Designator.Invalid)
3848 return false;
3849
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003850 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003851 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003852 return false;
3853 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003854
3855 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3856 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3857 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3858 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3859}
3860
Richard Smithe97cbd72011-11-11 04:05:33 +00003861/// Build an lvalue for the object argument of a member function call.
3862static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3863 LValue &This) {
3864 if (Object->getType()->isPointerType())
3865 return EvaluatePointer(Object, This, Info);
3866
3867 if (Object->isGLValue())
3868 return EvaluateLValue(Object, This, Info);
3869
Richard Smithd9f663b2013-04-22 15:31:51 +00003870 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003871 return EvaluateTemporary(Object, This, Info);
3872
Faisal Valie690b7a2016-07-02 22:34:24 +00003873 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003874 return false;
3875}
3876
3877/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3878/// lvalue referring to the result.
3879///
3880/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003881/// \param LV - An lvalue referring to the base of the member pointer.
3882/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003883/// \param IncludeMember - Specifies whether the member itself is included in
3884/// the resulting LValue subobject designator. This is not possible when
3885/// creating a bound member function.
3886/// \return The field or method declaration to which the member pointer refers,
3887/// or 0 if evaluation fails.
3888static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003889 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003890 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003891 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003892 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003893 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003894 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003895 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003896
3897 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3898 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003899 if (!MemPtr.getDecl()) {
3900 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003901 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003902 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003903 }
Richard Smith253c2a32012-01-27 01:14:48 +00003904
Richard Smith027bf112011-11-17 22:56:20 +00003905 if (MemPtr.isDerivedMember()) {
3906 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003907 // The end of the derived-to-base path for the base object must match the
3908 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003909 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003910 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003911 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003912 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003913 }
Richard Smith027bf112011-11-17 22:56:20 +00003914 unsigned PathLengthToMember =
3915 LV.Designator.Entries.size() - MemPtr.Path.size();
3916 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3917 const CXXRecordDecl *LVDecl = getAsBaseClass(
3918 LV.Designator.Entries[PathLengthToMember + I]);
3919 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003920 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003921 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003922 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003923 }
Richard Smith027bf112011-11-17 22:56:20 +00003924 }
3925
3926 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003927 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003928 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003929 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003930 } else if (!MemPtr.Path.empty()) {
3931 // Extend the LValue path with the member pointer's path.
3932 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3933 MemPtr.Path.size() + IncludeMember);
3934
3935 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003936 if (const PointerType *PT = LVType->getAs<PointerType>())
3937 LVType = PT->getPointeeType();
3938 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3939 assert(RD && "member pointer access on non-class-type expression");
3940 // The first class in the path is that of the lvalue.
3941 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3942 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003943 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003944 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003945 RD = Base;
3946 }
3947 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003948 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3949 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003950 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003951 }
3952
3953 // Add the member. Note that we cannot build bound member functions here.
3954 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003955 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003956 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003957 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003958 } else if (const IndirectFieldDecl *IFD =
3959 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003960 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003961 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003962 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003963 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003964 }
Richard Smith027bf112011-11-17 22:56:20 +00003965 }
3966
3967 return MemPtr.getDecl();
3968}
3969
Richard Smith84401042013-06-03 05:03:02 +00003970static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3971 const BinaryOperator *BO,
3972 LValue &LV,
3973 bool IncludeMember = true) {
3974 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3975
3976 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003977 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003978 MemberPtr MemPtr;
3979 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3980 }
Craig Topper36250ad2014-05-12 05:36:57 +00003981 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003982 }
3983
3984 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3985 BO->getRHS(), IncludeMember);
3986}
3987
Richard Smith027bf112011-11-17 22:56:20 +00003988/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3989/// the provided lvalue, which currently refers to the base object.
3990static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3991 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003992 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003993 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003994 return false;
3995
Richard Smitha8105bc2012-01-06 16:39:00 +00003996 QualType TargetQT = E->getType();
3997 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3998 TargetQT = PT->getPointeeType();
3999
4000 // Check this cast lands within the final derived-to-base subobject path.
4001 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004002 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004003 << D.MostDerivedType << TargetQT;
4004 return false;
4005 }
4006
Richard Smith027bf112011-11-17 22:56:20 +00004007 // Check the type of the final cast. We don't need to check the path,
4008 // since a cast can only be formed if the path is unique.
4009 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004010 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4011 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004012 if (NewEntriesSize == D.MostDerivedPathLength)
4013 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4014 else
Richard Smith027bf112011-11-17 22:56:20 +00004015 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004016 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004017 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004018 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004019 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004020 }
Richard Smith027bf112011-11-17 22:56:20 +00004021
4022 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004023 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004024}
4025
Mike Stump876387b2009-10-27 22:09:17 +00004026namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004027enum EvalStmtResult {
4028 /// Evaluation failed.
4029 ESR_Failed,
4030 /// Hit a 'return' statement.
4031 ESR_Returned,
4032 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004033 ESR_Succeeded,
4034 /// Hit a 'continue' statement.
4035 ESR_Continue,
4036 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004037 ESR_Break,
4038 /// Still scanning for 'case' or 'default' statement.
4039 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004040};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004041}
Richard Smith254a73d2011-10-28 22:34:42 +00004042
Richard Smith97fcf4b2016-08-14 23:15:52 +00004043static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4044 // We don't need to evaluate the initializer for a static local.
4045 if (!VD->hasLocalStorage())
4046 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004047
Richard Smith97fcf4b2016-08-14 23:15:52 +00004048 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004049 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00004050
Richard Smith97fcf4b2016-08-14 23:15:52 +00004051 const Expr *InitE = VD->getInit();
4052 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004053 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4054 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00004055 Val = APValue();
4056 return false;
4057 }
Richard Smith51f03172013-06-20 03:00:05 +00004058
Richard Smith97fcf4b2016-08-14 23:15:52 +00004059 if (InitE->isValueDependent())
4060 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004061
Richard Smith97fcf4b2016-08-14 23:15:52 +00004062 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4063 // Wipe out any partially-computed value, to allow tracking that this
4064 // evaluation failed.
4065 Val = APValue();
4066 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004067 }
4068
4069 return true;
4070}
4071
Richard Smith97fcf4b2016-08-14 23:15:52 +00004072static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4073 bool OK = true;
4074
4075 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4076 OK &= EvaluateVarDecl(Info, VD);
4077
4078 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4079 for (auto *BD : DD->bindings())
4080 if (auto *VD = BD->getHoldingVar())
4081 OK &= EvaluateDecl(Info, VD);
4082
4083 return OK;
4084}
4085
4086
Richard Smith4e18ca52013-05-06 05:56:11 +00004087/// Evaluate a condition (either a variable declaration or an expression).
4088static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4089 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004090 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004091 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4092 return false;
4093 return EvaluateAsBooleanCondition(Cond, Result, Info);
4094}
4095
Richard Smith89210072016-04-04 23:29:43 +00004096namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004097/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004098/// statement should be stored.
4099struct StmtResult {
4100 /// The APValue that should be filled in with the returned value.
4101 APValue &Value;
4102 /// The location containing the result, if any (used to support RVO).
4103 const LValue *Slot;
4104};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004105
4106struct TempVersionRAII {
4107 CallStackFrame &Frame;
4108
4109 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4110 Frame.pushTempVersion();
4111 }
4112
4113 ~TempVersionRAII() {
4114 Frame.popTempVersion();
4115 }
4116};
4117
Richard Smith89210072016-04-04 23:29:43 +00004118}
Richard Smith52a980a2015-08-28 02:43:42 +00004119
4120static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004121 const Stmt *S,
4122 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004123
4124/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004125static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004126 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004127 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004129 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004130 case ESR_Break:
4131 return ESR_Succeeded;
4132 case ESR_Succeeded:
4133 case ESR_Continue:
4134 return ESR_Continue;
4135 case ESR_Failed:
4136 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004137 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004138 return ESR;
4139 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004140 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004141}
4142
Richard Smith496ddcf2013-05-12 17:32:42 +00004143/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004144static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004145 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 BlockScopeRAII Scope(Info);
4147
Richard Smith496ddcf2013-05-12 17:32:42 +00004148 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004149 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004150 {
4151 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004152 if (const Stmt *Init = SS->getInit()) {
4153 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4154 if (ESR != ESR_Succeeded)
4155 return ESR;
4156 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004157 if (SS->getConditionVariable() &&
4158 !EvaluateDecl(Info, SS->getConditionVariable()))
4159 return ESR_Failed;
4160 if (!EvaluateInteger(SS->getCond(), Value, Info))
4161 return ESR_Failed;
4162 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004163
4164 // Find the switch case corresponding to the value of the condition.
4165 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004166 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004167 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4168 SC = SC->getNextSwitchCase()) {
4169 if (isa<DefaultStmt>(SC)) {
4170 Found = SC;
4171 continue;
4172 }
4173
4174 const CaseStmt *CS = cast<CaseStmt>(SC);
4175 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4176 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4177 : LHS;
4178 if (LHS <= Value && Value <= RHS) {
4179 Found = SC;
4180 break;
4181 }
4182 }
4183
4184 if (!Found)
4185 return ESR_Succeeded;
4186
4187 // Search the switch body for the switch case and evaluate it from there.
4188 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4189 case ESR_Break:
4190 return ESR_Succeeded;
4191 case ESR_Succeeded:
4192 case ESR_Continue:
4193 case ESR_Failed:
4194 case ESR_Returned:
4195 return ESR;
4196 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004197 // This can only happen if the switch case is nested within a statement
4198 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004199 Info.FFDiag(Found->getBeginLoc(),
4200 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004201 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004202 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004203 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004204}
4205
Richard Smith254a73d2011-10-28 22:34:42 +00004206// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004207static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004208 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004209 if (!Info.nextStep(S))
4210 return ESR_Failed;
4211
Richard Smith496ddcf2013-05-12 17:32:42 +00004212 // If we're hunting down a 'case' or 'default' label, recurse through
4213 // substatements until we hit the label.
4214 if (Case) {
4215 // FIXME: We don't start the lifetime of objects whose initialization we
4216 // jump over. However, such objects must be of class type with a trivial
4217 // default constructor that initialize all subobjects, so must be empty,
4218 // so this almost never matters.
4219 switch (S->getStmtClass()) {
4220 case Stmt::CompoundStmtClass:
4221 // FIXME: Precompute which substatement of a compound statement we
4222 // would jump to, and go straight there rather than performing a
4223 // linear scan each time.
4224 case Stmt::LabelStmtClass:
4225 case Stmt::AttributedStmtClass:
4226 case Stmt::DoStmtClass:
4227 break;
4228
4229 case Stmt::CaseStmtClass:
4230 case Stmt::DefaultStmtClass:
4231 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004232 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004233 break;
4234
4235 case Stmt::IfStmtClass: {
4236 // FIXME: Precompute which side of an 'if' we would jump to, and go
4237 // straight there rather than scanning both sides.
4238 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004239
4240 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4241 // preceded by our switch label.
4242 BlockScopeRAII Scope(Info);
4243
Richard Smith496ddcf2013-05-12 17:32:42 +00004244 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4245 if (ESR != ESR_CaseNotFound || !IS->getElse())
4246 return ESR;
4247 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4248 }
4249
4250 case Stmt::WhileStmtClass: {
4251 EvalStmtResult ESR =
4252 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4253 if (ESR != ESR_Continue)
4254 return ESR;
4255 break;
4256 }
4257
4258 case Stmt::ForStmtClass: {
4259 const ForStmt *FS = cast<ForStmt>(S);
4260 EvalStmtResult ESR =
4261 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4262 if (ESR != ESR_Continue)
4263 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004264 if (FS->getInc()) {
4265 FullExpressionRAII IncScope(Info);
4266 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4267 return ESR_Failed;
4268 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004269 break;
4270 }
4271
4272 case Stmt::DeclStmtClass:
4273 // FIXME: If the variable has initialization that can't be jumped over,
4274 // bail out of any immediately-surrounding compound-statement too.
4275 default:
4276 return ESR_CaseNotFound;
4277 }
4278 }
4279
Richard Smith254a73d2011-10-28 22:34:42 +00004280 switch (S->getStmtClass()) {
4281 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004282 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004283 // Don't bother evaluating beyond an expression-statement which couldn't
4284 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004285 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004286 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004287 return ESR_Failed;
4288 return ESR_Succeeded;
4289 }
4290
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004291 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004292 return ESR_Failed;
4293
4294 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004295 return ESR_Succeeded;
4296
Richard Smithd9f663b2013-04-22 15:31:51 +00004297 case Stmt::DeclStmtClass: {
4298 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004299 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004300 // Each declaration initialization is its own full-expression.
4301 // FIXME: This isn't quite right; if we're performing aggregate
4302 // initialization, each braced subexpression is its own full-expression.
4303 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004304 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004305 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004306 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004307 return ESR_Succeeded;
4308 }
4309
Richard Smith357362d2011-12-13 06:39:58 +00004310 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004311 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004312 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004313 if (RetExpr &&
4314 !(Result.Slot
4315 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4316 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004317 return ESR_Failed;
4318 return ESR_Returned;
4319 }
Richard Smith254a73d2011-10-28 22:34:42 +00004320
4321 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004322 BlockScopeRAII Scope(Info);
4323
Richard Smith254a73d2011-10-28 22:34:42 +00004324 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004325 for (const auto *BI : CS->body()) {
4326 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004327 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004328 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004329 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004330 return ESR;
4331 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004332 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004333 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004334
4335 case Stmt::IfStmtClass: {
4336 const IfStmt *IS = cast<IfStmt>(S);
4337
4338 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004339 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004340 if (const Stmt *Init = IS->getInit()) {
4341 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4342 if (ESR != ESR_Succeeded)
4343 return ESR;
4344 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004345 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004346 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004347 return ESR_Failed;
4348
4349 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4350 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4351 if (ESR != ESR_Succeeded)
4352 return ESR;
4353 }
4354 return ESR_Succeeded;
4355 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004356
4357 case Stmt::WhileStmtClass: {
4358 const WhileStmt *WS = cast<WhileStmt>(S);
4359 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004360 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004361 bool Continue;
4362 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4363 Continue))
4364 return ESR_Failed;
4365 if (!Continue)
4366 break;
4367
4368 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4369 if (ESR != ESR_Continue)
4370 return ESR;
4371 }
4372 return ESR_Succeeded;
4373 }
4374
4375 case Stmt::DoStmtClass: {
4376 const DoStmt *DS = cast<DoStmt>(S);
4377 bool Continue;
4378 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004379 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004380 if (ESR != ESR_Continue)
4381 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004382 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004383
Richard Smith08d6a2c2013-07-24 07:11:57 +00004384 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004385 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4386 return ESR_Failed;
4387 } while (Continue);
4388 return ESR_Succeeded;
4389 }
4390
4391 case Stmt::ForStmtClass: {
4392 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004393 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004394 if (FS->getInit()) {
4395 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4396 if (ESR != ESR_Succeeded)
4397 return ESR;
4398 }
4399 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004400 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004401 bool Continue = true;
4402 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4403 FS->getCond(), Continue))
4404 return ESR_Failed;
4405 if (!Continue)
4406 break;
4407
4408 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4409 if (ESR != ESR_Continue)
4410 return ESR;
4411
Richard Smith08d6a2c2013-07-24 07:11:57 +00004412 if (FS->getInc()) {
4413 FullExpressionRAII IncScope(Info);
4414 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4415 return ESR_Failed;
4416 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004417 }
4418 return ESR_Succeeded;
4419 }
4420
Richard Smith896e0d72013-05-06 06:51:17 +00004421 case Stmt::CXXForRangeStmtClass: {
4422 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004423 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004424
Richard Smith8baa5002018-09-28 18:44:09 +00004425 // Evaluate the init-statement if present.
4426 if (FS->getInit()) {
4427 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4428 if (ESR != ESR_Succeeded)
4429 return ESR;
4430 }
4431
Richard Smith896e0d72013-05-06 06:51:17 +00004432 // Initialize the __range variable.
4433 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4434 if (ESR != ESR_Succeeded)
4435 return ESR;
4436
4437 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004438 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4439 if (ESR != ESR_Succeeded)
4440 return ESR;
4441 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004442 if (ESR != ESR_Succeeded)
4443 return ESR;
4444
4445 while (true) {
4446 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004447 {
4448 bool Continue = true;
4449 FullExpressionRAII CondExpr(Info);
4450 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4451 return ESR_Failed;
4452 if (!Continue)
4453 break;
4454 }
Richard Smith896e0d72013-05-06 06:51:17 +00004455
4456 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004457 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004458 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4459 if (ESR != ESR_Succeeded)
4460 return ESR;
4461
4462 // Loop body.
4463 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4464 if (ESR != ESR_Continue)
4465 return ESR;
4466
4467 // Increment: ++__begin
4468 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4469 return ESR_Failed;
4470 }
4471
4472 return ESR_Succeeded;
4473 }
4474
Richard Smith496ddcf2013-05-12 17:32:42 +00004475 case Stmt::SwitchStmtClass:
4476 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4477
Richard Smith4e18ca52013-05-06 05:56:11 +00004478 case Stmt::ContinueStmtClass:
4479 return ESR_Continue;
4480
4481 case Stmt::BreakStmtClass:
4482 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004483
4484 case Stmt::LabelStmtClass:
4485 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4486
4487 case Stmt::AttributedStmtClass:
4488 // As a general principle, C++11 attributes can be ignored without
4489 // any semantic impact.
4490 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4491 Case);
4492
4493 case Stmt::CaseStmtClass:
4494 case Stmt::DefaultStmtClass:
4495 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004496 case Stmt::CXXTryStmtClass:
4497 // Evaluate try blocks by evaluating all sub statements.
4498 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004499 }
4500}
4501
Richard Smithcc36f692011-12-22 02:22:31 +00004502/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4503/// default constructor. If so, we'll fold it whether or not it's marked as
4504/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4505/// so we need special handling.
4506static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004507 const CXXConstructorDecl *CD,
4508 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004509 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4510 return false;
4511
Richard Smith66e05fe2012-01-18 05:21:49 +00004512 // Value-initialization does not call a trivial default constructor, so such a
4513 // call is a core constant expression whether or not the constructor is
4514 // constexpr.
4515 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004516 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004517 // FIXME: If DiagDecl is an implicitly-declared special member function,
4518 // we should be much more explicit about why it's not constexpr.
4519 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4520 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4521 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004522 } else {
4523 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4524 }
4525 }
4526 return true;
4527}
4528
Richard Smith357362d2011-12-13 06:39:58 +00004529/// CheckConstexprFunction - Check that a function can be called in a constant
4530/// expression.
4531static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4532 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004533 const FunctionDecl *Definition,
4534 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004535 // Potential constant expressions can contain calls to declared, but not yet
4536 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004537 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004538 Declaration->isConstexpr())
4539 return false;
4540
James Y Knightc7d3e602018-10-05 17:49:48 +00004541 // Bail out if the function declaration itself is invalid. We will
4542 // have produced a relevant diagnostic while parsing it, so just
4543 // note the problematic sub-expression.
4544 if (Declaration->isInvalidDecl()) {
4545 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004546 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004547 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004548
Richard Smithd9c6b032019-05-09 19:45:49 +00004549 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004550 // constant expression (prior to C++20). We can still constant-fold such a
4551 // call.
4552 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4553 cast<CXXMethodDecl>(Declaration)->isVirtual())
4554 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4555
4556 if (Definition && Definition->isInvalidDecl()) {
4557 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004558 return false;
4559 }
4560
Richard Smith357362d2011-12-13 06:39:58 +00004561 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004562 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004563 return true;
4564
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004565 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004566 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004567
Richard Smith5179eb72016-06-28 19:03:57 +00004568 // If this function is not constexpr because it is an inherited
4569 // non-constexpr constructor, diagnose that directly.
4570 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4571 if (CD && CD->isInheritingConstructor()) {
4572 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004573 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004574 DiagDecl = CD = Inherited;
4575 }
4576
4577 // FIXME: If DiagDecl is an implicitly-declared special member function
4578 // or an inheriting constructor, we should be much more explicit about why
4579 // it's not constexpr.
4580 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004581 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004582 << CD->getInheritedConstructor().getConstructor()->getParent();
4583 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004584 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004585 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004586 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4587 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004588 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004589 }
4590 return false;
4591}
4592
Richard Smithdebad642019-05-12 09:39:08 +00004593namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004594struct CheckDynamicTypeHandler {
4595 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004596 typedef bool result_type;
4597 bool failed() { return false; }
4598 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4599 bool found(APSInt &Value, QualType SubobjType) { return true; }
4600 bool found(APFloat &Value, QualType SubobjType) { return true; }
4601};
4602} // end anonymous namespace
4603
Richard Smith7bd54ab2019-05-15 20:22:21 +00004604/// Check that we can access the notional vptr of an object / determine its
4605/// dynamic type.
4606static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4607 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004608 if (This.Designator.Invalid)
4609 return false;
4610
Richard Smith7bd54ab2019-05-15 20:22:21 +00004611 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004612
4613 if (!Obj)
4614 return false;
4615
4616 if (!Obj.Value) {
4617 // The object is not usable in constant expressions, so we can't inspect
4618 // its value to see if it's in-lifetime or what the active union members
4619 // are. We can still check for a one-past-the-end lvalue.
4620 if (This.Designator.isOnePastTheEnd() ||
4621 This.Designator.isMostDerivedAnUnsizedArray()) {
4622 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4623 ? diag::note_constexpr_access_past_end
4624 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004625 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004626 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004627 } else if (Polymorphic) {
4628 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004629 // not be able to read a notional 'vptr' value.
4630 APValue Val;
4631 This.moveInto(Val);
4632 QualType StarThisType =
4633 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004634 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4635 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004636 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004637 }
4638 return true;
4639 }
4640
Richard Smith7bd54ab2019-05-15 20:22:21 +00004641 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004642 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4643}
4644
Richard Smith7bd54ab2019-05-15 20:22:21 +00004645/// Check that the pointee of the 'this' pointer in a member function call is
4646/// either within its lifetime or in its period of construction or destruction.
4647static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4648 const LValue &This) {
4649 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4650}
4651
Richard Smith921f1322019-05-13 23:35:21 +00004652struct DynamicType {
4653 /// The dynamic class type of the object.
4654 const CXXRecordDecl *Type;
4655 /// The corresponding path length in the lvalue.
4656 unsigned PathLength;
4657};
4658
4659static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4660 unsigned PathLength) {
4661 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4662 Designator.Entries.size() && "invalid path length");
4663 return (PathLength == Designator.MostDerivedPathLength)
4664 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4665 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4666}
4667
4668/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004669static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4670 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004671 // If we don't have an lvalue denoting an object of class type, there is no
4672 // meaningful dynamic type. (We consider objects of non-class type to have no
4673 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004674 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004675 return None;
4676
Richard Smith7bd54ab2019-05-15 20:22:21 +00004677 // Refuse to compute a dynamic type in the presence of virtual bases. This
4678 // shouldn't happen other than in constant-folding situations, since literal
4679 // types can't have virtual bases.
4680 //
4681 // Note that consumers of DynamicType assume that the type has no virtual
4682 // bases, and will need modifications if this restriction is relaxed.
4683 const CXXRecordDecl *Class =
4684 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4685 if (!Class || Class->getNumVBases()) {
4686 Info.FFDiag(E);
4687 return None;
4688 }
4689
Richard Smith921f1322019-05-13 23:35:21 +00004690 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4691 // binary search here instead. But the overwhelmingly common case is that
4692 // we're not in the middle of a constructor, so it probably doesn't matter
4693 // in practice.
4694 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4695 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4696 PathLength <= Path.size(); ++PathLength) {
4697 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4698 Path.slice(0, PathLength))) {
4699 case ConstructionPhase::Bases:
4700 // We're constructing a base class. This is not the dynamic type.
4701 break;
4702
4703 case ConstructionPhase::None:
4704 case ConstructionPhase::AfterBases:
4705 // We've finished constructing the base classes, so this is the dynamic
4706 // type.
4707 return DynamicType{getBaseClassType(This.Designator, PathLength),
4708 PathLength};
4709 }
4710 }
4711
4712 // CWG issue 1517: we're constructing a base class of the object described by
4713 // 'This', so that object has not yet begun its period of construction and
4714 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004715 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004716 return None;
4717}
4718
4719/// Perform virtual dispatch.
4720static const CXXMethodDecl *HandleVirtualDispatch(
4721 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4722 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004723 Optional<DynamicType> DynType =
4724 ComputeDynamicType(Info, E, This, AK_MemberCall);
4725 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004726 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004727
4728 // Find the final overrider. It must be declared in one of the classes on the
4729 // path from the dynamic type to the static type.
4730 // FIXME: If we ever allow literal types to have virtual base classes, that
4731 // won't be true.
4732 const CXXMethodDecl *Callee = Found;
4733 unsigned PathLength = DynType->PathLength;
4734 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4735 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004736 const CXXMethodDecl *Overrider =
4737 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4738 if (Overrider) {
4739 Callee = Overrider;
4740 break;
4741 }
4742 }
4743
4744 // C++2a [class.abstract]p6:
4745 // the effect of making a virtual call to a pure virtual function [...] is
4746 // undefined
4747 if (Callee->isPure()) {
4748 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4749 Info.Note(Callee->getLocation(), diag::note_declared_at);
4750 return nullptr;
4751 }
4752
4753 // If necessary, walk the rest of the path to determine the sequence of
4754 // covariant adjustment steps to apply.
4755 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4756 Found->getReturnType())) {
4757 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4758 for (unsigned CovariantPathLength = PathLength + 1;
4759 CovariantPathLength != This.Designator.Entries.size();
4760 ++CovariantPathLength) {
4761 const CXXRecordDecl *NextClass =
4762 getBaseClassType(This.Designator, CovariantPathLength);
4763 const CXXMethodDecl *Next =
4764 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4765 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4766 Next->getReturnType(), CovariantAdjustmentPath.back()))
4767 CovariantAdjustmentPath.push_back(Next->getReturnType());
4768 }
4769 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4770 CovariantAdjustmentPath.back()))
4771 CovariantAdjustmentPath.push_back(Found->getReturnType());
4772 }
4773
4774 // Perform 'this' adjustment.
4775 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4776 return nullptr;
4777
4778 return Callee;
4779}
4780
4781/// Perform the adjustment from a value returned by a virtual function to
4782/// a value of the statically expected type, which may be a pointer or
4783/// reference to a base class of the returned type.
4784static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4785 APValue &Result,
4786 ArrayRef<QualType> Path) {
4787 assert(Result.isLValue() &&
4788 "unexpected kind of APValue for covariant return");
4789 if (Result.isNullPointer())
4790 return true;
4791
4792 LValue LVal;
4793 LVal.setFrom(Info.Ctx, Result);
4794
4795 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4796 for (unsigned I = 1; I != Path.size(); ++I) {
4797 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4798 assert(OldClass && NewClass && "unexpected kind of covariant return");
4799 if (OldClass != NewClass &&
4800 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4801 return false;
4802 OldClass = NewClass;
4803 }
4804
4805 LVal.moveInto(Result);
4806 return true;
4807}
4808
Richard Smith7bd54ab2019-05-15 20:22:21 +00004809/// Determine whether \p Base, which is known to be a direct base class of
4810/// \p Derived, is a public base class.
4811static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4812 const CXXRecordDecl *Base) {
4813 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4814 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4815 if (BaseClass && declaresSameEntity(BaseClass, Base))
4816 return BaseSpec.getAccessSpecifier() == AS_public;
4817 }
4818 llvm_unreachable("Base is not a direct base of Derived");
4819}
4820
4821/// Apply the given dynamic cast operation on the provided lvalue.
4822///
4823/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4824/// to find a suitable target subobject.
4825static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4826 LValue &Ptr) {
4827 // We can't do anything with a non-symbolic pointer value.
4828 SubobjectDesignator &D = Ptr.Designator;
4829 if (D.Invalid)
4830 return false;
4831
4832 // C++ [expr.dynamic.cast]p6:
4833 // If v is a null pointer value, the result is a null pointer value.
4834 if (Ptr.isNullPointer() && !E->isGLValue())
4835 return true;
4836
4837 // For all the other cases, we need the pointer to point to an object within
4838 // its lifetime / period of construction / destruction, and we need to know
4839 // its dynamic type.
4840 Optional<DynamicType> DynType =
4841 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4842 if (!DynType)
4843 return false;
4844
4845 // C++ [expr.dynamic.cast]p7:
4846 // If T is "pointer to cv void", then the result is a pointer to the most
4847 // derived object
4848 if (E->getType()->isVoidPointerType())
4849 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4850
4851 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4852 assert(C && "dynamic_cast target is not void pointer nor class");
4853 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4854
4855 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4856 // C++ [expr.dynamic.cast]p9:
4857 if (!E->isGLValue()) {
4858 // The value of a failed cast to pointer type is the null pointer value
4859 // of the required result type.
4860 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4861 Ptr.setNull(E->getType(), TargetVal);
4862 return true;
4863 }
4864
4865 // A failed cast to reference type throws [...] std::bad_cast.
4866 unsigned DiagKind;
4867 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4868 DynType->Type->isDerivedFrom(C)))
4869 DiagKind = 0;
4870 else if (!Paths || Paths->begin() == Paths->end())
4871 DiagKind = 1;
4872 else if (Paths->isAmbiguous(CQT))
4873 DiagKind = 2;
4874 else {
4875 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4876 DiagKind = 3;
4877 }
4878 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4879 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4880 << Info.Ctx.getRecordType(DynType->Type)
4881 << E->getType().getUnqualifiedType();
4882 return false;
4883 };
4884
4885 // Runtime check, phase 1:
4886 // Walk from the base subobject towards the derived object looking for the
4887 // target type.
4888 for (int PathLength = Ptr.Designator.Entries.size();
4889 PathLength >= (int)DynType->PathLength; --PathLength) {
4890 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4891 if (declaresSameEntity(Class, C))
4892 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4893 // We can only walk across public inheritance edges.
4894 if (PathLength > (int)DynType->PathLength &&
4895 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4896 Class))
4897 return RuntimeCheckFailed(nullptr);
4898 }
4899
4900 // Runtime check, phase 2:
4901 // Search the dynamic type for an unambiguous public base of type C.
4902 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4903 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4904 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4905 Paths.front().Access == AS_public) {
4906 // Downcast to the dynamic type...
4907 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4908 return false;
4909 // ... then upcast to the chosen base class subobject.
4910 for (CXXBasePathElement &Elem : Paths.front())
4911 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4912 return false;
4913 return true;
4914 }
4915
4916 // Otherwise, the runtime check fails.
4917 return RuntimeCheckFailed(&Paths);
4918}
4919
Richard Smith31c69a32019-05-21 23:15:20 +00004920namespace {
4921struct StartLifetimeOfUnionMemberHandler {
4922 const FieldDecl *Field;
4923
4924 static const AccessKinds AccessKind = AK_Assign;
4925
4926 APValue getDefaultInitValue(QualType SubobjType) {
4927 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4928 if (RD->isUnion())
4929 return APValue((const FieldDecl*)nullptr);
4930
4931 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4932 std::distance(RD->field_begin(), RD->field_end()));
4933
4934 unsigned Index = 0;
4935 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4936 End = RD->bases_end(); I != End; ++I, ++Index)
4937 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4938
4939 for (const auto *I : RD->fields()) {
4940 if (I->isUnnamedBitfield())
4941 continue;
4942 Struct.getStructField(I->getFieldIndex()) =
4943 getDefaultInitValue(I->getType());
4944 }
4945 return Struct;
4946 }
4947
4948 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4949 SubobjType->getAsArrayTypeUnsafe())) {
4950 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4951 if (Array.hasArrayFiller())
4952 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4953 return Array;
4954 }
4955
4956 return APValue::IndeterminateValue();
4957 }
4958
4959 typedef bool result_type;
4960 bool failed() { return false; }
4961 bool found(APValue &Subobj, QualType SubobjType) {
4962 // We are supposed to perform no initialization but begin the lifetime of
4963 // the object. We interpret that as meaning to do what default
4964 // initialization of the object would do if all constructors involved were
4965 // trivial:
4966 // * All base, non-variant member, and array element subobjects' lifetimes
4967 // begin
4968 // * No variant members' lifetimes begin
4969 // * All scalar subobjects whose lifetimes begin have indeterminate values
4970 assert(SubobjType->isUnionType());
4971 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4972 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4973 return true;
4974 }
4975 bool found(APSInt &Value, QualType SubobjType) {
4976 llvm_unreachable("wrong value kind for union object");
4977 }
4978 bool found(APFloat &Value, QualType SubobjType) {
4979 llvm_unreachable("wrong value kind for union object");
4980 }
4981};
4982} // end anonymous namespace
4983
4984const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4985
4986/// Handle a builtin simple-assignment or a call to a trivial assignment
4987/// operator whose left-hand side might involve a union member access. If it
4988/// does, implicitly start the lifetime of any accessed union elements per
4989/// C++20 [class.union]5.
4990static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4991 const LValue &LHS) {
4992 if (LHS.InvalidBase || LHS.Designator.Invalid)
4993 return false;
4994
4995 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4996 // C++ [class.union]p5:
4997 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00004998 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00004999 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005000 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5001 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5002 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5003 if (!FD)
5004 break;
5005
5006 // ... and also contains A.B if B names a union member
5007 if (FD->getParent()->isUnion())
5008 UnionPathLengths.push_back({PathLength - 1, FD});
5009
5010 E = ME->getBase();
5011 --PathLength;
5012 assert(declaresSameEntity(FD,
5013 LHS.Designator.Entries[PathLength]
5014 .getAsBaseOrMember().getPointer()));
5015
5016 // -- If E is of the form A[B] and is interpreted as a built-in array
5017 // subscripting operator, S(E) is [S(the array operand, if any)].
5018 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5019 // Step over an ArrayToPointerDecay implicit cast.
5020 auto *Base = ASE->getBase()->IgnoreImplicit();
5021 if (!Base->getType()->isArrayType())
5022 break;
5023
5024 E = Base;
5025 --PathLength;
5026
5027 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5028 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005029 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005030 if (ICE->getCastKind() == CK_NoOp)
5031 continue;
5032 if (ICE->getCastKind() != CK_DerivedToBase &&
5033 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5034 break;
Richard Smitha481b012019-05-30 20:45:12 +00005035 // Walk path backwards as we walk up from the base to the derived class.
5036 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005037 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005038 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005039 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5040 LHS.Designator.Entries[PathLength]
5041 .getAsBaseOrMember().getPointer()));
5042 }
Richard Smith31c69a32019-05-21 23:15:20 +00005043
5044 // -- Otherwise, S(E) is empty.
5045 } else {
5046 break;
5047 }
5048 }
5049
5050 // Common case: no unions' lifetimes are started.
5051 if (UnionPathLengths.empty())
5052 return true;
5053
5054 // if modification of X [would access an inactive union member], an object
5055 // of the type of X is implicitly created
5056 CompleteObject Obj =
5057 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5058 if (!Obj)
5059 return false;
5060 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5061 llvm::reverse(UnionPathLengths)) {
5062 // Form a designator for the union object.
5063 SubobjectDesignator D = LHS.Designator;
5064 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5065
5066 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5067 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5068 return false;
5069 }
5070
5071 return true;
5072}
5073
Richard Smithbe6dd812014-11-19 21:27:17 +00005074/// Determine if a class has any fields that might need to be copied by a
5075/// trivial copy or move operation.
5076static bool hasFields(const CXXRecordDecl *RD) {
5077 if (!RD || RD->isEmpty())
5078 return false;
5079 for (auto *FD : RD->fields()) {
5080 if (FD->isUnnamedBitfield())
5081 continue;
5082 return true;
5083 }
5084 for (auto &Base : RD->bases())
5085 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5086 return true;
5087 return false;
5088}
5089
Richard Smithd62306a2011-11-10 06:34:14 +00005090namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005091typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005092}
5093
5094/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005095static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5096 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005097 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005098 llvm::SmallBitVector ForbiddenNullArgs;
5099 if (Callee->hasAttr<NonNullAttr>()) {
5100 ForbiddenNullArgs.resize(Args.size());
5101 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5102 if (!Attr->args_size()) {
5103 ForbiddenNullArgs.set();
5104 break;
5105 } else
5106 for (auto Idx : Attr->args()) {
5107 unsigned ASTIdx = Idx.getASTIndex();
5108 if (ASTIdx >= Args.size())
5109 continue;
5110 ForbiddenNullArgs[ASTIdx] = 1;
5111 }
5112 }
5113 }
Richard Smithd62306a2011-11-10 06:34:14 +00005114 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005115 I != E; ++I) {
5116 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5117 // If we're checking for a potential constant expression, evaluate all
5118 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005119 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005120 return false;
5121 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005122 } else if (!ForbiddenNullArgs.empty() &&
5123 ForbiddenNullArgs[I - Args.begin()] &&
5124 ArgValues[I - Args.begin()].isNullPointer()) {
5125 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5126 if (!Info.noteFailure())
5127 return false;
5128 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005129 }
5130 }
5131 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005132}
5133
Richard Smith254a73d2011-10-28 22:34:42 +00005134/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005135static bool HandleFunctionCall(SourceLocation CallLoc,
5136 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005137 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005138 EvalInfo &Info, APValue &Result,
5139 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005140 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005141 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005142 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005143
Richard Smith253c2a32012-01-27 01:14:48 +00005144 if (!Info.CheckCallLimit(CallLoc))
5145 return false;
5146
5147 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005148
5149 // For a trivial copy or move assignment, perform an APValue copy. This is
5150 // essential for unions, where the operations performed by the assignment
5151 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005152 //
5153 // Skip this for non-union classes with no fields; in that case, the defaulted
5154 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005155 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005156 if (MD && MD->isDefaulted() &&
5157 (MD->getParent()->isUnion() ||
5158 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005159 assert(This &&
5160 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5161 LValue RHS;
5162 RHS.setFrom(Info.Ctx, ArgValues[0]);
5163 APValue RHSValue;
5164 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5165 RHS, RHSValue))
5166 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005167 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5168 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5169 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005170 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005171 RHSValue))
5172 return false;
5173 This->moveInto(Result);
5174 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005175 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005176 // We're in a lambda; determine the lambda capture field maps unless we're
5177 // just constexpr checking a lambda's call operator. constexpr checking is
5178 // done before the captures have been added to the closure object (unless
5179 // we're inferring constexpr-ness), so we don't have access to them in this
5180 // case. But since we don't need the captures to constexpr check, we can
5181 // just ignore them.
5182 if (!Info.checkingPotentialConstantExpression())
5183 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5184 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005185 }
5186
Richard Smith52a980a2015-08-28 02:43:42 +00005187 StmtResult Ret = {Result, ResultSlot};
5188 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005189 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005190 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005191 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005192 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005193 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005194 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005195}
5196
Richard Smithd62306a2011-11-10 06:34:14 +00005197/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005198static bool HandleConstructorCall(const Expr *E, const LValue &This,
5199 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005200 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005201 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005202 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005203 if (!Info.CheckCallLimit(CallLoc))
5204 return false;
5205
Richard Smith3607ffe2012-02-13 03:54:03 +00005206 const CXXRecordDecl *RD = Definition->getParent();
5207 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005208 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005209 return false;
5210 }
5211
Erik Pilkington42925492017-10-04 00:18:55 +00005212 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005213 Info,
5214 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5215 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005216 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005217
Richard Smith52a980a2015-08-28 02:43:42 +00005218 // FIXME: Creating an APValue just to hold a nonexistent return value is
5219 // wasteful.
5220 APValue RetVal;
5221 StmtResult Ret = {RetVal, nullptr};
5222
Richard Smith5179eb72016-06-28 19:03:57 +00005223 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005224 if (Definition->isDelegatingConstructor()) {
5225 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005226 {
5227 FullExpressionRAII InitScope(Info);
5228 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5229 return false;
5230 }
Richard Smith52a980a2015-08-28 02:43:42 +00005231 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005232 }
5233
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005234 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005235 // essential for unions (or classes with anonymous union members), where the
5236 // operations performed by the constructor cannot be represented by
5237 // ctor-initializers.
5238 //
5239 // Skip this for empty non-union classes; we should not perform an
5240 // lvalue-to-rvalue conversion on them because their copy constructor does not
5241 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005242 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005243 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005244 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005245 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005246 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005247 return handleLValueToRValueConversion(
5248 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5249 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005250 }
5251
5252 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005253 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005254 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005255 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005256
John McCalld7bca762012-05-01 00:38:49 +00005257 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005258 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5259
Richard Smith08d6a2c2013-07-24 07:11:57 +00005260 // A scope for temporaries lifetime-extended by reference members.
5261 BlockScopeRAII LifetimeExtendedScope(Info);
5262
Richard Smith253c2a32012-01-27 01:14:48 +00005263 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005264 unsigned BasesSeen = 0;
5265#ifndef NDEBUG
5266 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5267#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005268 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005269 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005270 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005271 APValue *Value = &Result;
5272
5273 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005274 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005275 if (I->isBaseInitializer()) {
5276 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005277#ifndef NDEBUG
5278 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005279 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005280 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5281 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5282 "base class initializers not in expected order");
5283 ++BaseIt;
5284#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005285 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005286 BaseType->getAsCXXRecordDecl(), &Layout))
5287 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005288 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005289 } else if ((FD = I->getMember())) {
5290 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005291 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005292 if (RD->isUnion()) {
5293 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005294 Value = &Result.getUnionValue();
5295 } else {
5296 Value = &Result.getStructField(FD->getFieldIndex());
5297 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005298 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005299 // Walk the indirect field decl's chain to find the object to initialize,
5300 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005301 auto IndirectFieldChain = IFD->chain();
5302 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005303 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005304 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5305 // Switch the union field if it differs. This happens if we had
5306 // preceding zero-initialization, and we're now initializing a union
5307 // subobject other than the first.
5308 // FIXME: In this case, the values of the other subobjects are
5309 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005310 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005311 (Value->isUnion() && Value->getUnionField() != FD)) {
5312 if (CD->isUnion())
5313 *Value = APValue(FD);
5314 else
5315 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005316 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005317 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005318 // Store Subobject as its parent before updating it for the last element
5319 // in the chain.
5320 if (C == IndirectFieldChain.back())
5321 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005322 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005323 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005324 if (CD->isUnion())
5325 Value = &Value->getUnionValue();
5326 else
5327 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00005328 }
Richard Smithd62306a2011-11-10 06:34:14 +00005329 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005330 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005331 }
Richard Smith253c2a32012-01-27 01:14:48 +00005332
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005333 // Need to override This for implicit field initializers as in this case
5334 // This refers to innermost anonymous struct/union containing initializer,
5335 // not to currently constructed class.
5336 const Expr *Init = I->getInit();
5337 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5338 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005339 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005340 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5341 (FD && FD->isBitField() &&
5342 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005343 // If we're checking for a potential constant expression, evaluate all
5344 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005345 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005346 return false;
5347 Success = false;
5348 }
Richard Smith921f1322019-05-13 23:35:21 +00005349
5350 // This is the point at which the dynamic type of the object becomes this
5351 // class type.
5352 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5353 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005354 }
5355
Richard Smithd9f663b2013-04-22 15:31:51 +00005356 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005357 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005358}
5359
Richard Smith5179eb72016-06-28 19:03:57 +00005360static bool HandleConstructorCall(const Expr *E, const LValue &This,
5361 ArrayRef<const Expr*> Args,
5362 const CXXConstructorDecl *Definition,
5363 EvalInfo &Info, APValue &Result) {
5364 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005365 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005366 return false;
5367
5368 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5369 Info, Result);
5370}
5371
Eli Friedman9a156e52008-11-12 09:44:48 +00005372//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005373// Generic Evaluation
5374//===----------------------------------------------------------------------===//
5375namespace {
5376
Aaron Ballman68af21c2014-01-03 19:26:43 +00005377template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005378class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005379 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005380private:
Richard Smith52a980a2015-08-28 02:43:42 +00005381 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005382 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005383 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005384 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005385 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005386 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005388
Richard Smith17100ba2012-02-16 02:46:34 +00005389 // Check whether a conditional operator with a non-constant condition is a
5390 // potential constant expression. If neither arm is a potential constant
5391 // expression, then the conditional operator is not either.
5392 template<typename ConditionalOperator>
5393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005394 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005395
5396 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005397 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005398 {
Richard Smith17100ba2012-02-16 02:46:34 +00005399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005400 StmtVisitorTy::Visit(E->getFalseExpr());
5401 if (Diag.empty())
5402 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005403 }
Richard Smith17100ba2012-02-16 02:46:34 +00005404
George Burgess IV8c892b52016-05-25 22:31:54 +00005405 {
5406 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005407 Diag.clear();
5408 StmtVisitorTy::Visit(E->getTrueExpr());
5409 if (Diag.empty())
5410 return;
5411 }
5412
5413 Error(E, diag::note_constexpr_conditional_never_const);
5414 }
5415
5416
5417 template<typename ConditionalOperator>
5418 bool HandleConditionalOperator(const ConditionalOperator *E) {
5419 bool BoolResult;
5420 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005421 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005422 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005423 return false;
5424 }
5425 if (Info.noteFailure()) {
5426 StmtVisitorTy::Visit(E->getTrueExpr());
5427 StmtVisitorTy::Visit(E->getFalseExpr());
5428 }
Richard Smith17100ba2012-02-16 02:46:34 +00005429 return false;
5430 }
5431
5432 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5433 return StmtVisitorTy::Visit(EvalExpr);
5434 }
5435
Peter Collingbournee9200682011-05-13 03:29:01 +00005436protected:
5437 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005438 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005439 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5440
Richard Smith92b1ce02011-12-12 09:28:41 +00005441 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005442 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005443 }
5444
Aaron Ballman68af21c2014-01-03 19:26:43 +00005445 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005446
5447public:
5448 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5449
5450 EvalInfo &getEvalInfo() { return Info; }
5451
Richard Smithf57d8cb2011-12-09 22:58:01 +00005452 /// Report an evaluation error. This should only be called when an error is
5453 /// first discovered. When propagating an error, just return false.
5454 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005455 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005456 return false;
5457 }
5458 bool Error(const Expr *E) {
5459 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5460 }
5461
Aaron Ballman68af21c2014-01-03 19:26:43 +00005462 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005463 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005464 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005465 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005466 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005467 }
5468
Bill Wendling8003edc2018-11-09 00:41:36 +00005469 bool VisitConstantExpr(const ConstantExpr *E)
5470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005471 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005472 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005473 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005474 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005475 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005476 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005477 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005478 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005479 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005480 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005481 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005482 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005483 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5484 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005485 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005486 return StmtVisitorTy::Visit(E->getExpr());
5487 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005488 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005489 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005490 // The initializer may not have been parsed yet, or might be erroneous.
5491 if (!E->getExpr())
5492 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005493 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005494 return StmtVisitorTy::Visit(E->getExpr());
5495 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005496
Richard Smith5894a912011-12-19 22:12:41 +00005497 // We cannot create any objects for which cleanups are required, so there is
5498 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005499 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005500 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005501
Aaron Ballman68af21c2014-01-03 19:26:43 +00005502 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005503 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5504 return static_cast<Derived*>(this)->VisitCastExpr(E);
5505 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005506 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005507 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005509 return static_cast<Derived*>(this)->VisitCastExpr(E);
5510 }
5511
Aaron Ballman68af21c2014-01-03 19:26:43 +00005512 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005513 switch (E->getOpcode()) {
5514 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005515 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005516
5517 case BO_Comma:
5518 VisitIgnoredValue(E->getLHS());
5519 return StmtVisitorTy::Visit(E->getRHS());
5520
5521 case BO_PtrMemD:
5522 case BO_PtrMemI: {
5523 LValue Obj;
5524 if (!HandleMemberPointerAccess(Info, E, Obj))
5525 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005526 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00005527 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005528 return false;
5529 return DerivedSuccess(Result, E);
5530 }
5531 }
5532 }
5533
Aaron Ballman68af21c2014-01-03 19:26:43 +00005534 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00005535 // Evaluate and cache the common expression. We treat it as a temporary,
5536 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00005537 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00005538 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005539 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00005540
Richard Smith17100ba2012-02-16 02:46:34 +00005541 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005542 }
5543
Aaron Ballman68af21c2014-01-03 19:26:43 +00005544 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005545 bool IsBcpCall = false;
5546 // If the condition (ignoring parens) is a __builtin_constant_p call,
5547 // the result is a constant expression if it can be folded without
5548 // side-effects. This is an important GNU extension. See GCC PR38377
5549 // for discussion.
5550 if (const CallExpr *CallCE =
5551 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00005552 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005553 IsBcpCall = true;
5554
5555 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5556 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00005557 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005558 return false;
5559
Richard Smith6d4c6582013-11-05 22:18:15 +00005560 FoldConstant Fold(Info, IsBcpCall);
5561 if (!HandleConditionalOperator(E)) {
5562 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005563 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005564 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005565
5566 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005567 }
5568
Aaron Ballman68af21c2014-01-03 19:26:43 +00005569 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005570 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005571 return DerivedSuccess(*Value, E);
5572
5573 const Expr *Source = E->getSourceExpr();
5574 if (!Source)
5575 return Error(E);
5576 if (Source == E) { // sanity checking.
5577 assert(0 && "OpaqueValueExpr recursively refers to itself");
5578 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005579 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00005580 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00005581 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005582
Aaron Ballman68af21c2014-01-03 19:26:43 +00005583 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005584 APValue Result;
5585 if (!handleCallExpr(E, Result, nullptr))
5586 return false;
5587 return DerivedSuccess(Result, E);
5588 }
5589
5590 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00005591 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00005592 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00005593 QualType CalleeType = Callee->getType();
5594
Craig Topper36250ad2014-05-12 05:36:57 +00005595 const FunctionDecl *FD = nullptr;
5596 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00005597 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00005598 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00005599
Richard Smithe97cbd72011-11-11 04:05:33 +00005600 // Extract function decl and 'this' pointer from the callee.
5601 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00005602 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005603 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5604 // Explicit bound member calls, such as x.f() or p->g();
5605 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005606 return false;
Richard Smith921f1322019-05-13 23:35:21 +00005607 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5608 if (!Member)
5609 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005610 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00005611 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00005612 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5613 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00005614 Member = dyn_cast_or_null<CXXMethodDecl>(
5615 HandleMemberPointerAccess(Info, BE, ThisVal, false));
5616 if (!Member)
5617 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005618 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00005619 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005620 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00005621 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00005622 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00005623 LValue Call;
5624 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005625 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00005626
Richard Smitha8105bc2012-01-06 16:39:00 +00005627 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005628 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00005629 FD = dyn_cast_or_null<FunctionDecl>(
5630 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00005631 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005632 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00005633 // Don't call function pointers which have been cast to some other type.
5634 // Per DR (no number yet), the caller and callee can differ in noexcept.
5635 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5636 CalleeType->getPointeeType(), FD->getType())) {
5637 return Error(E);
5638 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005639
5640 // Overloaded operator calls to member functions are represented as normal
5641 // calls with '*this' as the first argument.
5642 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5643 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005644 // FIXME: When selecting an implicit conversion for an overloaded
5645 // operator delete, we sometimes try to evaluate calls to conversion
5646 // operators without a 'this' parameter!
5647 if (Args.empty())
5648 return Error(E);
5649
Nick Lewycky13073a62017-06-12 21:15:44 +00005650 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00005651 return false;
5652 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00005653 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00005654 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00005655 // Map the static invoker for the lambda back to the call operator.
5656 // Conveniently, we don't have to slice out the 'this' argument (as is
5657 // being done for the non-static case), since a static member function
5658 // doesn't have an implicit argument passed in.
5659 const CXXRecordDecl *ClosureClass = MD->getParent();
5660 assert(
5661 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5662 "Number of captures must be zero for conversion to function-ptr");
5663
5664 const CXXMethodDecl *LambdaCallOp =
5665 ClosureClass->getLambdaCallOperator();
5666
5667 // Set 'FD', the function that will be called below, to the call
5668 // operator. If the closure object represents a generic lambda, find
5669 // the corresponding specialization of the call operator.
5670
5671 if (ClosureClass->isGenericLambda()) {
5672 assert(MD->isFunctionTemplateSpecialization() &&
5673 "A generic lambda's static-invoker function must be a "
5674 "template specialization");
5675 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5676 FunctionTemplateDecl *CallOpTemplate =
5677 LambdaCallOp->getDescribedFunctionTemplate();
5678 void *InsertPos = nullptr;
5679 FunctionDecl *CorrespondingCallOpSpecialization =
5680 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5681 assert(CorrespondingCallOpSpecialization &&
5682 "We must always have a function call operator specialization "
5683 "that corresponds to our static invoker specialization");
5684 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5685 } else
5686 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00005687 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005688 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005689 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00005690
Richard Smith921f1322019-05-13 23:35:21 +00005691 SmallVector<QualType, 4> CovariantAdjustmentPath;
5692 if (This) {
5693 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005694 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5695 // Perform virtual dispatch, if necessary.
5696 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5697 CovariantAdjustmentPath);
5698 if (!FD)
5699 return false;
5700 } else {
5701 // Check that the 'this' pointer points to an object of the right type.
5702 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5703 return false;
5704 }
Richard Smith921f1322019-05-13 23:35:21 +00005705 }
Richard Smith47b34932012-02-01 02:39:43 +00005706
Craig Topper36250ad2014-05-12 05:36:57 +00005707 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005708 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005709
Nick Lewycky13073a62017-06-12 21:15:44 +00005710 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5711 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005712 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005713 return false;
5714
Richard Smith921f1322019-05-13 23:35:21 +00005715 if (!CovariantAdjustmentPath.empty() &&
5716 !HandleCovariantReturnAdjustment(Info, E, Result,
5717 CovariantAdjustmentPath))
5718 return false;
5719
Richard Smith52a980a2015-08-28 02:43:42 +00005720 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005721 }
5722
Aaron Ballman68af21c2014-01-03 19:26:43 +00005723 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005724 return StmtVisitorTy::Visit(E->getInitializer());
5725 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005726 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005727 if (E->getNumInits() == 0)
5728 return DerivedZeroInitialization(E);
5729 if (E->getNumInits() == 1)
5730 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005731 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005732 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005733 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005734 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005735 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005736 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005737 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005738 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005739 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005740 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005741 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005742
Richard Smithd62306a2011-11-10 06:34:14 +00005743 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005744 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005745 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5746 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00005747 assert(!E->isArrow() && "missing call to bound member function?");
5748
Richard Smith2e312c82012-03-03 22:46:17 +00005749 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005750 if (!Evaluate(Val, Info, E->getBase()))
5751 return false;
5752
5753 QualType BaseTy = E->getBase()->getType();
5754
5755 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005756 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005757 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005758 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005759 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5760
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005761 // Note: there is no lvalue base here. But this case should only ever
5762 // happen in C or in C++98, where we cannot be evaluating a constexpr
5763 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00005764 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00005765 SubobjectDesignator Designator(BaseTy);
5766 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005767
Richard Smith3229b742013-05-05 21:17:10 +00005768 APValue Result;
5769 return extractSubobject(Info, E, Obj, Designator, Result) &&
5770 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005771 }
5772
Aaron Ballman68af21c2014-01-03 19:26:43 +00005773 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005774 switch (E->getCastKind()) {
5775 default:
5776 break;
5777
Richard Smitha23ab512013-05-23 00:30:41 +00005778 case CK_AtomicToNonAtomic: {
5779 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005780 // This does not need to be done in place even for class/array types:
5781 // atomic-to-non-atomic conversion implies copying the object
5782 // representation.
5783 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005784 return false;
5785 return DerivedSuccess(AtomicVal, E);
5786 }
5787
Richard Smith11562c52011-10-28 17:51:58 +00005788 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005789 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005790 return StmtVisitorTy::Visit(E->getSubExpr());
5791
5792 case CK_LValueToRValue: {
5793 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005794 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5795 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005796 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005797 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005798 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005799 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005800 return false;
5801 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005802 }
5803 }
5804
Richard Smithf57d8cb2011-12-09 22:58:01 +00005805 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005806 }
5807
Aaron Ballman68af21c2014-01-03 19:26:43 +00005808 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005809 return VisitUnaryPostIncDec(UO);
5810 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005811 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005812 return VisitUnaryPostIncDec(UO);
5813 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005814 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005815 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005816 return Error(UO);
5817
5818 LValue LVal;
5819 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5820 return false;
5821 APValue RVal;
5822 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5823 UO->isIncrementOp(), &RVal))
5824 return false;
5825 return DerivedSuccess(RVal, UO);
5826 }
5827
Aaron Ballman68af21c2014-01-03 19:26:43 +00005828 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005829 // We will have checked the full-expressions inside the statement expression
5830 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005831 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005832 return Error(E);
5833
Richard Smith08d6a2c2013-07-24 07:11:57 +00005834 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005835 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005836 if (CS->body_empty())
5837 return true;
5838
Richard Smith51f03172013-06-20 03:00:05 +00005839 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5840 BE = CS->body_end();
5841 /**/; ++BI) {
5842 if (BI + 1 == BE) {
5843 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5844 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005845 Info.FFDiag((*BI)->getBeginLoc(),
5846 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005847 return false;
5848 }
5849 return this->Visit(FinalExpr);
5850 }
5851
5852 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005853 StmtResult Result = { ReturnValue, nullptr };
5854 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005855 if (ESR != ESR_Succeeded) {
5856 // FIXME: If the statement-expression terminated due to 'return',
5857 // 'break', or 'continue', it would be nice to propagate that to
5858 // the outer statement evaluation rather than bailing out.
5859 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005860 Info.FFDiag((*BI)->getBeginLoc(),
5861 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005862 return false;
5863 }
5864 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005865
5866 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005867 }
5868
Richard Smith4a678122011-10-24 18:44:57 +00005869 /// Visit a value which is evaluated, but whose value is ignored.
5870 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005871 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005872 }
David Majnemere9807b22016-02-26 04:23:19 +00005873
5874 /// Potentially visit a MemberExpr's base expression.
5875 void VisitIgnoredBaseExpression(const Expr *E) {
5876 // While MSVC doesn't evaluate the base expression, it does diagnose the
5877 // presence of side-effecting behavior.
5878 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5879 return;
5880 VisitIgnoredValue(E);
5881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005882};
5883
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005884} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005885
5886//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005887// Common base class for lvalue and temporary evaluation.
5888//===----------------------------------------------------------------------===//
5889namespace {
5890template<class Derived>
5891class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005892 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005893protected:
5894 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005895 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005896 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005897 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005898
5899 bool Success(APValue::LValueBase B) {
5900 Result.set(B);
5901 return true;
5902 }
5903
George Burgess IVf9013bf2017-02-10 22:52:29 +00005904 bool evaluatePointer(const Expr *E, LValue &Result) {
5905 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5906 }
5907
Richard Smith027bf112011-11-17 22:56:20 +00005908public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005909 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5910 : ExprEvaluatorBaseTy(Info), Result(Result),
5911 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005912
Richard Smith2e312c82012-03-03 22:46:17 +00005913 bool Success(const APValue &V, const Expr *E) {
5914 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005915 return true;
5916 }
Richard Smith027bf112011-11-17 22:56:20 +00005917
Richard Smith027bf112011-11-17 22:56:20 +00005918 bool VisitMemberExpr(const MemberExpr *E) {
5919 // Handle non-static data members.
5920 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005921 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005922 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005923 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005924 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005925 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005926 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005927 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005928 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005929 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005930 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005931 BaseTy = E->getBase()->getType();
5932 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005933 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005934 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005935 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005936 Result.setInvalid(E);
5937 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005938 }
Richard Smith027bf112011-11-17 22:56:20 +00005939
Richard Smith1b78b3d2012-01-25 22:15:11 +00005940 const ValueDecl *MD = E->getMemberDecl();
5941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5942 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5943 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5944 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005945 if (!HandleLValueMember(this->Info, E, Result, FD))
5946 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005947 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005948 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5949 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005950 } else
5951 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005952
Richard Smith1b78b3d2012-01-25 22:15:11 +00005953 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005954 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005955 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005956 RefValue))
5957 return false;
5958 return Success(RefValue, E);
5959 }
5960 return true;
5961 }
5962
5963 bool VisitBinaryOperator(const BinaryOperator *E) {
5964 switch (E->getOpcode()) {
5965 default:
5966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5967
5968 case BO_PtrMemD:
5969 case BO_PtrMemI:
5970 return HandleMemberPointerAccess(this->Info, E, Result);
5971 }
5972 }
5973
5974 bool VisitCastExpr(const CastExpr *E) {
5975 switch (E->getCastKind()) {
5976 default:
5977 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5978
5979 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005980 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005981 if (!this->Visit(E->getSubExpr()))
5982 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005983
5984 // Now figure out the necessary offset to add to the base LV to get from
5985 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005986 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5987 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005988 }
5989 }
5990};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005991}
Richard Smith027bf112011-11-17 22:56:20 +00005992
5993//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005994// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005995//
5996// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5997// function designators (in C), decl references to void objects (in C), and
5998// temporaries (if building with -Wno-address-of-temporary).
5999//
6000// LValue evaluation produces values comprising a base expression of one of the
6001// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006002// - Declarations
6003// * VarDecl
6004// * FunctionDecl
6005// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006006// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006007// * StringLiteral
6008// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006009// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006010// * ObjCEncodeExpr
6011// * AddrLabelExpr
6012// * BlockExpr
6013// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006014// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006015// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006016// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006017// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006018// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6019// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006020// * A MaterializeTemporaryExpr that has static storage duration, with no
6021// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006022// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006023//===----------------------------------------------------------------------===//
6024namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006025class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006026 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006027public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006028 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6029 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006030
Richard Smith11562c52011-10-28 17:51:58 +00006031 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006032 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006033
Peter Collingbournee9200682011-05-13 03:29:01 +00006034 bool VisitDeclRefExpr(const DeclRefExpr *E);
6035 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006036 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006037 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6038 bool VisitMemberExpr(const MemberExpr *E);
6039 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6040 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006041 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006042 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006043 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6044 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006045 bool VisitUnaryReal(const UnaryOperator *E);
6046 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006047 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6048 return VisitUnaryPreIncDec(UO);
6049 }
6050 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6051 return VisitUnaryPreIncDec(UO);
6052 }
Richard Smith3229b742013-05-05 21:17:10 +00006053 bool VisitBinAssign(const BinaryOperator *BO);
6054 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006055
Peter Collingbournee9200682011-05-13 03:29:01 +00006056 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006057 switch (E->getCastKind()) {
6058 default:
Richard Smith027bf112011-11-17 22:56:20 +00006059 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006060
Eli Friedmance3e02a2011-10-11 00:13:24 +00006061 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006062 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006063 if (!Visit(E->getSubExpr()))
6064 return false;
6065 Result.Designator.setInvalid();
6066 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006067
Richard Smith027bf112011-11-17 22:56:20 +00006068 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006069 if (!Visit(E->getSubExpr()))
6070 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006071 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006072
6073 case CK_Dynamic:
6074 if (!Visit(E->getSubExpr()))
6075 return false;
6076 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006077 }
6078 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006079};
6080} // end anonymous namespace
6081
Richard Smith11562c52011-10-28 17:51:58 +00006082/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006083/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006084/// * function designators in C, and
6085/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006086/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006087static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6088 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006089 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006090 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006091 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006092}
6093
Peter Collingbournee9200682011-05-13 03:29:01 +00006094bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006096 return Success(FD);
6097 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006098 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006099 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006100 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006101 return Error(E);
6102}
Richard Smith733237d2011-10-24 23:14:33 +00006103
Faisal Vali0528a312016-11-13 06:09:16 +00006104
Richard Smith11562c52011-10-28 17:51:58 +00006105bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006106
6107 // If we are within a lambda's call operator, check whether the 'VD' referred
6108 // to within 'E' actually represents a lambda-capture that maps to a
6109 // data-member/field within the closure object, and if so, evaluate to the
6110 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006111 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6112 isa<DeclRefExpr>(E) &&
6113 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6114 // We don't always have a complete capture-map when checking or inferring if
6115 // the function call operator meets the requirements of a constexpr function
6116 // - but we don't need to evaluate the captures to determine constexprness
6117 // (dcl.constexpr C++17).
6118 if (Info.checkingPotentialConstantExpression())
6119 return false;
6120
Faisal Vali051e3a22017-02-16 04:12:21 +00006121 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006122 // Start with 'Result' referring to the complete closure object...
6123 Result = *Info.CurrentCall->This;
6124 // ... then update it to refer to the field of the closure object
6125 // that represents the capture.
6126 if (!HandleLValueMember(Info, E, Result, FD))
6127 return false;
6128 // And if the field is of reference type, update 'Result' to refer to what
6129 // the field refers to.
6130 if (FD->getType()->isReferenceType()) {
6131 APValue RVal;
6132 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6133 RVal))
6134 return false;
6135 Result.setFrom(Info.Ctx, RVal);
6136 }
6137 return true;
6138 }
6139 }
Craig Topper36250ad2014-05-12 05:36:57 +00006140 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006141 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6142 // Only if a local variable was declared in the function currently being
6143 // evaluated, do we expect to be able to find its value in the current
6144 // frame. (Otherwise it was likely declared in an enclosing context and
6145 // could either have a valid evaluatable value (for e.g. a constexpr
6146 // variable) or be ill-formed (and trigger an appropriate evaluation
6147 // diagnostic)).
6148 if (Info.CurrentCall->Callee &&
6149 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6150 Frame = Info.CurrentCall;
6151 }
6152 }
Richard Smith3229b742013-05-05 21:17:10 +00006153
Richard Smithfec09922011-11-01 16:57:24 +00006154 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006155 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006156 Result.set({VD, Frame->Index,
6157 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006158 return true;
6159 }
Richard Smithce40ad62011-11-12 22:28:03 +00006160 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006161 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006162
Richard Smith3229b742013-05-05 21:17:10 +00006163 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006164 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006165 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006166 if (!V->hasValue()) {
6167 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6168 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006169 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006170 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006171 return false;
6172 }
Richard Smith3229b742013-05-05 21:17:10 +00006173 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006174}
6175
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006176bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6177 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006178 // Walk through the expression to find the materialized temporary itself.
6179 SmallVector<const Expr *, 2> CommaLHSs;
6180 SmallVector<SubobjectAdjustment, 2> Adjustments;
6181 const Expr *Inner = E->GetTemporaryExpr()->
6182 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006183
Richard Smith84401042013-06-03 05:03:02 +00006184 // If we passed any comma operators, evaluate their LHSs.
6185 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6186 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6187 return false;
6188
Richard Smithe6c01442013-06-05 00:46:14 +00006189 // A materialized temporary with static storage duration can appear within the
6190 // result of a constant expression evaluation, so we need to preserve its
6191 // value for use outside this evaluation.
6192 APValue *Value;
6193 if (E->getStorageDuration() == SD_Static) {
6194 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006195 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006196 Result.set(E);
6197 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006198 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6199 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006200 }
6201
Richard Smithea4ad5d2013-06-06 08:19:16 +00006202 QualType Type = Inner->getType();
6203
Richard Smith84401042013-06-03 05:03:02 +00006204 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006205 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6206 (E->getStorageDuration() == SD_Static &&
6207 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6208 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006209 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006210 }
Richard Smith84401042013-06-03 05:03:02 +00006211
6212 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006213 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6214 --I;
6215 switch (Adjustments[I].Kind) {
6216 case SubobjectAdjustment::DerivedToBaseAdjustment:
6217 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6218 Type, Result))
6219 return false;
6220 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6221 break;
6222
6223 case SubobjectAdjustment::FieldAdjustment:
6224 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6225 return false;
6226 Type = Adjustments[I].Field->getType();
6227 break;
6228
6229 case SubobjectAdjustment::MemberPointerAdjustment:
6230 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6231 Adjustments[I].Ptr.RHS))
6232 return false;
6233 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6234 break;
6235 }
6236 }
6237
6238 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006239}
6240
Peter Collingbournee9200682011-05-13 03:29:01 +00006241bool
6242LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006243 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6244 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006245 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6246 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006247 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006248}
6249
Richard Smith6e525142011-12-27 12:18:28 +00006250bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006251 TypeInfoLValue TypeInfo;
6252
Richard Smithee0ce3022019-05-17 07:06:46 +00006253 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006254 if (E->isTypeOperand())
6255 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6256 else
6257 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006258 } else {
6259 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6260 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6261 << E->getExprOperand()->getType()
6262 << E->getExprOperand()->getSourceRange();
6263 }
6264
6265 if (!Visit(E->getExprOperand()))
6266 return false;
6267
6268 Optional<DynamicType> DynType =
6269 ComputeDynamicType(Info, E, Result, AK_TypeId);
6270 if (!DynType)
6271 return false;
6272
6273 TypeInfo =
6274 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006275 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006276
Richard Smitha9330302019-05-17 19:19:28 +00006277 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006278}
6279
Francois Pichet0066db92012-04-16 04:08:35 +00006280bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6281 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006282}
Francois Pichet0066db92012-04-16 04:08:35 +00006283
Peter Collingbournee9200682011-05-13 03:29:01 +00006284bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006285 // Handle static data members.
6286 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006287 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006288 return VisitVarDecl(E, VD);
6289 }
6290
Richard Smith254a73d2011-10-28 22:34:42 +00006291 // Handle static member functions.
6292 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6293 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006294 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006295 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006296 }
6297 }
6298
Richard Smithd62306a2011-11-10 06:34:14 +00006299 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006300 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006301}
6302
Peter Collingbournee9200682011-05-13 03:29:01 +00006303bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006304 // FIXME: Deal with vectors as array subscript bases.
6305 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006306 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006307
Nick Lewyckyad888682017-04-27 07:27:36 +00006308 bool Success = true;
6309 if (!evaluatePointer(E->getBase(), Result)) {
6310 if (!Info.noteFailure())
6311 return false;
6312 Success = false;
6313 }
Mike Stump11289f42009-09-09 15:08:12 +00006314
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006315 APSInt Index;
6316 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006317 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006318
Nick Lewyckyad888682017-04-27 07:27:36 +00006319 return Success &&
6320 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006321}
Eli Friedman9a156e52008-11-12 09:44:48 +00006322
Peter Collingbournee9200682011-05-13 03:29:01 +00006323bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006324 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006325}
6326
Richard Smith66c96992012-02-18 22:04:06 +00006327bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6328 if (!Visit(E->getSubExpr()))
6329 return false;
6330 // __real is a no-op on scalar lvalues.
6331 if (E->getSubExpr()->getType()->isAnyComplexType())
6332 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6333 return true;
6334}
6335
6336bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6337 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6338 "lvalue __imag__ on scalar?");
6339 if (!Visit(E->getSubExpr()))
6340 return false;
6341 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6342 return true;
6343}
6344
Richard Smith243ef902013-05-05 23:31:59 +00006345bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006346 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006347 return Error(UO);
6348
6349 if (!this->Visit(UO->getSubExpr()))
6350 return false;
6351
Richard Smith243ef902013-05-05 23:31:59 +00006352 return handleIncDec(
6353 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006354 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006355}
6356
6357bool LValueExprEvaluator::VisitCompoundAssignOperator(
6358 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006359 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006360 return Error(CAO);
6361
Richard Smith3229b742013-05-05 21:17:10 +00006362 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006363
6364 // The overall lvalue result is the result of evaluating the LHS.
6365 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006366 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006367 Evaluate(RHS, this->Info, CAO->getRHS());
6368 return false;
6369 }
6370
Richard Smith3229b742013-05-05 21:17:10 +00006371 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6372 return false;
6373
Richard Smith43e77732013-05-07 04:50:00 +00006374 return handleCompoundAssignment(
6375 this->Info, CAO,
6376 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6377 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006378}
6379
6380bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006381 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006382 return Error(E);
6383
Richard Smith3229b742013-05-05 21:17:10 +00006384 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006385
6386 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006387 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006388 Evaluate(NewVal, this->Info, E->getRHS());
6389 return false;
6390 }
6391
Richard Smith3229b742013-05-05 21:17:10 +00006392 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6393 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006394
Richard Smith31c69a32019-05-21 23:15:20 +00006395 if (Info.getLangOpts().CPlusPlus2a &&
6396 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6397 return false;
6398
Richard Smith243ef902013-05-05 23:31:59 +00006399 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006400 NewVal);
6401}
6402
Eli Friedman9a156e52008-11-12 09:44:48 +00006403//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006404// Pointer Evaluation
6405//===----------------------------------------------------------------------===//
6406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006407/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006408/// returned by a function with the alloc_size attribute. Returns true if we
6409/// were successful. Places an unsigned number into `Result`.
6410///
6411/// This expects the given CallExpr to be a call to a function with an
6412/// alloc_size attribute.
6413static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6414 const CallExpr *Call,
6415 llvm::APInt &Result) {
6416 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6417
Joel E. Denny81508102018-03-13 14:51:22 +00006418 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6419 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006420 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6421 if (Call->getNumArgs() <= SizeArgNo)
6422 return false;
6423
6424 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006425 Expr::EvalResult ExprResult;
6426 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006427 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006428 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006429 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6430 return false;
6431 Into = Into.zextOrSelf(BitsInSizeT);
6432 return true;
6433 };
6434
6435 APSInt SizeOfElem;
6436 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6437 return false;
6438
Joel E. Denny81508102018-03-13 14:51:22 +00006439 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006440 Result = std::move(SizeOfElem);
6441 return true;
6442 }
6443
6444 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006445 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006446 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6447 return false;
6448
6449 bool Overflow;
6450 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6451 if (Overflow)
6452 return false;
6453
6454 Result = std::move(BytesAvailable);
6455 return true;
6456}
6457
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006458/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006459/// function.
6460static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6461 const LValue &LVal,
6462 llvm::APInt &Result) {
6463 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6464 "Can't get the size of a non alloc_size function");
6465 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6466 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6467 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6468}
6469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006470/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006471/// a function with the alloc_size attribute. If it was possible to do so, this
6472/// function will return true, make Result's Base point to said function call,
6473/// and mark Result's Base as invalid.
6474static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6475 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006476 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006477 return false;
6478
6479 // Because we do no form of static analysis, we only support const variables.
6480 //
6481 // Additionally, we can't support parameters, nor can we support static
6482 // variables (in the latter case, use-before-assign isn't UB; in the former,
6483 // we have no clue what they'll be assigned to).
6484 const auto *VD =
6485 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6486 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6487 return false;
6488
6489 const Expr *Init = VD->getAnyInitializer();
6490 if (!Init)
6491 return false;
6492
6493 const Expr *E = Init->IgnoreParens();
6494 if (!tryUnwrapAllocSizeCall(E))
6495 return false;
6496
6497 // Store E instead of E unwrapped so that the type of the LValue's base is
6498 // what the user wanted.
6499 Result.setInvalid(E);
6500
6501 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006502 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00006503 return true;
6504}
6505
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006506namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006507class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006508 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00006509 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006510 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00006511
Peter Collingbournee9200682011-05-13 03:29:01 +00006512 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00006513 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00006514 return true;
6515 }
George Burgess IVe3763372016-12-22 02:50:20 +00006516
George Burgess IVf9013bf2017-02-10 22:52:29 +00006517 bool evaluateLValue(const Expr *E, LValue &Result) {
6518 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6519 }
6520
6521 bool evaluatePointer(const Expr *E, LValue &Result) {
6522 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6523 }
6524
George Burgess IVe3763372016-12-22 02:50:20 +00006525 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006526public:
Mike Stump11289f42009-09-09 15:08:12 +00006527
George Burgess IVf9013bf2017-02-10 22:52:29 +00006528 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6529 : ExprEvaluatorBaseTy(info), Result(Result),
6530 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006531
Richard Smith2e312c82012-03-03 22:46:17 +00006532 bool Success(const APValue &V, const Expr *E) {
6533 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00006534 return true;
6535 }
Richard Smithfddd3842011-12-30 21:15:51 +00006536 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00006537 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6538 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00006539 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00006540 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006541
John McCall45d55e42010-05-07 21:00:08 +00006542 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006543 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00006544 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006545 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00006546 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006547 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00006548 if (E->isExpressibleAsConstantInitializer())
6549 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006550 if (Info.noteFailure())
6551 EvaluateIgnoredValue(Info, E->getSubExpr());
6552 return Error(E);
6553 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006554 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00006555 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00006556 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006557 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00006558 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00006559 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00006560 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006561 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00006562 }
Richard Smithd62306a2011-11-10 06:34:14 +00006563 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006564 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00006565 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00006566 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00006567 if (!Info.CurrentCall->This) {
6568 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00006569 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00006570 else
Faisal Valie690b7a2016-07-02 22:34:24 +00006571 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00006572 return false;
6573 }
Richard Smithd62306a2011-11-10 06:34:14 +00006574 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00006575 // If we are inside a lambda's call operator, the 'this' expression refers
6576 // to the enclosing '*this' object (either by value or reference) which is
6577 // either copied into the closure object's field that represents the '*this'
6578 // or refers to '*this'.
6579 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6580 // Update 'Result' to refer to the data member/field of the closure object
6581 // that represents the '*this' capture.
6582 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00006583 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00006584 return false;
6585 // If we captured '*this' by reference, replace the field with its referent.
6586 if (Info.CurrentCall->LambdaThisCaptureField->getType()
6587 ->isPointerType()) {
6588 APValue RVal;
6589 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6590 RVal))
6591 return false;
6592
6593 Result.setFrom(Info.Ctx, RVal);
6594 }
6595 }
Richard Smithd62306a2011-11-10 06:34:14 +00006596 return true;
6597 }
John McCallc07a0c72011-02-17 10:25:35 +00006598
Eric Fiselier708afb52019-05-16 21:04:15 +00006599 bool VisitSourceLocExpr(const SourceLocExpr *E) {
6600 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6601 APValue LValResult = E->EvaluateInContext(
6602 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6603 Result.setFrom(Info.Ctx, LValResult);
6604 return true;
6605 }
6606
Eli Friedman449fe542009-03-23 04:56:01 +00006607 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006608};
Chris Lattner05706e882008-07-11 18:11:29 +00006609} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006610
George Burgess IVf9013bf2017-02-10 22:52:29 +00006611static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6612 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00006613 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00006614 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00006615}
6616
John McCall45d55e42010-05-07 21:00:08 +00006617bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00006618 if (E->getOpcode() != BO_Add &&
6619 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00006620 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00006621
Chris Lattner05706e882008-07-11 18:11:29 +00006622 const Expr *PExp = E->getLHS();
6623 const Expr *IExp = E->getRHS();
6624 if (IExp->getType()->isPointerType())
6625 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00006626
George Burgess IVf9013bf2017-02-10 22:52:29 +00006627 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00006628 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00006629 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006630
John McCall45d55e42010-05-07 21:00:08 +00006631 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00006632 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00006633 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006634
Richard Smith96e0c102011-11-04 02:25:55 +00006635 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00006636 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006637
Ted Kremenek28831752012-08-23 20:46:57 +00006638 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00006639 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006640}
Eli Friedman9a156e52008-11-12 09:44:48 +00006641
John McCall45d55e42010-05-07 21:00:08 +00006642bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006643 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006644}
Mike Stump11289f42009-09-09 15:08:12 +00006645
Richard Smith81dfef92018-07-11 00:29:05 +00006646bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6647 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00006648
Eli Friedman847a2bc2009-12-27 05:43:15 +00006649 switch (E->getCastKind()) {
6650 default:
6651 break;
6652
John McCalle3027922010-08-25 11:45:40 +00006653 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00006654 case CK_CPointerToObjCPointerCast:
6655 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00006656 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00006657 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00006658 if (!Visit(SubExpr))
6659 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006660 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6661 // permitted in constant expressions in C++11. Bitcasts from cv void* are
6662 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00006663 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00006664 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00006665 if (SubExpr->getType()->isVoidPointerType())
6666 CCEDiag(E, diag::note_constexpr_invalid_cast)
6667 << 3 << SubExpr->getType();
6668 else
6669 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6670 }
Yaxun Liu402804b2016-12-15 08:09:08 +00006671 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6672 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00006673 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00006674
Anders Carlsson18275092010-10-31 20:41:46 +00006675 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006676 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006677 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00006678 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006679 if (!Result.Base && Result.Offset.isZero())
6680 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00006681
Richard Smithd62306a2011-11-10 06:34:14 +00006682 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00006683 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006684 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6685 castAs<PointerType>()->getPointeeType(),
6686 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00006687
Richard Smith027bf112011-11-17 22:56:20 +00006688 case CK_BaseToDerived:
6689 if (!Visit(E->getSubExpr()))
6690 return false;
6691 if (!Result.Base && Result.Offset.isZero())
6692 return true;
6693 return HandleBaseToDerivedCast(Info, E, Result);
6694
Richard Smith7bd54ab2019-05-15 20:22:21 +00006695 case CK_Dynamic:
6696 if (!Visit(E->getSubExpr()))
6697 return false;
6698 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6699
Richard Smith0b0a0b62011-10-29 20:57:55 +00006700 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006701 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006702 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00006703
John McCalle3027922010-08-25 11:45:40 +00006704 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006705 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6706
Richard Smith2e312c82012-03-03 22:46:17 +00006707 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00006708 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00006709 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00006710
John McCall45d55e42010-05-07 21:00:08 +00006711 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00006712 unsigned Size = Info.Ctx.getTypeSize(E->getType());
6713 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006714 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006715 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00006716 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00006717 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00006718 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00006719 return true;
6720 } else {
6721 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00006722 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00006723 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00006724 }
6725 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00006726
6727 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00006728 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006729 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006730 return false;
6731 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006732 APValue &Value = createTemporary(SubExpr, false, Result,
6733 *Info.CurrentCall);
6734 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00006735 return false;
6736 }
Richard Smith96e0c102011-11-04 02:25:55 +00006737 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00006738 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6739 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00006740 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00006741 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00006742 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00006743 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00006744 }
Richard Smithdd785442011-10-31 20:57:44 +00006745
John McCalle3027922010-08-25 11:45:40 +00006746 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006747 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006748
6749 case CK_LValueToRValue: {
6750 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006751 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00006752 return false;
6753
6754 APValue RVal;
6755 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6756 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6757 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006758 return InvalidBaseOK &&
6759 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006760 return Success(RVal, E);
6761 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006762 }
6763
Richard Smith11562c52011-10-28 17:51:58 +00006764 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006765}
Chris Lattner05706e882008-07-11 18:11:29 +00006766
Richard Smith6822bd72018-10-26 19:26:45 +00006767static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6768 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006769 // C++ [expr.alignof]p3:
6770 // When alignof is applied to a reference type, the result is the
6771 // alignment of the referenced type.
6772 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6773 T = Ref->getPointeeType();
6774
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006775 if (T.getQualifiers().hasUnaligned())
6776 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006777
6778 const bool AlignOfReturnsPreferred =
6779 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6780
6781 // __alignof is defined to return the preferred alignment.
6782 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6783 // as well.
6784 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6785 return Info.Ctx.toCharUnitsFromBits(
6786 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6787 // alignof and _Alignof are defined to return the ABI alignment.
6788 else if (ExprKind == UETT_AlignOf)
6789 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6790 else
6791 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006792}
6793
Richard Smith6822bd72018-10-26 19:26:45 +00006794static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6795 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006796 E = E->IgnoreParens();
6797
6798 // The kinds of expressions that we have special-case logic here for
6799 // should be kept up to date with the special checks for those
6800 // expressions in Sema.
6801
6802 // alignof decl is always accepted, even if it doesn't make sense: we default
6803 // to 1 in those cases.
6804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6805 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6806 /*RefAsPointee*/true);
6807
6808 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6809 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6810 /*RefAsPointee*/true);
6811
Richard Smith6822bd72018-10-26 19:26:45 +00006812 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006813}
6814
George Burgess IVe3763372016-12-22 02:50:20 +00006815// To be clear: this happily visits unsupported builtins. Better name welcomed.
6816bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6817 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6818 return true;
6819
George Burgess IVf9013bf2017-02-10 22:52:29 +00006820 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006821 return false;
6822
6823 Result.setInvalid(E);
6824 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006825 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006826 return true;
6827}
6828
Peter Collingbournee9200682011-05-13 03:29:01 +00006829bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006830 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006831 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006832
Richard Smith6328cbd2016-11-16 00:57:23 +00006833 if (unsigned BuiltinOp = E->getBuiltinCallee())
6834 return VisitBuiltinCallExpr(E, BuiltinOp);
6835
George Burgess IVe3763372016-12-22 02:50:20 +00006836 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006837}
6838
6839bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6840 unsigned BuiltinOp) {
6841 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006842 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006843 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006844 case Builtin::BI__builtin_assume_aligned: {
6845 // We need to be very careful here because: if the pointer does not have the
6846 // asserted alignment, then the behavior is undefined, and undefined
6847 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006848 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006849 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006850
Hal Finkel0dd05d42014-10-03 17:18:37 +00006851 LValue OffsetResult(Result);
6852 APSInt Alignment;
6853 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6854 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006855 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006856
6857 if (E->getNumArgs() > 2) {
6858 APSInt Offset;
6859 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6860 return false;
6861
Richard Smith642a2362017-01-30 23:30:26 +00006862 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006863 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6864 }
6865
6866 // If there is a base object, then it must have the correct alignment.
6867 if (OffsetResult.Base) {
6868 CharUnits BaseAlignment;
6869 if (const ValueDecl *VD =
6870 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6871 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00006872 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6873 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006874 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00006875 BaseAlignment = GetAlignOfType(
6876 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006877 }
6878
6879 if (BaseAlignment < Align) {
6880 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006881 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006882 CCEDiag(E->getArg(0),
6883 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006884 << (unsigned)BaseAlignment.getQuantity()
6885 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006886 return false;
6887 }
6888 }
6889
6890 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006891 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006892 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006893
Richard Smith642a2362017-01-30 23:30:26 +00006894 (OffsetResult.Base
6895 ? CCEDiag(E->getArg(0),
6896 diag::note_constexpr_baa_insufficient_alignment) << 1
6897 : CCEDiag(E->getArg(0),
6898 diag::note_constexpr_baa_value_insufficient_alignment))
6899 << (int)OffsetResult.Offset.getQuantity()
6900 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006901 return false;
6902 }
6903
6904 return true;
6905 }
Eric Fiselier26187502018-12-14 21:11:28 +00006906 case Builtin::BI__builtin_launder:
6907 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006908 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006909 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006910 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006911 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006912 if (Info.getLangOpts().CPlusPlus11)
6913 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6914 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006915 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006916 else
6917 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006918 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006919 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006920 case Builtin::BI__builtin_wcschr:
6921 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006922 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006923 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006924 if (!Visit(E->getArg(0)))
6925 return false;
6926 APSInt Desired;
6927 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6928 return false;
6929 uint64_t MaxLength = uint64_t(-1);
6930 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006931 BuiltinOp != Builtin::BIwcschr &&
6932 BuiltinOp != Builtin::BI__builtin_strchr &&
6933 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006934 APSInt N;
6935 if (!EvaluateInteger(E->getArg(2), N, Info))
6936 return false;
6937 MaxLength = N.getExtValue();
6938 }
Hubert Tong147b7432018-12-12 16:53:43 +00006939 // We cannot find the value if there are no candidates to match against.
6940 if (MaxLength == 0u)
6941 return ZeroInitialization(E);
6942 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6943 Result.Designator.Invalid)
6944 return false;
6945 QualType CharTy = Result.Designator.getType(Info.Ctx);
6946 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6947 BuiltinOp == Builtin::BI__builtin_memchr;
6948 assert(IsRawByte ||
6949 Info.Ctx.hasSameUnqualifiedType(
6950 CharTy, E->getArg(0)->getType()->getPointeeType()));
6951 // Pointers to const void may point to objects of incomplete type.
6952 if (IsRawByte && CharTy->isIncompleteType()) {
6953 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6954 return false;
6955 }
6956 // Give up on byte-oriented matching against multibyte elements.
6957 // FIXME: We can compare the bytes in the correct order.
6958 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6959 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006960 // Figure out what value we're actually looking for (after converting to
6961 // the corresponding unsigned type if necessary).
6962 uint64_t DesiredVal;
6963 bool StopAtNull = false;
6964 switch (BuiltinOp) {
6965 case Builtin::BIstrchr:
6966 case Builtin::BI__builtin_strchr:
6967 // strchr compares directly to the passed integer, and therefore
6968 // always fails if given an int that is not a char.
6969 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6970 E->getArg(1)->getType(),
6971 Desired),
6972 Desired))
6973 return ZeroInitialization(E);
6974 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006975 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006976 case Builtin::BImemchr:
6977 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006978 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006979 // memchr compares by converting both sides to unsigned char. That's also
6980 // correct for strchr if we get this far (to cope with plain char being
6981 // unsigned in the strchr case).
6982 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6983 break;
Richard Smithe9507952016-11-12 01:39:56 +00006984
Richard Smith8110c9d2016-11-29 19:45:17 +00006985 case Builtin::BIwcschr:
6986 case Builtin::BI__builtin_wcschr:
6987 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006988 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006989 case Builtin::BIwmemchr:
6990 case Builtin::BI__builtin_wmemchr:
6991 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6992 DesiredVal = Desired.getZExtValue();
6993 break;
6994 }
Richard Smithe9507952016-11-12 01:39:56 +00006995
6996 for (; MaxLength; --MaxLength) {
6997 APValue Char;
6998 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6999 !Char.isInt())
7000 return false;
7001 if (Char.getInt().getZExtValue() == DesiredVal)
7002 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007003 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007004 break;
7005 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7006 return false;
7007 }
7008 // Not found: return nullptr.
7009 return ZeroInitialization(E);
7010 }
7011
Richard Smith06f71b52018-08-04 00:57:17 +00007012 case Builtin::BImemcpy:
7013 case Builtin::BImemmove:
7014 case Builtin::BIwmemcpy:
7015 case Builtin::BIwmemmove:
7016 if (Info.getLangOpts().CPlusPlus11)
7017 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7018 << /*isConstexpr*/0 << /*isConstructor*/0
7019 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7020 else
7021 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7022 LLVM_FALLTHROUGH;
7023 case Builtin::BI__builtin_memcpy:
7024 case Builtin::BI__builtin_memmove:
7025 case Builtin::BI__builtin_wmemcpy:
7026 case Builtin::BI__builtin_wmemmove: {
7027 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7028 BuiltinOp == Builtin::BIwmemmove ||
7029 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7030 BuiltinOp == Builtin::BI__builtin_wmemmove;
7031 bool Move = BuiltinOp == Builtin::BImemmove ||
7032 BuiltinOp == Builtin::BIwmemmove ||
7033 BuiltinOp == Builtin::BI__builtin_memmove ||
7034 BuiltinOp == Builtin::BI__builtin_wmemmove;
7035
7036 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007037 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007038 return false;
7039 LValue Dest = Result;
7040
7041 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007042 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007043 return false;
7044
7045 APSInt N;
7046 if (!EvaluateInteger(E->getArg(2), N, Info))
7047 return false;
7048 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7049
7050 // If the size is zero, we treat this as always being a valid no-op.
7051 // (Even if one of the src and dest pointers is null.)
7052 if (!N)
7053 return true;
7054
Richard Smith128719c2018-09-13 22:47:33 +00007055 // Otherwise, if either of the operands is null, we can't proceed. Don't
7056 // try to determine the type of the copied objects, because there aren't
7057 // any.
7058 if (!Src.Base || !Dest.Base) {
7059 APValue Val;
7060 (!Src.Base ? Src : Dest).moveInto(Val);
7061 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7062 << Move << WChar << !!Src.Base
7063 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7064 return false;
7065 }
7066 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7067 return false;
7068
Richard Smith06f71b52018-08-04 00:57:17 +00007069 // We require that Src and Dest are both pointers to arrays of
7070 // trivially-copyable type. (For the wide version, the designator will be
7071 // invalid if the designated object is not a wchar_t.)
7072 QualType T = Dest.Designator.getType(Info.Ctx);
7073 QualType SrcT = Src.Designator.getType(Info.Ctx);
7074 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7075 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7076 return false;
7077 }
Petr Pavlued083f22018-10-04 09:25:44 +00007078 if (T->isIncompleteType()) {
7079 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7080 return false;
7081 }
Richard Smith06f71b52018-08-04 00:57:17 +00007082 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7083 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7084 return false;
7085 }
7086
7087 // Figure out how many T's we're copying.
7088 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7089 if (!WChar) {
7090 uint64_t Remainder;
7091 llvm::APInt OrigN = N;
7092 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7093 if (Remainder) {
7094 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7095 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7096 << (unsigned)TSize;
7097 return false;
7098 }
7099 }
7100
7101 // Check that the copying will remain within the arrays, just so that we
7102 // can give a more meaningful diagnostic. This implicitly also checks that
7103 // N fits into 64 bits.
7104 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7105 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7106 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7107 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7108 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7109 << N.toString(10, /*Signed*/false);
7110 return false;
7111 }
7112 uint64_t NElems = N.getZExtValue();
7113 uint64_t NBytes = NElems * TSize;
7114
7115 // Check for overlap.
7116 int Direction = 1;
7117 if (HasSameBase(Src, Dest)) {
7118 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7119 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7120 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7121 // Dest is inside the source region.
7122 if (!Move) {
7123 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7124 return false;
7125 }
7126 // For memmove and friends, copy backwards.
7127 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7128 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7129 return false;
7130 Direction = -1;
7131 } else if (!Move && SrcOffset >= DestOffset &&
7132 SrcOffset - DestOffset < NBytes) {
7133 // Src is inside the destination region for memcpy: invalid.
7134 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7135 return false;
7136 }
7137 }
7138
7139 while (true) {
7140 APValue Val;
7141 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7142 !handleAssignment(Info, E, Dest, T, Val))
7143 return false;
7144 // Do not iterate past the last element; if we're copying backwards, that
7145 // might take us off the start of the array.
7146 if (--NElems == 0)
7147 return true;
7148 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7149 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7150 return false;
7151 }
7152 }
7153
Richard Smith6cbd65d2013-07-11 02:27:57 +00007154 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007155 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007156 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007157}
Chris Lattner05706e882008-07-11 18:11:29 +00007158
7159//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007160// Member Pointer Evaluation
7161//===----------------------------------------------------------------------===//
7162
7163namespace {
7164class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007165 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007166 MemberPtr &Result;
7167
7168 bool Success(const ValueDecl *D) {
7169 Result = MemberPtr(D);
7170 return true;
7171 }
7172public:
7173
7174 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7175 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7176
Richard Smith2e312c82012-03-03 22:46:17 +00007177 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007178 Result.setFrom(V);
7179 return true;
7180 }
Richard Smithfddd3842011-12-30 21:15:51 +00007181 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007182 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007183 }
7184
7185 bool VisitCastExpr(const CastExpr *E);
7186 bool VisitUnaryAddrOf(const UnaryOperator *E);
7187};
7188} // end anonymous namespace
7189
7190static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7191 EvalInfo &Info) {
7192 assert(E->isRValue() && E->getType()->isMemberPointerType());
7193 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7194}
7195
7196bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7197 switch (E->getCastKind()) {
7198 default:
7199 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7200
7201 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007202 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007203 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007204
7205 case CK_BaseToDerivedMemberPointer: {
7206 if (!Visit(E->getSubExpr()))
7207 return false;
7208 if (E->path_empty())
7209 return true;
7210 // Base-to-derived member pointer casts store the path in derived-to-base
7211 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7212 // the wrong end of the derived->base arc, so stagger the path by one class.
7213 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7214 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7215 PathI != PathE; ++PathI) {
7216 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7217 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7218 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007219 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007220 }
7221 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7222 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007223 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007224 return true;
7225 }
7226
7227 case CK_DerivedToBaseMemberPointer:
7228 if (!Visit(E->getSubExpr()))
7229 return false;
7230 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7231 PathE = E->path_end(); PathI != PathE; ++PathI) {
7232 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7233 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7234 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007235 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007236 }
7237 return true;
7238 }
7239}
7240
7241bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7242 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7243 // member can be formed.
7244 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7245}
7246
7247//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007248// Record Evaluation
7249//===----------------------------------------------------------------------===//
7250
7251namespace {
7252 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007253 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007254 const LValue &This;
7255 APValue &Result;
7256 public:
7257
7258 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7259 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7260
Richard Smith2e312c82012-03-03 22:46:17 +00007261 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007262 Result = V;
7263 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007264 }
Richard Smithb8348f52016-05-12 22:16:28 +00007265 bool ZeroInitialization(const Expr *E) {
7266 return ZeroInitialization(E, E->getType());
7267 }
7268 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007269
Richard Smith52a980a2015-08-28 02:43:42 +00007270 bool VisitCallExpr(const CallExpr *E) {
7271 return handleCallExpr(E, Result, &This);
7272 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007273 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007274 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007275 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7276 return VisitCXXConstructExpr(E, E->getType());
7277 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007278 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007279 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007280 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007281 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007282
7283 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007284 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007285}
Richard Smithd62306a2011-11-10 06:34:14 +00007286
Richard Smithfddd3842011-12-30 21:15:51 +00007287/// Perform zero-initialization on an object of non-union class type.
7288/// C++11 [dcl.init]p5:
7289/// To zero-initialize an object or reference of type T means:
7290/// [...]
7291/// -- if T is a (possibly cv-qualified) non-union class type,
7292/// each non-static data member and each base-class subobject is
7293/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007294static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7295 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007296 const LValue &This, APValue &Result) {
7297 assert(!RD->isUnion() && "Expected non-union class type");
7298 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7299 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007300 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007301
John McCalld7bca762012-05-01 00:38:49 +00007302 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007303 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7304
7305 if (CD) {
7306 unsigned Index = 0;
7307 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007308 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007309 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7310 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007311 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7312 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007313 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007314 Result.getStructBase(Index)))
7315 return false;
7316 }
7317 }
7318
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007319 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007320 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007321 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007322 continue;
7323
7324 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007325 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007326 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007327
David Blaikie2d7c57e2012-04-30 02:36:29 +00007328 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007329 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007330 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007331 return false;
7332 }
7333
7334 return true;
7335}
7336
Richard Smithb8348f52016-05-12 22:16:28 +00007337bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7338 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007339 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007340 if (RD->isUnion()) {
7341 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7342 // object's first non-static named data member is zero-initialized
7343 RecordDecl::field_iterator I = RD->field_begin();
7344 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007345 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007346 return true;
7347 }
7348
7349 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007350 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007351 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007352 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007353 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007354 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007355 }
7356
Richard Smith5d108602012-02-17 00:44:16 +00007357 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007358 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007359 return false;
7360 }
7361
Richard Smitha8105bc2012-01-06 16:39:00 +00007362 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007363}
7364
Richard Smithe97cbd72011-11-11 04:05:33 +00007365bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7366 switch (E->getCastKind()) {
7367 default:
7368 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7369
7370 case CK_ConstructorConversion:
7371 return Visit(E->getSubExpr());
7372
7373 case CK_DerivedToBase:
7374 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007375 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007376 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007377 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007378 if (!DerivedObject.isStruct())
7379 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007380
7381 // Derived-to-base rvalue conversion: just slice off the derived part.
7382 APValue *Value = &DerivedObject;
7383 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7384 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7385 PathE = E->path_end(); PathI != PathE; ++PathI) {
7386 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7387 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7388 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7389 RD = Base;
7390 }
7391 Result = *Value;
7392 return true;
7393 }
7394 }
7395}
7396
Richard Smithd62306a2011-11-10 06:34:14 +00007397bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007398 if (E->isTransparent())
7399 return Visit(E->getInit(0));
7400
Richard Smithd62306a2011-11-10 06:34:14 +00007401 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007402 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007403 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007404 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7405
7406 EvalInfo::EvaluatingConstructorRAII EvalObj(
7407 Info,
7408 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7409 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007410
7411 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007412 const FieldDecl *Field = E->getInitializedFieldInUnion();
7413 Result = APValue(Field);
7414 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007415 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007416
7417 // If the initializer list for a union does not contain any elements, the
7418 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007419 // FIXME: The element should be initialized from an initializer list.
7420 // Is this difference ever observable for initializer lists which
7421 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007422 ImplicitValueInitExpr VIE(Field->getType());
7423 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7424
Richard Smithd62306a2011-11-10 06:34:14 +00007425 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007426 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7427 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007428
7429 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7430 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7431 isa<CXXDefaultInitExpr>(InitExpr));
7432
Richard Smithb228a862012-02-15 02:18:13 +00007433 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007434 }
7435
Richard Smithe637cbe2019-05-21 23:15:18 +00007436 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007437 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7438 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007439 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007440 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007441
7442 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007443 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007444 for (const auto &Base : CXXRD->bases()) {
7445 assert(ElementNo < E->getNumInits() && "missing init for base class");
7446 const Expr *Init = E->getInit(ElementNo);
7447
7448 LValue Subobject = This;
7449 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7450 return false;
7451
7452 APValue &FieldVal = Result.getStructBase(ElementNo);
7453 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007454 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007455 return false;
7456 Success = false;
7457 }
7458 ++ElementNo;
7459 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007460
7461 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007462 }
7463
7464 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007465 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007466 // Anonymous bit-fields are not considered members of the class for
7467 // purposes of aggregate initialization.
7468 if (Field->isUnnamedBitfield())
7469 continue;
7470
7471 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007472
Richard Smith253c2a32012-01-27 01:14:48 +00007473 bool HaveInit = ElementNo < E->getNumInits();
7474
7475 // FIXME: Diagnostics here should point to the end of the initializer
7476 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007477 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007478 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007479 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007480
7481 // Perform an implicit value-initialization for members beyond the end of
7482 // the initializer list.
7483 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007484 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007485
Richard Smith852c9db2013-04-20 22:23:05 +00007486 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7487 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7488 isa<CXXDefaultInitExpr>(Init));
7489
Richard Smith49ca8aa2013-08-06 07:09:20 +00007490 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7491 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7492 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007493 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007494 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007495 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007496 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007497 }
7498 }
7499
Richard Smith253c2a32012-01-27 01:14:48 +00007500 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007501}
7502
Richard Smithb8348f52016-05-12 22:16:28 +00007503bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7504 QualType T) {
7505 // Note that E's type is not necessarily the type of our class here; we might
7506 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00007507 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00007508 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7509
Richard Smithfddd3842011-12-30 21:15:51 +00007510 bool ZeroInit = E->requiresZeroInitialization();
7511 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00007512 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00007513 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00007514 return true;
7515
Richard Smithda3f4fd2014-03-05 23:32:50 +00007516 // We can get here in two different ways:
7517 // 1) We're performing value-initialization, and should zero-initialize
7518 // the object, or
7519 // 2) We're performing default-initialization of an object with a trivial
7520 // constexpr default constructor, in which case we should start the
7521 // lifetimes of all the base subobjects (there can be no data member
7522 // subobjects in this case) per [basic.life]p1.
7523 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00007524 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00007525 }
7526
Craig Topper36250ad2014-05-12 05:36:57 +00007527 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007528 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00007529
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007530 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00007531 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007532
Richard Smith1bc5c2c2012-01-10 04:32:03 +00007533 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00007534 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00007535 if (const MaterializeTemporaryExpr *ME
7536 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7537 return Visit(ME->GetTemporaryExpr());
7538
Richard Smithb8348f52016-05-12 22:16:28 +00007539 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00007540 return false;
7541
Craig Topper5fc8fc22014-08-27 06:28:36 +00007542 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00007543 return HandleConstructorCall(E, This, Args,
7544 cast<CXXConstructorDecl>(Definition), Info,
7545 Result);
7546}
7547
7548bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7549 const CXXInheritedCtorInitExpr *E) {
7550 if (!Info.CurrentCall) {
7551 assert(Info.checkingPotentialConstantExpression());
7552 return false;
7553 }
7554
7555 const CXXConstructorDecl *FD = E->getConstructor();
7556 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7557 return false;
7558
7559 const FunctionDecl *Definition = nullptr;
7560 auto Body = FD->getBody(Definition);
7561
7562 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7563 return false;
7564
7565 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566 cast<CXXConstructorDecl>(Definition), Info,
7567 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00007568}
7569
Richard Smithcc1b96d2013-06-12 22:31:48 +00007570bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7571 const CXXStdInitializerListExpr *E) {
7572 const ConstantArrayType *ArrayType =
7573 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7574
7575 LValue Array;
7576 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7577 return false;
7578
7579 // Get a pointer to the first element of the array.
7580 Array.addArray(Info, E, ArrayType);
7581
7582 // FIXME: Perform the checks on the field types in SemaInit.
7583 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7584 RecordDecl::field_iterator Field = Record->field_begin();
7585 if (Field == Record->field_end())
7586 return Error(E);
7587
7588 // Start pointer.
7589 if (!Field->getType()->isPointerType() ||
7590 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7591 ArrayType->getElementType()))
7592 return Error(E);
7593
7594 // FIXME: What if the initializer_list type has base classes, etc?
7595 Result = APValue(APValue::UninitStruct(), 0, 2);
7596 Array.moveInto(Result.getStructField(0));
7597
7598 if (++Field == Record->field_end())
7599 return Error(E);
7600
7601 if (Field->getType()->isPointerType() &&
7602 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7603 ArrayType->getElementType())) {
7604 // End pointer.
7605 if (!HandleLValueArrayAdjustment(Info, E, Array,
7606 ArrayType->getElementType(),
7607 ArrayType->getSize().getZExtValue()))
7608 return false;
7609 Array.moveInto(Result.getStructField(1));
7610 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7611 // Length.
7612 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7613 else
7614 return Error(E);
7615
7616 if (++Field != Record->field_end())
7617 return Error(E);
7618
7619 return true;
7620}
7621
Faisal Valic72a08c2017-01-09 03:02:53 +00007622bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7623 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7624 if (ClosureClass->isInvalidDecl()) return false;
7625
7626 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007627
Faisal Vali051e3a22017-02-16 04:12:21 +00007628 const size_t NumFields =
7629 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00007630
7631 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7632 E->capture_init_end()) &&
7633 "The number of lambda capture initializers should equal the number of "
7634 "fields within the closure type");
7635
Faisal Vali051e3a22017-02-16 04:12:21 +00007636 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7637 // Iterate through all the lambda's closure object's fields and initialize
7638 // them.
7639 auto *CaptureInitIt = E->capture_init_begin();
7640 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7641 bool Success = true;
7642 for (const auto *Field : ClosureClass->fields()) {
7643 assert(CaptureInitIt != E->capture_init_end());
7644 // Get the initializer for this field
7645 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00007646
Faisal Vali051e3a22017-02-16 04:12:21 +00007647 // If there is no initializer, either this is a VLA or an error has
7648 // occurred.
7649 if (!CurFieldInit)
7650 return Error(E);
7651
7652 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7653 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7654 if (!Info.keepEvaluatingAfterFailure())
7655 return false;
7656 Success = false;
7657 }
7658 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00007659 }
Faisal Vali051e3a22017-02-16 04:12:21 +00007660 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00007661}
7662
Richard Smithd62306a2011-11-10 06:34:14 +00007663static bool EvaluateRecord(const Expr *E, const LValue &This,
7664 APValue &Result, EvalInfo &Info) {
7665 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00007666 "can't evaluate expression as a record rvalue");
7667 return RecordExprEvaluator(Info, This, Result).Visit(E);
7668}
7669
7670//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007671// Temporary Evaluation
7672//
7673// Temporaries are represented in the AST as rvalues, but generally behave like
7674// lvalues. The full-object of which the temporary is a subobject is implicitly
7675// materialized so that a reference can bind to it.
7676//===----------------------------------------------------------------------===//
7677namespace {
7678class TemporaryExprEvaluator
7679 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7680public:
7681 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00007682 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00007683
7684 /// Visit an expression which constructs the value of this temporary.
7685 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007686 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7687 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00007688 }
7689
7690 bool VisitCastExpr(const CastExpr *E) {
7691 switch (E->getCastKind()) {
7692 default:
7693 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7694
7695 case CK_ConstructorConversion:
7696 return VisitConstructExpr(E->getSubExpr());
7697 }
7698 }
7699 bool VisitInitListExpr(const InitListExpr *E) {
7700 return VisitConstructExpr(E);
7701 }
7702 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7703 return VisitConstructExpr(E);
7704 }
7705 bool VisitCallExpr(const CallExpr *E) {
7706 return VisitConstructExpr(E);
7707 }
Richard Smith513955c2014-12-17 19:24:30 +00007708 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7709 return VisitConstructExpr(E);
7710 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007711 bool VisitLambdaExpr(const LambdaExpr *E) {
7712 return VisitConstructExpr(E);
7713 }
Richard Smith027bf112011-11-17 22:56:20 +00007714};
7715} // end anonymous namespace
7716
7717/// Evaluate an expression of record type as a temporary.
7718static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007719 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00007720 return TemporaryExprEvaluator(Info, Result).Visit(E);
7721}
7722
7723//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007724// Vector Evaluation
7725//===----------------------------------------------------------------------===//
7726
7727namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007728 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007729 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00007730 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007731 public:
Mike Stump11289f42009-09-09 15:08:12 +00007732
Richard Smith2d406342011-10-22 21:10:00 +00007733 VectorExprEvaluator(EvalInfo &info, APValue &Result)
7734 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00007735
Craig Topper9798b932015-09-29 04:30:05 +00007736 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007737 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7738 // FIXME: remove this APValue copy.
7739 Result = APValue(V.data(), V.size());
7740 return true;
7741 }
Richard Smith2e312c82012-03-03 22:46:17 +00007742 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00007743 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00007744 Result = V;
7745 return true;
7746 }
Richard Smithfddd3842011-12-30 21:15:51 +00007747 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00007748
Richard Smith2d406342011-10-22 21:10:00 +00007749 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00007750 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00007751 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00007752 bool VisitInitListExpr(const InitListExpr *E);
7753 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007754 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00007755 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00007756 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007757 };
7758} // end anonymous namespace
7759
7760static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007761 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007762 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007763}
7764
George Burgess IV533ff002015-12-11 00:23:35 +00007765bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007766 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007767 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007768
Richard Smith161f09a2011-12-06 22:44:34 +00007769 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007770 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007771
Eli Friedmanc757de22011-03-25 00:43:55 +00007772 switch (E->getCastKind()) {
7773 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007774 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007775 if (SETy->isIntegerType()) {
7776 APSInt IntResult;
7777 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007778 return false;
7779 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007780 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007781 APFloat FloatResult(0.0);
7782 if (!EvaluateFloat(SE, FloatResult, Info))
7783 return false;
7784 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007785 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007786 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007787 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007788
7789 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007790 SmallVector<APValue, 4> Elts(NElts, Val);
7791 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007792 }
Eli Friedman803acb32011-12-22 03:51:45 +00007793 case CK_BitCast: {
7794 // Evaluate the operand into an APInt we can extract from.
7795 llvm::APInt SValInt;
7796 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7797 return false;
7798 // Extract the elements
7799 QualType EltTy = VTy->getElementType();
7800 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7801 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7802 SmallVector<APValue, 4> Elts;
7803 if (EltTy->isRealFloatingType()) {
7804 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007805 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007806 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007807 FloatEltSize = 80;
7808 for (unsigned i = 0; i < NElts; i++) {
7809 llvm::APInt Elt;
7810 if (BigEndian)
7811 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7812 else
7813 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007814 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007815 }
7816 } else if (EltTy->isIntegerType()) {
7817 for (unsigned i = 0; i < NElts; i++) {
7818 llvm::APInt Elt;
7819 if (BigEndian)
7820 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7821 else
7822 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7823 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7824 }
7825 } else {
7826 return Error(E);
7827 }
7828 return Success(Elts, E);
7829 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007830 default:
Richard Smith11562c52011-10-28 17:51:58 +00007831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007832 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007833}
7834
Richard Smith2d406342011-10-22 21:10:00 +00007835bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007836VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007837 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007838 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007839 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007840
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007841 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007842 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007843
Eli Friedmanb9c71292012-01-03 23:24:20 +00007844 // The number of initializers can be less than the number of
7845 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007846 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007847 // should be initialized with zeroes.
7848 unsigned CountInits = 0, CountElts = 0;
7849 while (CountElts < NumElements) {
7850 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007851 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007852 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007853 APValue v;
7854 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7855 return Error(E);
7856 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007857 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007858 Elements.push_back(v.getVectorElt(j));
7859 CountElts += vlen;
7860 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007861 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007862 if (CountInits < NumInits) {
7863 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007864 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007865 } else // trailing integer zero.
7866 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7867 Elements.push_back(APValue(sInt));
7868 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007869 } else {
7870 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007871 if (CountInits < NumInits) {
7872 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007873 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007874 } else // trailing float zero.
7875 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7876 Elements.push_back(APValue(f));
7877 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007878 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007879 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007880 }
Richard Smith2d406342011-10-22 21:10:00 +00007881 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007882}
7883
Richard Smith2d406342011-10-22 21:10:00 +00007884bool
Richard Smithfddd3842011-12-30 21:15:51 +00007885VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007886 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007887 QualType EltTy = VT->getElementType();
7888 APValue ZeroElement;
7889 if (EltTy->isIntegerType())
7890 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7891 else
7892 ZeroElement =
7893 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007895 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007896 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007897}
7898
Richard Smith2d406342011-10-22 21:10:00 +00007899bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007900 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007901 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007902}
7903
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007904//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007905// Array Evaluation
7906//===----------------------------------------------------------------------===//
7907
7908namespace {
7909 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007910 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007911 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007912 APValue &Result;
7913 public:
7914
Richard Smithd62306a2011-11-10 06:34:14 +00007915 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7916 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007917
7918 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007919 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007920 Result = V;
7921 return true;
7922 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007923
Richard Smithfddd3842011-12-30 21:15:51 +00007924 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007925 const ConstantArrayType *CAT =
7926 Info.Ctx.getAsConstantArrayType(E->getType());
7927 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007928 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007929
7930 Result = APValue(APValue::UninitArray(), 0,
7931 CAT->getSize().getZExtValue());
7932 if (!Result.hasArrayFiller()) return true;
7933
Richard Smithfddd3842011-12-30 21:15:51 +00007934 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007935 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007936 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007937 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007938 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007939 }
7940
Richard Smith52a980a2015-08-28 02:43:42 +00007941 bool VisitCallExpr(const CallExpr *E) {
7942 return handleCallExpr(E, Result, &This);
7943 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007944 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007945 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007946 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007947 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7948 const LValue &Subobject,
7949 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007950 bool VisitStringLiteral(const StringLiteral *E) {
7951 expandStringLiteral(Info, E, Result);
7952 return true;
7953 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007954 };
7955} // end anonymous namespace
7956
Richard Smithd62306a2011-11-10 06:34:14 +00007957static bool EvaluateArray(const Expr *E, const LValue &This,
7958 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007959 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007960 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007961}
7962
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007963// Return true iff the given array filler may depend on the element index.
7964static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7965 // For now, just whitelist non-class value-initialization and initialization
7966 // lists comprised of them.
7967 if (isa<ImplicitValueInitExpr>(FillerExpr))
7968 return false;
7969 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7970 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7971 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7972 return true;
7973 }
7974 return false;
7975 }
7976 return true;
7977}
7978
Richard Smithf3e9e432011-11-07 09:22:26 +00007979bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7980 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7981 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007982 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007983
Richard Smithca2cfbf2011-12-22 01:07:19 +00007984 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7985 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007986 if (E->isStringLiteralInit())
7987 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007988
Richard Smith253c2a32012-01-27 01:14:48 +00007989 bool Success = true;
7990
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007991 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7992 "zero-initialized array shouldn't have any initialized elts");
7993 APValue Filler;
7994 if (Result.isArray() && Result.hasArrayFiller())
7995 Filler = Result.getArrayFiller();
7996
Richard Smith9543c5e2013-04-22 14:44:29 +00007997 unsigned NumEltsToInit = E->getNumInits();
7998 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007999 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008000
8001 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008002 // array element.
8003 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008004 NumEltsToInit = NumElts;
8005
Nicola Zaghen3538b392018-05-15 13:30:56 +00008006 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8007 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008008
Richard Smith9543c5e2013-04-22 14:44:29 +00008009 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008010
8011 // If the array was previously zero-initialized, preserve the
8012 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008013 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008014 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8015 Result.getArrayInitializedElt(I) = Filler;
8016 if (Result.hasArrayFiller())
8017 Result.getArrayFiller() = Filler;
8018 }
8019
Richard Smithd62306a2011-11-10 06:34:14 +00008020 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008021 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008022 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8023 const Expr *Init =
8024 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008025 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008026 Info, Subobject, Init) ||
8027 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008028 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008029 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008030 return false;
8031 Success = false;
8032 }
Richard Smithd62306a2011-11-10 06:34:14 +00008033 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008034
Richard Smith9543c5e2013-04-22 14:44:29 +00008035 if (!Result.hasArrayFiller())
8036 return Success;
8037
8038 // If we get here, we have a trivial filler, which we can just evaluate
8039 // once and splat over the rest of the array elements.
8040 assert(FillerExpr && "no array filler for incomplete init list");
8041 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8042 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008043}
8044
Richard Smith410306b2016-12-12 02:53:20 +00008045bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8046 if (E->getCommonExpr() &&
8047 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8048 Info, E->getCommonExpr()->getSourceExpr()))
8049 return false;
8050
8051 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8052
8053 uint64_t Elements = CAT->getSize().getZExtValue();
8054 Result = APValue(APValue::UninitArray(), Elements, Elements);
8055
8056 LValue Subobject = This;
8057 Subobject.addArray(Info, E, CAT);
8058
8059 bool Success = true;
8060 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8061 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8062 Info, Subobject, E->getSubExpr()) ||
8063 !HandleLValueArrayAdjustment(Info, E, Subobject,
8064 CAT->getElementType(), 1)) {
8065 if (!Info.noteFailure())
8066 return false;
8067 Success = false;
8068 }
8069 }
8070
8071 return Success;
8072}
8073
Richard Smith027bf112011-11-17 22:56:20 +00008074bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008075 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8076}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008077
Richard Smith9543c5e2013-04-22 14:44:29 +00008078bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8079 const LValue &Subobject,
8080 APValue *Value,
8081 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008082 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008083
8084 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8085 unsigned N = CAT->getSize().getZExtValue();
8086
8087 // Preserve the array filler if we had prior zero-initialization.
8088 APValue Filler =
8089 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8090 : APValue();
8091
8092 *Value = APValue(APValue::UninitArray(), N, N);
8093
8094 if (HadZeroInit)
8095 for (unsigned I = 0; I != N; ++I)
8096 Value->getArrayInitializedElt(I) = Filler;
8097
8098 // Initialize the elements.
8099 LValue ArrayElt = Subobject;
8100 ArrayElt.addArray(Info, E, CAT);
8101 for (unsigned I = 0; I != N; ++I)
8102 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8103 CAT->getElementType()) ||
8104 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8105 CAT->getElementType(), 1))
8106 return false;
8107
8108 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008109 }
Richard Smith027bf112011-11-17 22:56:20 +00008110
Richard Smith9543c5e2013-04-22 14:44:29 +00008111 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008112 return Error(E);
8113
Richard Smithb8348f52016-05-12 22:16:28 +00008114 return RecordExprEvaluator(Info, Subobject, *Value)
8115 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008116}
8117
Richard Smithf3e9e432011-11-07 09:22:26 +00008118//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008119// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008120//
8121// As a GNU extension, we support casting pointers to sufficiently-wide integer
8122// types and back in constant folding. Integer values are thus represented
8123// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008124//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008125
8126namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008127class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008128 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008129 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008130public:
Richard Smith2e312c82012-03-03 22:46:17 +00008131 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008132 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008134 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008135 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008136 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008137 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008138 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008139 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008140 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008141 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008142 return true;
8143 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008144 bool Success(const llvm::APSInt &SI, const Expr *E) {
8145 return Success(SI, E, Result);
8146 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008148 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008149 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008150 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008151 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008152 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008153 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008154 Result.getInt().setIsUnsigned(
8155 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008156 return true;
8157 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008158 bool Success(const llvm::APInt &I, const Expr *E) {
8159 return Success(I, E, Result);
8160 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008161
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008162 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008163 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008164 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008165 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008166 return true;
8167 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008168 bool Success(uint64_t Value, const Expr *E) {
8169 return Success(Value, E, Result);
8170 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008171
Ken Dyckdbc01912011-03-11 02:13:43 +00008172 bool Success(CharUnits Size, const Expr *E) {
8173 return Success(Size.getQuantity(), E);
8174 }
8175
Richard Smith2e312c82012-03-03 22:46:17 +00008176 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008177 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008178 Result = V;
8179 return true;
8180 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008181 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008182 }
Mike Stump11289f42009-09-09 15:08:12 +00008183
Richard Smithfddd3842011-12-30 21:15:51 +00008184 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008185
Peter Collingbournee9200682011-05-13 03:29:01 +00008186 //===--------------------------------------------------------------------===//
8187 // Visitor Methods
8188 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008189
Fangrui Song407659a2018-11-30 23:41:18 +00008190 bool VisitConstantExpr(const ConstantExpr *E);
8191
Chris Lattner7174bf32008-07-12 00:38:25 +00008192 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008193 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008194 }
8195 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008196 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008197 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008198
8199 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8200 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008201 if (CheckReferencedDecl(E, E->getDecl()))
8202 return true;
8203
8204 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008205 }
8206 bool VisitMemberExpr(const MemberExpr *E) {
8207 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008208 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008209 return true;
8210 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008211
8212 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008213 }
8214
Peter Collingbournee9200682011-05-13 03:29:01 +00008215 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008216 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008217 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008218 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008219 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008220
Peter Collingbournee9200682011-05-13 03:29:01 +00008221 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008222 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008223
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008224 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008225 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008226 }
Mike Stump11289f42009-09-09 15:08:12 +00008227
Ted Kremeneke65b0862012-03-06 20:05:56 +00008228 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8229 return Success(E->getValue(), E);
8230 }
Richard Smith410306b2016-12-12 02:53:20 +00008231
8232 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8233 if (Info.ArrayInitIndex == uint64_t(-1)) {
8234 // We were asked to evaluate this subexpression independent of the
8235 // enclosing ArrayInitLoopExpr. We can't do that.
8236 Info.FFDiag(E);
8237 return false;
8238 }
8239 return Success(Info.ArrayInitIndex, E);
8240 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008241
Richard Smith4ce706a2011-10-11 21:43:33 +00008242 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008243 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008244 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008245 }
8246
Douglas Gregor29c42f22012-02-24 07:38:34 +00008247 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8248 return Success(E->getValue(), E);
8249 }
8250
John Wiegley6242b6a2011-04-28 00:16:57 +00008251 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8252 return Success(E->getValue(), E);
8253 }
8254
John Wiegleyf9f65842011-04-25 06:54:41 +00008255 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8256 return Success(E->getValue(), E);
8257 }
8258
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008259 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008260 bool VisitUnaryImag(const UnaryOperator *E);
8261
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008262 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008263 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008264 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008265 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008266};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008267
8268class FixedPointExprEvaluator
8269 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8270 APValue &Result;
8271
8272 public:
8273 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8274 : ExprEvaluatorBaseTy(info), Result(result) {}
8275
Leonard Chandb01c3a2018-06-20 17:19:40 +00008276 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008277 return Success(
8278 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008279 }
8280
Leonard Chandb01c3a2018-06-20 17:19:40 +00008281 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008282 return Success(
8283 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008284 }
8285
8286 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008287 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008288 }
8289
Leonard Chand3f3e162019-01-18 21:04:25 +00008290 bool Success(const APFixedPoint &V, const Expr *E) {
8291 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8292 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8293 "Invalid evaluation result.");
8294 Result = APValue(V);
8295 return true;
8296 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008297
8298 //===--------------------------------------------------------------------===//
8299 // Visitor Methods
8300 //===--------------------------------------------------------------------===//
8301
8302 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8303 return Success(E->getValue(), E);
8304 }
8305
Leonard Chand3f3e162019-01-18 21:04:25 +00008306 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008307 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008308 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008309};
Chris Lattner05706e882008-07-11 18:11:29 +00008310} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008311
Richard Smith11562c52011-10-28 17:51:58 +00008312/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8313/// produce either the integer value or a pointer.
8314///
8315/// GCC has a heinous extension which folds casts between pointer types and
8316/// pointer-sized integral types. We support this by allowing the evaluation of
8317/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8318/// Some simple arithmetic on such values is supported (they are treated much
8319/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008320static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008321 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008322 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008323 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008324}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008325
Richard Smithf57d8cb2011-12-09 22:58:01 +00008326static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008327 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008328 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008329 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008330 if (!Val.isInt()) {
8331 // FIXME: It would be better to produce the diagnostic for casting
8332 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008333 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008334 return false;
8335 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008336 Result = Val.getInt();
8337 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008338}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008339
Eric Fiselier708afb52019-05-16 21:04:15 +00008340bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8341 APValue Evaluated = E->EvaluateInContext(
8342 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8343 return Success(Evaluated, E);
8344}
8345
Leonard Chand3f3e162019-01-18 21:04:25 +00008346static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8347 EvalInfo &Info) {
8348 if (E->getType()->isFixedPointType()) {
8349 APValue Val;
8350 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8351 return false;
8352 if (!Val.isFixedPoint())
8353 return false;
8354
8355 Result = Val.getFixedPoint();
8356 return true;
8357 }
8358 return false;
8359}
8360
8361static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8362 EvalInfo &Info) {
8363 if (E->getType()->isIntegerType()) {
8364 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8365 APSInt Val;
8366 if (!EvaluateInteger(E, Val, Info))
8367 return false;
8368 Result = APFixedPoint(Val, FXSema);
8369 return true;
8370 } else if (E->getType()->isFixedPointType()) {
8371 return EvaluateFixedPoint(E, Result, Info);
8372 }
8373 return false;
8374}
8375
Richard Smithf57d8cb2011-12-09 22:58:01 +00008376/// Check whether the given declaration can be directly converted to an integral
8377/// rvalue. If not, no diagnostic is produced; there are other things we can
8378/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008379bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008380 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008381 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008382 // Check for signedness/width mismatches between E type and ECD value.
8383 bool SameSign = (ECD->getInitVal().isSigned()
8384 == E->getType()->isSignedIntegerOrEnumerationType());
8385 bool SameWidth = (ECD->getInitVal().getBitWidth()
8386 == Info.Ctx.getIntWidth(E->getType()));
8387 if (SameSign && SameWidth)
8388 return Success(ECD->getInitVal(), E);
8389 else {
8390 // Get rid of mismatch (otherwise Success assertions will fail)
8391 // by computing a new value matching the type of E.
8392 llvm::APSInt Val = ECD->getInitVal();
8393 if (!SameSign)
8394 Val.setIsSigned(!ECD->getInitVal().isSigned());
8395 if (!SameWidth)
8396 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8397 return Success(Val, E);
8398 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008399 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008400 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008401}
8402
Richard Smith08b682b2018-05-23 21:18:00 +00008403/// Values returned by __builtin_classify_type, chosen to match the values
8404/// produced by GCC's builtin.
8405enum class GCCTypeClass {
8406 None = -1,
8407 Void = 0,
8408 Integer = 1,
8409 // GCC reserves 2 for character types, but instead classifies them as
8410 // integers.
8411 Enum = 3,
8412 Bool = 4,
8413 Pointer = 5,
8414 // GCC reserves 6 for references, but appears to never use it (because
8415 // expressions never have reference type, presumably).
8416 PointerToDataMember = 7,
8417 RealFloat = 8,
8418 Complex = 9,
8419 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8420 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8421 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8422 // uses 12 for that purpose, same as for a class or struct. Maybe it
8423 // internally implements a pointer to member as a struct? Who knows.
8424 PointerToMemberFunction = 12, // Not a bug, see above.
8425 ClassOrStruct = 12,
8426 Union = 13,
8427 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8428 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8429 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8430 // literals.
8431};
8432
Chris Lattner86ee2862008-10-06 06:40:35 +00008433/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8434/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008435static GCCTypeClass
8436EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8437 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008438
Richard Smith08b682b2018-05-23 21:18:00 +00008439 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008440 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8441
8442 switch (CanTy->getTypeClass()) {
8443#define TYPE(ID, BASE)
8444#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8445#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8446#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8447#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008448 case Type::Auto:
8449 case Type::DeducedTemplateSpecialization:
8450 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008451
8452 case Type::Builtin:
8453 switch (BT->getKind()) {
8454#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008455#define SIGNED_TYPE(ID, SINGLETON_ID) \
8456 case BuiltinType::ID: return GCCTypeClass::Integer;
8457#define FLOATING_TYPE(ID, SINGLETON_ID) \
8458 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8459#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8460 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008461#include "clang/AST/BuiltinTypes.def"
8462 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008463 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008464
8465 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008466 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008467
Richard Smith08b682b2018-05-23 21:18:00 +00008468 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008469 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008470 case BuiltinType::WChar_U:
8471 case BuiltinType::Char8:
8472 case BuiltinType::Char16:
8473 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008474 case BuiltinType::UShort:
8475 case BuiltinType::UInt:
8476 case BuiltinType::ULong:
8477 case BuiltinType::ULongLong:
8478 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008479 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008480
Leonard Chanf921d852018-06-04 16:07:52 +00008481 case BuiltinType::UShortAccum:
8482 case BuiltinType::UAccum:
8483 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008484 case BuiltinType::UShortFract:
8485 case BuiltinType::UFract:
8486 case BuiltinType::ULongFract:
8487 case BuiltinType::SatUShortAccum:
8488 case BuiltinType::SatUAccum:
8489 case BuiltinType::SatULongAccum:
8490 case BuiltinType::SatUShortFract:
8491 case BuiltinType::SatUFract:
8492 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008493 return GCCTypeClass::None;
8494
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008495 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008496
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008497 case BuiltinType::ObjCId:
8498 case BuiltinType::ObjCClass:
8499 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008500#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8501 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008502#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008503#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8504 case BuiltinType::Id:
8505#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008506 case BuiltinType::OCLSampler:
8507 case BuiltinType::OCLEvent:
8508 case BuiltinType::OCLClkEvent:
8509 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008510 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00008511 return GCCTypeClass::None;
8512
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008513 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00008514 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008515 };
Richard Smith08b682b2018-05-23 21:18:00 +00008516 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008517
8518 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00008519 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008520
8521 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008522 case Type::ConstantArray:
8523 case Type::VariableArray:
8524 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00008525 case Type::FunctionNoProto:
8526 case Type::FunctionProto:
8527 return GCCTypeClass::Pointer;
8528
8529 case Type::MemberPointer:
8530 return CanTy->isMemberDataPointerType()
8531 ? GCCTypeClass::PointerToDataMember
8532 : GCCTypeClass::PointerToMemberFunction;
8533
8534 case Type::Complex:
8535 return GCCTypeClass::Complex;
8536
8537 case Type::Record:
8538 return CanTy->isUnionType() ? GCCTypeClass::Union
8539 : GCCTypeClass::ClassOrStruct;
8540
8541 case Type::Atomic:
8542 // GCC classifies _Atomic T the same as T.
8543 return EvaluateBuiltinClassifyType(
8544 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008545
8546 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008547 case Type::Vector:
8548 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008549 case Type::ObjCObject:
8550 case Type::ObjCInterface:
8551 case Type::ObjCObjectPointer:
8552 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00008553 // GCC classifies vectors as None. We follow its lead and classify all
8554 // other types that don't fit into the regular classification the same way.
8555 return GCCTypeClass::None;
8556
8557 case Type::LValueReference:
8558 case Type::RValueReference:
8559 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008560 }
8561
Richard Smith08b682b2018-05-23 21:18:00 +00008562 llvm_unreachable("unexpected type class");
8563}
8564
8565/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8566/// as GCC.
8567static GCCTypeClass
8568EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8569 // If no argument was supplied, default to None. This isn't
8570 // ideal, however it is what gcc does.
8571 if (E->getNumArgs() == 0)
8572 return GCCTypeClass::None;
8573
8574 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8575 // being an ICE, but still folds it to a constant using the type of the first
8576 // argument.
8577 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00008578}
8579
Richard Smith5fab0c92011-12-28 19:48:30 +00008580/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00008581/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00008582///
Richard Smith31cfb312019-04-27 02:58:17 +00008583/// A pointer is only "constant" if it is null (or a pointer cast to integer)
8584/// or it points to the first character of a string literal.
8585static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8586 APValue::LValueBase Base = LV.getLValueBase();
8587 if (Base.isNull()) {
8588 // A null base is acceptable.
8589 return true;
8590 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8591 if (!isa<StringLiteral>(E))
8592 return false;
8593 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00008594 } else if (Base.is<TypeInfoLValue>()) {
8595 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8596 // evaluate to true.
8597 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00008598 } else {
8599 // Any other base is not constant enough for GCC.
8600 return false;
8601 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008602}
8603
8604/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8605/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00008606static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00008607 // This evaluation is not permitted to have side-effects, so evaluate it in
8608 // a speculative evaluation context.
8609 SpeculativeEvaluationRAII SpeculativeEval(Info);
8610
Richard Smith31cfb312019-04-27 02:58:17 +00008611 // Constant-folding is always enabled for the operand of __builtin_constant_p
8612 // (even when the enclosing evaluation context otherwise requires a strict
8613 // language-specific constant expression).
8614 FoldConstant Fold(Info, true);
8615
Richard Smith5fab0c92011-12-28 19:48:30 +00008616 QualType ArgType = Arg->getType();
8617
8618 // __builtin_constant_p always has one operand. The rules which gcc follows
8619 // are not precisely documented, but are as follows:
8620 //
8621 // - If the operand is of integral, floating, complex or enumeration type,
8622 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00008623 // - If the operand can be folded to a pointer to the first character
8624 // of a string literal (or such a pointer cast to an integral type)
8625 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00008626 //
8627 // Otherwise, it returns 0.
8628 //
8629 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00008630 // its support for this did not work prior to GCC 9 and is not yet well
8631 // understood.
8632 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8633 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8634 ArgType->isNullPtrType()) {
8635 APValue V;
8636 if (!::EvaluateAsRValue(Info, Arg, V)) {
8637 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00008638 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00008639 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008640
Richard Smith31cfb312019-04-27 02:58:17 +00008641 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00008642 if (V.getKind() == APValue::LValue)
8643 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00008644
8645 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00008646 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00008647 }
8648
8649 // Anything else isn't considered to be sufficiently constant.
8650 return false;
8651}
8652
John McCall95007602010-05-10 23:27:23 +00008653/// Retrieves the "underlying object type" of the given expression,
8654/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00008655static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00008656 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8657 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00008658 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00008659 } else if (const Expr *E = B.get<const Expr*>()) {
8660 if (isa<CompoundLiteralExpr>(E))
8661 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00008662 } else if (B.is<TypeInfoLValue>()) {
8663 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00008664 }
8665
8666 return QualType();
8667}
8668
George Burgess IV3a03fab2015-09-04 21:28:13 +00008669/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00008670/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00008671/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00008672/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8673///
8674/// Always returns an RValue with a pointer representation.
8675static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8676 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8677
8678 auto *NoParens = E->IgnoreParens();
8679 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00008680 if (Cast == nullptr)
8681 return NoParens;
8682
8683 // We only conservatively allow a few kinds of casts, because this code is
8684 // inherently a simple solution that seeks to support the common case.
8685 auto CastKind = Cast->getCastKind();
8686 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8687 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00008688 return NoParens;
8689
8690 auto *SubExpr = Cast->getSubExpr();
8691 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8692 return NoParens;
8693 return ignorePointerCastsAndParens(SubExpr);
8694}
8695
George Burgess IVa51c4072015-10-16 01:49:01 +00008696/// Checks to see if the given LValue's Designator is at the end of the LValue's
8697/// record layout. e.g.
8698/// struct { struct { int a, b; } fst, snd; } obj;
8699/// obj.fst // no
8700/// obj.snd // yes
8701/// obj.fst.a // no
8702/// obj.fst.b // no
8703/// obj.snd.a // no
8704/// obj.snd.b // yes
8705///
8706/// Please note: this function is specialized for how __builtin_object_size
8707/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00008708///
Richard Smith6f4f0f12017-10-20 22:56:25 +00008709/// If this encounters an invalid RecordDecl or otherwise cannot determine the
8710/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00008711static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8712 assert(!LVal.Designator.Invalid);
8713
George Burgess IV4168d752016-06-27 19:40:41 +00008714 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8715 const RecordDecl *Parent = FD->getParent();
8716 Invalid = Parent->isInvalidDecl();
8717 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00008718 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00008719 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00008720 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8721 };
8722
8723 auto &Base = LVal.getLValueBase();
8724 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8725 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008726 bool Invalid;
8727 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8728 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008729 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008730 for (auto *FD : IFD->chain()) {
8731 bool Invalid;
8732 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8733 return Invalid;
8734 }
George Burgess IVa51c4072015-10-16 01:49:01 +00008735 }
8736 }
8737
George Burgess IVe3763372016-12-22 02:50:20 +00008738 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00008739 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00008740 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00008741 // If we don't know the array bound, conservatively assume we're looking at
8742 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00008743 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00008744 if (BaseType->isIncompleteArrayType())
8745 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8746 else
8747 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00008748 }
8749
8750 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8751 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00008752 if (BaseType->isArrayType()) {
8753 // Because __builtin_object_size treats arrays as objects, we can ignore
8754 // the index iff this is the last array in the Designator.
8755 if (I + 1 == E)
8756 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00008757 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00008758 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008759 if (Index + 1 != CAT->getSize())
8760 return false;
8761 BaseType = CAT->getElementType();
8762 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00008763 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008764 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008765 if (Index != 1)
8766 return false;
8767 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00008768 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00008769 bool Invalid;
8770 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8771 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008772 BaseType = FD->getType();
8773 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008774 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008775 return false;
8776 }
8777 }
8778 return true;
8779}
8780
George Burgess IVe3763372016-12-22 02:50:20 +00008781/// Tests to see if the LValue has a user-specified designator (that isn't
8782/// necessarily valid). Note that this always returns 'true' if the LValue has
8783/// an unsized array as its first designator entry, because there's currently no
8784/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008785static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008786 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008787 return false;
8788
George Burgess IVe3763372016-12-22 02:50:20 +00008789 if (!LVal.Designator.Entries.empty())
8790 return LVal.Designator.isMostDerivedAnUnsizedArray();
8791
George Burgess IVa51c4072015-10-16 01:49:01 +00008792 if (!LVal.InvalidBase)
8793 return true;
8794
George Burgess IVe3763372016-12-22 02:50:20 +00008795 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8796 // the LValueBase.
8797 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8798 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008799}
8800
George Burgess IVe3763372016-12-22 02:50:20 +00008801/// Attempts to detect a user writing into a piece of memory that's impossible
8802/// to figure out the size of by just using types.
8803static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8804 const SubobjectDesignator &Designator = LVal.Designator;
8805 // Notes:
8806 // - Users can only write off of the end when we have an invalid base. Invalid
8807 // bases imply we don't know where the memory came from.
8808 // - We used to be a bit more aggressive here; we'd only be conservative if
8809 // the array at the end was flexible, or if it had 0 or 1 elements. This
8810 // broke some common standard library extensions (PR30346), but was
8811 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8812 // with some sort of whitelist. OTOH, it seems that GCC is always
8813 // conservative with the last element in structs (if it's an array), so our
8814 // current behavior is more compatible than a whitelisting approach would
8815 // be.
8816 return LVal.InvalidBase &&
8817 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8818 Designator.MostDerivedIsArrayElement &&
8819 isDesignatorAtObjectEnd(Ctx, LVal);
8820}
8821
8822/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8823/// Fails if the conversion would cause loss of precision.
8824static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8825 CharUnits &Result) {
8826 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8827 if (Int.ugt(CharUnitsMax))
8828 return false;
8829 Result = CharUnits::fromQuantity(Int.getZExtValue());
8830 return true;
8831}
8832
8833/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8834/// determine how many bytes exist from the beginning of the object to either
8835/// the end of the current subobject, or the end of the object itself, depending
8836/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008837///
George Burgess IVe3763372016-12-22 02:50:20 +00008838/// If this returns false, the value of Result is undefined.
8839static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8840 unsigned Type, const LValue &LVal,
8841 CharUnits &EndOffset) {
8842 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008843
George Burgess IV7fb7e362017-01-03 23:35:19 +00008844 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8845 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8846 return false;
8847 return HandleSizeof(Info, ExprLoc, Ty, Result);
8848 };
8849
George Burgess IVe3763372016-12-22 02:50:20 +00008850 // We want to evaluate the size of the entire object. This is a valid fallback
8851 // for when Type=1 and the designator is invalid, because we're asked for an
8852 // upper-bound.
8853 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8854 // Type=3 wants a lower bound, so we can't fall back to this.
8855 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008856 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008857
8858 llvm::APInt APEndOffset;
8859 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8860 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8861 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8862
8863 if (LVal.InvalidBase)
8864 return false;
8865
8866 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008867 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008868 }
8869
George Burgess IVe3763372016-12-22 02:50:20 +00008870 // We want to evaluate the size of a subobject.
8871 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008872
8873 // The following is a moderately common idiom in C:
8874 //
8875 // struct Foo { int a; char c[1]; };
8876 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8877 // strcpy(&F->c[0], Bar);
8878 //
George Burgess IVe3763372016-12-22 02:50:20 +00008879 // In order to not break too much legacy code, we need to support it.
8880 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8881 // If we can resolve this to an alloc_size call, we can hand that back,
8882 // because we know for certain how many bytes there are to write to.
8883 llvm::APInt APEndOffset;
8884 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8885 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8886 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8887
8888 // If we cannot determine the size of the initial allocation, then we can't
8889 // given an accurate upper-bound. However, we are still able to give
8890 // conservative lower-bounds for Type=3.
8891 if (Type == 1)
8892 return false;
8893 }
8894
8895 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008896 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008897 return false;
8898
George Burgess IVe3763372016-12-22 02:50:20 +00008899 // According to the GCC documentation, we want the size of the subobject
8900 // denoted by the pointer. But that's not quite right -- what we actually
8901 // want is the size of the immediately-enclosing array, if there is one.
8902 int64_t ElemsRemaining;
8903 if (Designator.MostDerivedIsArrayElement &&
8904 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8905 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008906 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00008907 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8908 } else {
8909 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8910 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008911
George Burgess IVe3763372016-12-22 02:50:20 +00008912 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8913 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008914}
8915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008916/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008917/// returns true and stores the result in @p Size.
8918///
8919/// If @p WasError is non-null, this will report whether the failure to evaluate
8920/// is to be treated as an Error in IntExprEvaluator.
8921static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8922 EvalInfo &Info, uint64_t &Size) {
8923 // Determine the denoted object.
8924 LValue LVal;
8925 {
8926 // The operand of __builtin_object_size is never evaluated for side-effects.
8927 // If there are any, but we can determine the pointed-to object anyway, then
8928 // ignore the side-effects.
8929 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008930 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008931
8932 if (E->isGLValue()) {
8933 // It's possible for us to be given GLValues if we're called via
8934 // Expr::tryEvaluateObjectSize.
8935 APValue RVal;
8936 if (!EvaluateAsRValue(Info, E, RVal))
8937 return false;
8938 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008939 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8940 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008941 return false;
8942 }
8943
8944 // If we point to before the start of the object, there are no accessible
8945 // bytes.
8946 if (LVal.getLValueOffset().isNegative()) {
8947 Size = 0;
8948 return true;
8949 }
8950
8951 CharUnits EndOffset;
8952 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8953 return false;
8954
8955 // If we've fallen outside of the end offset, just pretend there's nothing to
8956 // write to/read from.
8957 if (EndOffset <= LVal.getLValueOffset())
8958 Size = 0;
8959 else
8960 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8961 return true;
John McCall95007602010-05-10 23:27:23 +00008962}
8963
Fangrui Song407659a2018-11-30 23:41:18 +00008964bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8965 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8966 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8967}
8968
Peter Collingbournee9200682011-05-13 03:29:01 +00008969bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008970 if (unsigned BuiltinOp = E->getBuiltinCallee())
8971 return VisitBuiltinCallExpr(E, BuiltinOp);
8972
8973 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8974}
8975
8976bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8977 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008978 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008979 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008980 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008981
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008982 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008983 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008984 // The type was checked when we built the expression.
8985 unsigned Type =
8986 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8987 assert(Type <= 3 && "unexpected type");
8988
George Burgess IVe3763372016-12-22 02:50:20 +00008989 uint64_t Size;
8990 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8991 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008992
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008993 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008994 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008995
Richard Smith01ade172012-05-23 04:13:20 +00008996 // Expression had no side effects, but we couldn't statically determine the
8997 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008998 switch (Info.EvalMode) {
8999 case EvalInfo::EM_ConstantExpression:
9000 case EvalInfo::EM_PotentialConstantExpression:
9001 case EvalInfo::EM_ConstantFold:
9002 case EvalInfo::EM_EvaluateForOverflow:
9003 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009004 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009005 return Error(E);
9006 case EvalInfo::EM_ConstantExpressionUnevaluated:
9007 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009008 // Reduce it to a constant now.
9009 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009010 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009011
9012 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009013 }
9014
Tim Northover314fbfa2018-11-02 13:14:11 +00009015 case Builtin::BI__builtin_os_log_format_buffer_size: {
9016 analyze_os_log::OSLogBufferLayout Layout;
9017 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9018 return Success(Layout.size().getQuantity(), E);
9019 }
9020
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009021 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009022 case Builtin::BI__builtin_bswap32:
9023 case Builtin::BI__builtin_bswap64: {
9024 APSInt Val;
9025 if (!EvaluateInteger(E->getArg(0), Val, Info))
9026 return false;
9027
9028 return Success(Val.byteSwap(), E);
9029 }
9030
Richard Smith8889a3d2013-06-13 06:26:32 +00009031 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009032 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009033
Craig Topperf95a6d92018-08-08 22:31:12 +00009034 case Builtin::BI__builtin_clrsb:
9035 case Builtin::BI__builtin_clrsbl:
9036 case Builtin::BI__builtin_clrsbll: {
9037 APSInt Val;
9038 if (!EvaluateInteger(E->getArg(0), Val, Info))
9039 return false;
9040
9041 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9042 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009043
Richard Smith80b3c8e2013-06-13 05:04:16 +00009044 case Builtin::BI__builtin_clz:
9045 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009046 case Builtin::BI__builtin_clzll:
9047 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009048 APSInt Val;
9049 if (!EvaluateInteger(E->getArg(0), Val, Info))
9050 return false;
9051 if (!Val)
9052 return Error(E);
9053
9054 return Success(Val.countLeadingZeros(), E);
9055 }
9056
Fangrui Song407659a2018-11-30 23:41:18 +00009057 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009058 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009059 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009060 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009061 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009062 // Outside a constant context, eagerly evaluate to false in the presence
9063 // of side-effects in order to avoid -Wunsequenced false-positives in
9064 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009065 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009066 }
David Blaikie639b3d12019-05-03 18:11:31 +00009067 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9068 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009069 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009070
Eric Fiselieradd16a82019-04-24 02:23:30 +00009071 case Builtin::BI__builtin_is_constant_evaluated:
9072 return Success(Info.InConstantContext, E);
9073
Richard Smith80b3c8e2013-06-13 05:04:16 +00009074 case Builtin::BI__builtin_ctz:
9075 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009076 case Builtin::BI__builtin_ctzll:
9077 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009078 APSInt Val;
9079 if (!EvaluateInteger(E->getArg(0), Val, Info))
9080 return false;
9081 if (!Val)
9082 return Error(E);
9083
9084 return Success(Val.countTrailingZeros(), E);
9085 }
9086
Richard Smith8889a3d2013-06-13 06:26:32 +00009087 case Builtin::BI__builtin_eh_return_data_regno: {
9088 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9089 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9090 return Success(Operand, E);
9091 }
9092
9093 case Builtin::BI__builtin_expect:
9094 return Visit(E->getArg(0));
9095
9096 case Builtin::BI__builtin_ffs:
9097 case Builtin::BI__builtin_ffsl:
9098 case Builtin::BI__builtin_ffsll: {
9099 APSInt Val;
9100 if (!EvaluateInteger(E->getArg(0), Val, Info))
9101 return false;
9102
9103 unsigned N = Val.countTrailingZeros();
9104 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9105 }
9106
9107 case Builtin::BI__builtin_fpclassify: {
9108 APFloat Val(0.0);
9109 if (!EvaluateFloat(E->getArg(5), Val, Info))
9110 return false;
9111 unsigned Arg;
9112 switch (Val.getCategory()) {
9113 case APFloat::fcNaN: Arg = 0; break;
9114 case APFloat::fcInfinity: Arg = 1; break;
9115 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9116 case APFloat::fcZero: Arg = 4; break;
9117 }
9118 return Visit(E->getArg(Arg));
9119 }
9120
9121 case Builtin::BI__builtin_isinf_sign: {
9122 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009123 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009124 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9125 }
9126
Richard Smithea3019d2013-10-15 19:07:14 +00009127 case Builtin::BI__builtin_isinf: {
9128 APFloat Val(0.0);
9129 return EvaluateFloat(E->getArg(0), Val, Info) &&
9130 Success(Val.isInfinity() ? 1 : 0, E);
9131 }
9132
9133 case Builtin::BI__builtin_isfinite: {
9134 APFloat Val(0.0);
9135 return EvaluateFloat(E->getArg(0), Val, Info) &&
9136 Success(Val.isFinite() ? 1 : 0, E);
9137 }
9138
9139 case Builtin::BI__builtin_isnan: {
9140 APFloat Val(0.0);
9141 return EvaluateFloat(E->getArg(0), Val, Info) &&
9142 Success(Val.isNaN() ? 1 : 0, E);
9143 }
9144
9145 case Builtin::BI__builtin_isnormal: {
9146 APFloat Val(0.0);
9147 return EvaluateFloat(E->getArg(0), Val, Info) &&
9148 Success(Val.isNormal() ? 1 : 0, E);
9149 }
9150
Richard Smith8889a3d2013-06-13 06:26:32 +00009151 case Builtin::BI__builtin_parity:
9152 case Builtin::BI__builtin_parityl:
9153 case Builtin::BI__builtin_parityll: {
9154 APSInt Val;
9155 if (!EvaluateInteger(E->getArg(0), Val, Info))
9156 return false;
9157
9158 return Success(Val.countPopulation() % 2, E);
9159 }
9160
Richard Smith80b3c8e2013-06-13 05:04:16 +00009161 case Builtin::BI__builtin_popcount:
9162 case Builtin::BI__builtin_popcountl:
9163 case Builtin::BI__builtin_popcountll: {
9164 APSInt Val;
9165 if (!EvaluateInteger(E->getArg(0), Val, Info))
9166 return false;
9167
9168 return Success(Val.countPopulation(), E);
9169 }
9170
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009171 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009172 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009173 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009174 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009175 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009176 << /*isConstexpr*/0 << /*isConstructor*/0
9177 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009178 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009179 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009180 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009181 case Builtin::BI__builtin_strlen:
9182 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009183 // As an extension, we support __builtin_strlen() as a constant expression,
9184 // and support folding strlen() to a constant.
9185 LValue String;
9186 if (!EvaluatePointer(E->getArg(0), String, Info))
9187 return false;
9188
Richard Smith8110c9d2016-11-29 19:45:17 +00009189 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9190
Richard Smithe6c19f22013-11-15 02:10:04 +00009191 // Fast path: if it's a string literal, search the string value.
9192 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9193 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009194 // The string literal may have embedded null characters. Find the first
9195 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009196 StringRef Str = S->getBytes();
9197 int64_t Off = String.Offset.getQuantity();
9198 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009199 S->getCharByteWidth() == 1 &&
9200 // FIXME: Add fast-path for wchar_t too.
9201 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009202 Str = Str.substr(Off);
9203
9204 StringRef::size_type Pos = Str.find(0);
9205 if (Pos != StringRef::npos)
9206 Str = Str.substr(0, Pos);
9207
9208 return Success(Str.size(), E);
9209 }
9210
9211 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009212 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009213
9214 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009215 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9216 APValue Char;
9217 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9218 !Char.isInt())
9219 return false;
9220 if (!Char.getInt())
9221 return Success(Strlen, E);
9222 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9223 return false;
9224 }
9225 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009226
Richard Smithe151bab2016-11-11 23:43:35 +00009227 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009228 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009229 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009230 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009231 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009232 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009233 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009234 // A call to strlen is not a constant expression.
9235 if (Info.getLangOpts().CPlusPlus11)
9236 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9237 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009238 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009239 else
9240 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009241 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009242 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009243 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009244 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009245 case Builtin::BI__builtin_wcsncmp:
9246 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009247 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009248 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009249 LValue String1, String2;
9250 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9251 !EvaluatePointer(E->getArg(1), String2, Info))
9252 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009253
Richard Smithe151bab2016-11-11 23:43:35 +00009254 uint64_t MaxLength = uint64_t(-1);
9255 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009256 BuiltinOp != Builtin::BIwcscmp &&
9257 BuiltinOp != Builtin::BI__builtin_strcmp &&
9258 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009259 APSInt N;
9260 if (!EvaluateInteger(E->getArg(2), N, Info))
9261 return false;
9262 MaxLength = N.getExtValue();
9263 }
Hubert Tong147b7432018-12-12 16:53:43 +00009264
9265 // Empty substrings compare equal by definition.
9266 if (MaxLength == 0u)
9267 return Success(0, E);
9268
9269 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9270 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9271 String1.Designator.Invalid || String2.Designator.Invalid)
9272 return false;
9273
9274 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9275 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9276
9277 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009278 BuiltinOp == Builtin::BIbcmp ||
9279 BuiltinOp == Builtin::BI__builtin_memcmp ||
9280 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009281
9282 assert(IsRawByte ||
9283 (Info.Ctx.hasSameUnqualifiedType(
9284 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9285 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9286
9287 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9288 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9289 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9290 Char1.isInt() && Char2.isInt();
9291 };
9292 const auto &AdvanceElems = [&] {
9293 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9294 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9295 };
9296
9297 if (IsRawByte) {
9298 uint64_t BytesRemaining = MaxLength;
9299 // Pointers to const void may point to objects of incomplete type.
9300 if (CharTy1->isIncompleteType()) {
9301 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9302 return false;
9303 }
9304 if (CharTy2->isIncompleteType()) {
9305 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9306 return false;
9307 }
9308 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9309 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9310 // Give up on comparing between elements with disparate widths.
9311 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9312 return false;
9313 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9314 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9315 "following loop considers at least one element");
9316 while (true) {
9317 APValue Char1, Char2;
9318 if (!ReadCurElems(Char1, Char2))
9319 return false;
9320 // We have compatible in-memory widths, but a possible type and
9321 // (for `bool`) internal representation mismatch.
9322 // Assuming two's complement representation, including 0 for `false` and
9323 // 1 for `true`, we can check an appropriate number of elements for
9324 // equality even if they are not byte-sized.
9325 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9326 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9327 if (Char1InMem.ne(Char2InMem)) {
9328 // If the elements are byte-sized, then we can produce a three-way
9329 // comparison result in a straightforward manner.
9330 if (BytesPerElement == 1u) {
9331 // memcmp always compares unsigned chars.
9332 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9333 }
9334 // The result is byte-order sensitive, and we have multibyte elements.
9335 // FIXME: We can compare the remaining bytes in the correct order.
9336 return false;
9337 }
9338 if (!AdvanceElems())
9339 return false;
9340 if (BytesRemaining <= BytesPerElement)
9341 break;
9342 BytesRemaining -= BytesPerElement;
9343 }
9344 // Enough elements are equal to account for the memcmp limit.
9345 return Success(0, E);
9346 }
9347
Clement Courbet8c3343d2019-02-14 12:00:34 +00009348 bool StopAtNull =
9349 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9350 BuiltinOp != Builtin::BIwmemcmp &&
9351 BuiltinOp != Builtin::BI__builtin_memcmp &&
9352 BuiltinOp != Builtin::BI__builtin_bcmp &&
9353 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009354 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9355 BuiltinOp == Builtin::BIwcsncmp ||
9356 BuiltinOp == Builtin::BIwmemcmp ||
9357 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9358 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9359 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009360
Richard Smithe151bab2016-11-11 23:43:35 +00009361 for (; MaxLength; --MaxLength) {
9362 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009363 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009364 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009365 if (Char1.getInt() != Char2.getInt()) {
9366 if (IsWide) // wmemcmp compares with wchar_t signedness.
9367 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9368 // memcmp always compares unsigned chars.
9369 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9370 }
Richard Smithe151bab2016-11-11 23:43:35 +00009371 if (StopAtNull && !Char1.getInt())
9372 return Success(0, E);
9373 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009374 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009375 return false;
9376 }
9377 // We hit the strncmp / memcmp limit.
9378 return Success(0, E);
9379 }
9380
Richard Smith01ba47d2012-04-13 00:45:38 +00009381 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009382 case Builtin::BI__atomic_is_lock_free:
9383 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009384 APSInt SizeVal;
9385 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9386 return false;
9387
9388 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9389 // of two less than the maximum inline atomic width, we know it is
9390 // lock-free. If the size isn't a power of two, or greater than the
9391 // maximum alignment where we promote atomics, we know it is not lock-free
9392 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9393 // the answer can only be determined at runtime; for example, 16-byte
9394 // atomics have lock-free implementations on some, but not all,
9395 // x86-64 processors.
9396
9397 // Check power-of-two.
9398 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009399 if (Size.isPowerOfTwo()) {
9400 // Check against inlining width.
9401 unsigned InlineWidthBits =
9402 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9403 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9404 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9405 Size == CharUnits::One() ||
9406 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9407 Expr::NPC_NeverValueDependent))
9408 // OK, we will inline appropriately-aligned operations of this size,
9409 // and _Atomic(T) is appropriately-aligned.
9410 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009411
Richard Smith01ba47d2012-04-13 00:45:38 +00009412 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9413 castAs<PointerType>()->getPointeeType();
9414 if (!PointeeType->isIncompleteType() &&
9415 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9416 // OK, we will inline operations on this object.
9417 return Success(1, E);
9418 }
9419 }
9420 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009421
Richard Smith01ba47d2012-04-13 00:45:38 +00009422 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9423 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009424 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009425 case Builtin::BIomp_is_initial_device:
9426 // We can decide statically which value the runtime would return if called.
9427 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009428 case Builtin::BI__builtin_add_overflow:
9429 case Builtin::BI__builtin_sub_overflow:
9430 case Builtin::BI__builtin_mul_overflow:
9431 case Builtin::BI__builtin_sadd_overflow:
9432 case Builtin::BI__builtin_uadd_overflow:
9433 case Builtin::BI__builtin_uaddl_overflow:
9434 case Builtin::BI__builtin_uaddll_overflow:
9435 case Builtin::BI__builtin_usub_overflow:
9436 case Builtin::BI__builtin_usubl_overflow:
9437 case Builtin::BI__builtin_usubll_overflow:
9438 case Builtin::BI__builtin_umul_overflow:
9439 case Builtin::BI__builtin_umull_overflow:
9440 case Builtin::BI__builtin_umulll_overflow:
9441 case Builtin::BI__builtin_saddl_overflow:
9442 case Builtin::BI__builtin_saddll_overflow:
9443 case Builtin::BI__builtin_ssub_overflow:
9444 case Builtin::BI__builtin_ssubl_overflow:
9445 case Builtin::BI__builtin_ssubll_overflow:
9446 case Builtin::BI__builtin_smul_overflow:
9447 case Builtin::BI__builtin_smull_overflow:
9448 case Builtin::BI__builtin_smulll_overflow: {
9449 LValue ResultLValue;
9450 APSInt LHS, RHS;
9451
9452 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9453 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9454 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9455 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9456 return false;
9457
9458 APSInt Result;
9459 bool DidOverflow = false;
9460
9461 // If the types don't have to match, enlarge all 3 to the largest of them.
9462 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9463 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9464 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9465 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9466 ResultType->isSignedIntegerOrEnumerationType();
9467 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9468 ResultType->isSignedIntegerOrEnumerationType();
9469 uint64_t LHSSize = LHS.getBitWidth();
9470 uint64_t RHSSize = RHS.getBitWidth();
9471 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9472 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9473
9474 // Add an additional bit if the signedness isn't uniformly agreed to. We
9475 // could do this ONLY if there is a signed and an unsigned that both have
9476 // MaxBits, but the code to check that is pretty nasty. The issue will be
9477 // caught in the shrink-to-result later anyway.
9478 if (IsSigned && !AllSigned)
9479 ++MaxBits;
9480
Erich Keanefc3dfd32019-05-30 21:35:32 +00009481 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9482 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009483 Result = APSInt(MaxBits, !IsSigned);
9484 }
9485
9486 // Find largest int.
9487 switch (BuiltinOp) {
9488 default:
9489 llvm_unreachable("Invalid value for BuiltinOp");
9490 case Builtin::BI__builtin_add_overflow:
9491 case Builtin::BI__builtin_sadd_overflow:
9492 case Builtin::BI__builtin_saddl_overflow:
9493 case Builtin::BI__builtin_saddll_overflow:
9494 case Builtin::BI__builtin_uadd_overflow:
9495 case Builtin::BI__builtin_uaddl_overflow:
9496 case Builtin::BI__builtin_uaddll_overflow:
9497 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9498 : LHS.uadd_ov(RHS, DidOverflow);
9499 break;
9500 case Builtin::BI__builtin_sub_overflow:
9501 case Builtin::BI__builtin_ssub_overflow:
9502 case Builtin::BI__builtin_ssubl_overflow:
9503 case Builtin::BI__builtin_ssubll_overflow:
9504 case Builtin::BI__builtin_usub_overflow:
9505 case Builtin::BI__builtin_usubl_overflow:
9506 case Builtin::BI__builtin_usubll_overflow:
9507 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9508 : LHS.usub_ov(RHS, DidOverflow);
9509 break;
9510 case Builtin::BI__builtin_mul_overflow:
9511 case Builtin::BI__builtin_smul_overflow:
9512 case Builtin::BI__builtin_smull_overflow:
9513 case Builtin::BI__builtin_smulll_overflow:
9514 case Builtin::BI__builtin_umul_overflow:
9515 case Builtin::BI__builtin_umull_overflow:
9516 case Builtin::BI__builtin_umulll_overflow:
9517 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9518 : LHS.umul_ov(RHS, DidOverflow);
9519 break;
9520 }
9521
9522 // In the case where multiple sizes are allowed, truncate and see if
9523 // the values are the same.
9524 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9525 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9526 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9527 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9528 // since it will give us the behavior of a TruncOrSelf in the case where
9529 // its parameter <= its size. We previously set Result to be at least the
9530 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9531 // will work exactly like TruncOrSelf.
9532 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9533 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9534
9535 if (!APSInt::isSameValue(Temp, Result))
9536 DidOverflow = true;
9537 Result = Temp;
9538 }
9539
9540 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00009541 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9542 return false;
Erich Keane00958272018-06-13 20:43:27 +00009543 return Success(DidOverflow, E);
9544 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009545 }
Chris Lattner7174bf32008-07-12 00:38:25 +00009546}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009548/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00009549/// object referred to by the lvalue.
9550static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9551 const LValue &LV) {
9552 // A null pointer can be viewed as being "past the end" but we don't
9553 // choose to look at it that way here.
9554 if (!LV.getLValueBase())
9555 return false;
9556
9557 // If the designator is valid and refers to a subobject, we're not pointing
9558 // past the end.
9559 if (!LV.getLValueDesignator().Invalid &&
9560 !LV.getLValueDesignator().isOnePastTheEnd())
9561 return false;
9562
David Majnemerc378ca52015-08-29 08:32:55 +00009563 // A pointer to an incomplete type might be past-the-end if the type's size is
9564 // zero. We cannot tell because the type is incomplete.
9565 QualType Ty = getType(LV.getLValueBase());
9566 if (Ty->isIncompleteType())
9567 return true;
9568
Richard Smithd20f1e62014-10-21 23:01:04 +00009569 // We're a past-the-end pointer if we point to the byte after the object,
9570 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00009571 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00009572 return LV.getLValueOffset() == Size;
9573}
9574
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009575namespace {
Richard Smith11562c52011-10-28 17:51:58 +00009576
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009577/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009578///
9579/// We use a data recursive algorithm for binary operators so that we are able
9580/// to handle extreme cases of chained binary operators without causing stack
9581/// overflow.
9582class DataRecursiveIntBinOpEvaluator {
9583 struct EvalResult {
9584 APValue Val;
9585 bool Failed;
9586
9587 EvalResult() : Failed(false) { }
9588
9589 void swap(EvalResult &RHS) {
9590 Val.swap(RHS.Val);
9591 Failed = RHS.Failed;
9592 RHS.Failed = false;
9593 }
9594 };
9595
9596 struct Job {
9597 const Expr *E;
9598 EvalResult LHSResult; // meaningful only for binary operator expression.
9599 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00009600
David Blaikie73726062015-08-12 23:09:24 +00009601 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00009602 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00009603
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009604 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00009605 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009606 }
George Burgess IV8c892b52016-05-25 22:31:54 +00009607
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009608 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00009609 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009610 };
9611
9612 SmallVector<Job, 16> Queue;
9613
9614 IntExprEvaluator &IntEval;
9615 EvalInfo &Info;
9616 APValue &FinalResult;
9617
9618public:
9619 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9620 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009622 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009623 /// data recursively.
9624 /// We handle binary operators that are comma, logical, or that have operands
9625 /// with integral or enumeration type.
9626 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009627 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9628 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00009629 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009630 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00009631 }
9632
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009633 bool Traverse(const BinaryOperator *E) {
9634 enqueue(E);
9635 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00009636 while (!Queue.empty())
9637 process(PrevResult);
9638
9639 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009640
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009641 FinalResult.swap(PrevResult.Val);
9642 return true;
9643 }
9644
9645private:
9646 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9647 return IntEval.Success(Value, E, Result);
9648 }
9649 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9650 return IntEval.Success(Value, E, Result);
9651 }
9652 bool Error(const Expr *E) {
9653 return IntEval.Error(E);
9654 }
9655 bool Error(const Expr *E, diag::kind D) {
9656 return IntEval.Error(E, D);
9657 }
9658
9659 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9660 return Info.CCEDiag(E, D);
9661 }
9662
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009663 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009664 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009665 bool &SuppressRHSDiags);
9666
9667 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9668 const BinaryOperator *E, APValue &Result);
9669
9670 void EvaluateExpr(const Expr *E, EvalResult &Result) {
9671 Result.Failed = !Evaluate(Result.Val, Info, E);
9672 if (Result.Failed)
9673 Result.Val = APValue();
9674 }
9675
Richard Trieuba4d0872012-03-21 23:30:30 +00009676 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009677
9678 void enqueue(const Expr *E) {
9679 E = E->IgnoreParens();
9680 Queue.resize(Queue.size()+1);
9681 Queue.back().E = E;
9682 Queue.back().Kind = Job::AnyExprKind;
9683 }
9684};
9685
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009686}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009687
9688bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009689 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009690 bool &SuppressRHSDiags) {
9691 if (E->getOpcode() == BO_Comma) {
9692 // Ignore LHS but note if we could not evaluate it.
9693 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00009694 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009695 return true;
9696 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009697
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009698 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009699 bool LHSAsBool;
9700 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009701 // We were able to evaluate the LHS, see if we can get away with not
9702 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00009703 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9704 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009705 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009706 }
9707 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009708 LHSResult.Failed = true;
9709
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009710 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00009711 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00009712 if (!Info.noteSideEffect())
9713 return false;
9714
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009715 // We can't evaluate the LHS; however, sometimes the result
9716 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9717 // Don't ignore RHS and suppress diagnostics from this arm.
9718 SuppressRHSDiags = true;
9719 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009720
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009721 return true;
9722 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009723
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009724 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9725 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00009726
George Burgess IVa145e252016-05-25 22:38:36 +00009727 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009728 return false; // Ignore RHS;
9729
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009730 return true;
9731}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009732
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00009733static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9734 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00009735 // Compute the new offset in the appropriate width, wrapping at 64 bits.
9736 // FIXME: When compiling for a 32-bit target, we should use 32-bit
9737 // offsets.
9738 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9739 CharUnits &Offset = LVal.getLValueOffset();
9740 uint64_t Offset64 = Offset.getQuantity();
9741 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9742 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9743 : Offset64 + Index64);
9744}
9745
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009746bool DataRecursiveIntBinOpEvaluator::
9747 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9748 const BinaryOperator *E, APValue &Result) {
9749 if (E->getOpcode() == BO_Comma) {
9750 if (RHSResult.Failed)
9751 return false;
9752 Result = RHSResult.Val;
9753 return true;
9754 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009755
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009756 if (E->isLogicalOp()) {
9757 bool lhsResult, rhsResult;
9758 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9759 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00009760
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009761 if (LHSIsOK) {
9762 if (RHSIsOK) {
9763 if (E->getOpcode() == BO_LOr)
9764 return Success(lhsResult || rhsResult, E, Result);
9765 else
9766 return Success(lhsResult && rhsResult, E, Result);
9767 }
9768 } else {
9769 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009770 // We can't evaluate the LHS; however, sometimes the result
9771 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9772 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009773 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009774 }
9775 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009776
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009777 return false;
9778 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009779
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009780 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9781 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009782
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009783 if (LHSResult.Failed || RHSResult.Failed)
9784 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009785
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009786 const APValue &LHSVal = LHSResult.Val;
9787 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009788
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009789 // Handle cases like (unsigned long)&a + 4.
9790 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9791 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009792 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009793 return true;
9794 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009795
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009796 // Handle cases like 4 + (unsigned long)&a
9797 if (E->getOpcode() == BO_Add &&
9798 RHSVal.isLValue() && LHSVal.isInt()) {
9799 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009800 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009801 return true;
9802 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009803
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009804 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9805 // Handle (intptr_t)&&A - (intptr_t)&&B.
9806 if (!LHSVal.getLValueOffset().isZero() ||
9807 !RHSVal.getLValueOffset().isZero())
9808 return false;
9809 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9810 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9811 if (!LHSExpr || !RHSExpr)
9812 return false;
9813 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9814 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9815 if (!LHSAddrExpr || !RHSAddrExpr)
9816 return false;
9817 // Make sure both labels come from the same function.
9818 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9819 RHSAddrExpr->getLabel()->getDeclContext())
9820 return false;
9821 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9822 return true;
9823 }
Richard Smith43e77732013-05-07 04:50:00 +00009824
9825 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009826 if (!LHSVal.isInt() || !RHSVal.isInt())
9827 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009828
9829 // Set up the width and signedness manually, in case it can't be deduced
9830 // from the operation we're performing.
9831 // FIXME: Don't do this in the cases where we can deduce it.
9832 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9833 E->getType()->isUnsignedIntegerOrEnumerationType());
9834 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9835 RHSVal.getInt(), Value))
9836 return false;
9837 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009838}
9839
Richard Trieuba4d0872012-03-21 23:30:30 +00009840void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009841 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009842
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009843 switch (job.Kind) {
9844 case Job::AnyExprKind: {
9845 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9846 if (shouldEnqueue(Bop)) {
9847 job.Kind = Job::BinOpKind;
9848 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009849 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009850 }
9851 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009852
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009853 EvaluateExpr(job.E, Result);
9854 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009855 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009856 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009857
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009858 case Job::BinOpKind: {
9859 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009860 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009861 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009862 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009863 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009864 }
9865 if (SuppressRHSDiags)
9866 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009867 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009868 job.Kind = Job::BinOpVisitedLHSKind;
9869 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009870 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009871 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009872
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009873 case Job::BinOpVisitedLHSKind: {
9874 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9875 EvalResult RHS;
9876 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009877 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009878 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009879 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009880 }
9881 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009882
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009883 llvm_unreachable("Invalid Job::Kind!");
9884}
9885
George Burgess IV8c892b52016-05-25 22:31:54 +00009886namespace {
9887/// Used when we determine that we should fail, but can keep evaluating prior to
9888/// noting that we had a failure.
9889class DelayedNoteFailureRAII {
9890 EvalInfo &Info;
9891 bool NoteFailure;
9892
9893public:
9894 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9895 : Info(Info), NoteFailure(NoteFailure) {}
9896 ~DelayedNoteFailureRAII() {
9897 if (NoteFailure) {
9898 bool ContinueAfterFailure = Info.noteFailure();
9899 (void)ContinueAfterFailure;
9900 assert(ContinueAfterFailure &&
9901 "Shouldn't have kept evaluating on failure.");
9902 }
9903 }
9904};
9905}
9906
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009907template <class SuccessCB, class AfterCB>
9908static bool
9909EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9910 SuccessCB &&Success, AfterCB &&DoAfter) {
9911 assert(E->isComparisonOp() && "expected comparison operator");
9912 assert((E->getOpcode() == BO_Cmp ||
9913 E->getType()->isIntegralOrEnumerationType()) &&
9914 "unsupported binary expression evaluation");
9915 auto Error = [&](const Expr *E) {
9916 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9917 return false;
9918 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009919
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009920 using CCR = ComparisonCategoryResult;
9921 bool IsRelational = E->isRelationalOp();
9922 bool IsEquality = E->isEqualityOp();
9923 if (E->getOpcode() == BO_Cmp) {
9924 const ComparisonCategoryInfo &CmpInfo =
9925 Info.Ctx.CompCategories.getInfoForType(E->getType());
9926 IsRelational = CmpInfo.isOrdered();
9927 IsEquality = CmpInfo.isEquality();
9928 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009929
Anders Carlssonacc79812008-11-16 07:17:21 +00009930 QualType LHSTy = E->getLHS()->getType();
9931 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009932
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009933 if (LHSTy->isIntegralOrEnumerationType() &&
9934 RHSTy->isIntegralOrEnumerationType()) {
9935 APSInt LHS, RHS;
9936 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9937 if (!LHSOK && !Info.noteFailure())
9938 return false;
9939 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9940 return false;
9941 if (LHS < RHS)
9942 return Success(CCR::Less, E);
9943 if (LHS > RHS)
9944 return Success(CCR::Greater, E);
9945 return Success(CCR::Equal, E);
9946 }
9947
Leonard Chance1d4f12019-02-21 20:50:09 +00009948 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9949 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9950 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9951
9952 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9953 if (!LHSOK && !Info.noteFailure())
9954 return false;
9955 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9956 return false;
9957 if (LHSFX < RHSFX)
9958 return Success(CCR::Less, E);
9959 if (LHSFX > RHSFX)
9960 return Success(CCR::Greater, E);
9961 return Success(CCR::Equal, E);
9962 }
9963
Chandler Carruthb29a7432014-10-11 11:03:30 +00009964 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009965 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009966 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009967 if (E->isAssignmentOp()) {
9968 LValue LV;
9969 EvaluateLValue(E->getLHS(), LV, Info);
9970 LHSOK = false;
9971 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009972 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9973 if (LHSOK) {
9974 LHS.makeComplexFloat();
9975 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9976 }
9977 } else {
9978 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9979 }
George Burgess IVa145e252016-05-25 22:38:36 +00009980 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009981 return false;
9982
Chandler Carruthb29a7432014-10-11 11:03:30 +00009983 if (E->getRHS()->getType()->isRealFloatingType()) {
9984 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9985 return false;
9986 RHS.makeComplexFloat();
9987 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9988 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009989 return false;
9990
9991 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009992 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009993 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009994 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009995 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009996 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9997 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009998 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009999 assert(IsEquality && "invalid complex comparison");
10000 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10001 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10002 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010003 }
10004 }
Mike Stump11289f42009-09-09 15:08:12 +000010005
Anders Carlssonacc79812008-11-16 07:17:21 +000010006 if (LHSTy->isRealFloatingType() &&
10007 RHSTy->isRealFloatingType()) {
10008 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010009
Richard Smith253c2a32012-01-27 01:14:48 +000010010 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010011 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010012 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010013
Richard Smith253c2a32012-01-27 01:14:48 +000010014 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010015 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010016
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010017 assert(E->isComparisonOp() && "Invalid binary operator!");
10018 auto GetCmpRes = [&]() {
10019 switch (LHS.compare(RHS)) {
10020 case APFloat::cmpEqual:
10021 return CCR::Equal;
10022 case APFloat::cmpLessThan:
10023 return CCR::Less;
10024 case APFloat::cmpGreaterThan:
10025 return CCR::Greater;
10026 case APFloat::cmpUnordered:
10027 return CCR::Unordered;
10028 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010029 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010030 };
10031 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010032 }
Mike Stump11289f42009-09-09 15:08:12 +000010033
Eli Friedmana38da572009-04-28 19:17:36 +000010034 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010035 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010036
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010037 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10038 if (!LHSOK && !Info.noteFailure())
10039 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010040
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010041 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10042 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010043
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010044 // Reject differing bases from the normal codepath; we special-case
10045 // comparisons to null.
10046 if (!HasSameBase(LHSValue, RHSValue)) {
10047 // Inequalities and subtractions between unrelated pointers have
10048 // unspecified or undefined behavior.
10049 if (!IsEquality)
10050 return Error(E);
10051 // A constant address may compare equal to the address of a symbol.
10052 // The one exception is that address of an object cannot compare equal
10053 // to a null pointer constant.
10054 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10055 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10056 return Error(E);
10057 // It's implementation-defined whether distinct literals will have
10058 // distinct addresses. In clang, the result of such a comparison is
10059 // unspecified, so it is not a constant expression. However, we do know
10060 // that the address of a literal will be non-null.
10061 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10062 LHSValue.Base && RHSValue.Base)
10063 return Error(E);
10064 // We can't tell whether weak symbols will end up pointing to the same
10065 // object.
10066 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10067 return Error(E);
10068 // We can't compare the address of the start of one object with the
10069 // past-the-end address of another object, per C++ DR1652.
10070 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10071 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10072 (RHSValue.Base && RHSValue.Offset.isZero() &&
10073 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10074 return Error(E);
10075 // We can't tell whether an object is at the same address as another
10076 // zero sized object.
10077 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10078 (LHSValue.Base && isZeroSized(RHSValue)))
10079 return Error(E);
10080 return Success(CCR::Nonequal, E);
10081 }
Eli Friedman64004332009-03-23 04:38:34 +000010082
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010083 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10084 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010085
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010086 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10087 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010088
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010089 // C++11 [expr.rel]p3:
10090 // Pointers to void (after pointer conversions) can be compared, with a
10091 // result defined as follows: If both pointers represent the same
10092 // address or are both the null pointer value, the result is true if the
10093 // operator is <= or >= and false otherwise; otherwise the result is
10094 // unspecified.
10095 // We interpret this as applying to pointers to *cv* void.
10096 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10097 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010098
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010099 // C++11 [expr.rel]p2:
10100 // - If two pointers point to non-static data members of the same object,
10101 // or to subobjects or array elements fo such members, recursively, the
10102 // pointer to the later declared member compares greater provided the
10103 // two members have the same access control and provided their class is
10104 // not a union.
10105 // [...]
10106 // - Otherwise pointer comparisons are unspecified.
10107 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10108 bool WasArrayIndex;
10109 unsigned Mismatch = FindDesignatorMismatch(
10110 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10111 // At the point where the designators diverge, the comparison has a
10112 // specified value if:
10113 // - we are comparing array indices
10114 // - we are comparing fields of a union, or fields with the same access
10115 // Otherwise, the result is unspecified and thus the comparison is not a
10116 // constant expression.
10117 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10118 Mismatch < RHSDesignator.Entries.size()) {
10119 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10120 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10121 if (!LF && !RF)
10122 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10123 else if (!LF)
10124 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010125 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10126 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010127 else if (!RF)
10128 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010129 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10130 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010131 else if (!LF->getParent()->isUnion() &&
10132 LF->getAccess() != RF->getAccess())
10133 Info.CCEDiag(E,
10134 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010135 << LF << LF->getAccess() << RF << RF->getAccess()
10136 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010137 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010138 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010139
10140 // The comparison here must be unsigned, and performed with the same
10141 // width as the pointer.
10142 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10143 uint64_t CompareLHS = LHSOffset.getQuantity();
10144 uint64_t CompareRHS = RHSOffset.getQuantity();
10145 assert(PtrSize <= 64 && "Unexpected pointer width");
10146 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10147 CompareLHS &= Mask;
10148 CompareRHS &= Mask;
10149
10150 // If there is a base and this is a relational operator, we can only
10151 // compare pointers within the object in question; otherwise, the result
10152 // depends on where the object is located in memory.
10153 if (!LHSValue.Base.isNull() && IsRelational) {
10154 QualType BaseTy = getType(LHSValue.Base);
10155 if (BaseTy->isIncompleteType())
10156 return Error(E);
10157 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10158 uint64_t OffsetLimit = Size.getQuantity();
10159 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10160 return Error(E);
10161 }
10162
10163 if (CompareLHS < CompareRHS)
10164 return Success(CCR::Less, E);
10165 if (CompareLHS > CompareRHS)
10166 return Success(CCR::Greater, E);
10167 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010168 }
Richard Smith7bb00672012-02-01 01:42:44 +000010169
10170 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010171 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010172 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10173
10174 MemberPtr LHSValue, RHSValue;
10175
10176 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010177 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010178 return false;
10179
10180 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10181 return false;
10182
10183 // C++11 [expr.eq]p2:
10184 // If both operands are null, they compare equal. Otherwise if only one is
10185 // null, they compare unequal.
10186 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10187 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010188 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010189 }
10190
10191 // Otherwise if either is a pointer to a virtual member function, the
10192 // result is unspecified.
10193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10194 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010195 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010196 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10197 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010198 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010199
10200 // Otherwise they compare equal if and only if they would refer to the
10201 // same member of the same most derived object or the same subobject if
10202 // they were dereferenced with a hypothetical object of the associated
10203 // class type.
10204 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010205 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010206 }
10207
Richard Smithab44d9b2012-02-14 22:35:28 +000010208 if (LHSTy->isNullPtrType()) {
10209 assert(E->isComparisonOp() && "unexpected nullptr operation");
10210 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10211 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10212 // are compared, the result is true of the operator is <=, >= or ==, and
10213 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010214 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010215 }
10216
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010217 return DoAfter();
10218}
10219
10220bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10221 if (!CheckLiteralType(Info, E))
10222 return false;
10223
10224 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10225 const BinaryOperator *E) {
10226 // Evaluation succeeded. Lookup the information for the comparison category
10227 // type and fetch the VarDecl for the result.
10228 const ComparisonCategoryInfo &CmpInfo =
10229 Info.Ctx.CompCategories.getInfoForType(E->getType());
10230 const VarDecl *VD =
10231 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10232 // Check and evaluate the result as a constant expression.
10233 LValue LV;
10234 LV.set(VD);
10235 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10236 return false;
10237 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10238 };
10239 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10240 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10241 });
10242}
10243
10244bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10245 // We don't call noteFailure immediately because the assignment happens after
10246 // we evaluate LHS and RHS.
10247 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10248 return Error(E);
10249
10250 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10251 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10252 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10253
10254 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10255 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010256 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010257
10258 if (E->isComparisonOp()) {
10259 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10260 // comparisons and then translating the result.
10261 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10262 const BinaryOperator *E) {
10263 using CCR = ComparisonCategoryResult;
10264 bool IsEqual = ResKind == CCR::Equal,
10265 IsLess = ResKind == CCR::Less,
10266 IsGreater = ResKind == CCR::Greater;
10267 auto Op = E->getOpcode();
10268 switch (Op) {
10269 default:
10270 llvm_unreachable("unsupported binary operator");
10271 case BO_EQ:
10272 case BO_NE:
10273 return Success(IsEqual == (Op == BO_EQ), E);
10274 case BO_LT: return Success(IsLess, E);
10275 case BO_GT: return Success(IsGreater, E);
10276 case BO_LE: return Success(IsEqual || IsLess, E);
10277 case BO_GE: return Success(IsEqual || IsGreater, E);
10278 }
10279 };
10280 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10281 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10282 });
10283 }
10284
10285 QualType LHSTy = E->getLHS()->getType();
10286 QualType RHSTy = E->getRHS()->getType();
10287
10288 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10289 E->getOpcode() == BO_Sub) {
10290 LValue LHSValue, RHSValue;
10291
10292 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10293 if (!LHSOK && !Info.noteFailure())
10294 return false;
10295
10296 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10297 return false;
10298
10299 // Reject differing bases from the normal codepath; we special-case
10300 // comparisons to null.
10301 if (!HasSameBase(LHSValue, RHSValue)) {
10302 // Handle &&A - &&B.
10303 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10304 return Error(E);
10305 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10306 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10307 if (!LHSExpr || !RHSExpr)
10308 return Error(E);
10309 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10310 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10311 if (!LHSAddrExpr || !RHSAddrExpr)
10312 return Error(E);
10313 // Make sure both labels come from the same function.
10314 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10315 RHSAddrExpr->getLabel()->getDeclContext())
10316 return Error(E);
10317 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10318 }
10319 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10320 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10321
10322 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10323 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10324
10325 // C++11 [expr.add]p6:
10326 // Unless both pointers point to elements of the same array object, or
10327 // one past the last element of the array object, the behavior is
10328 // undefined.
10329 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10330 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10331 RHSDesignator))
10332 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10333
10334 QualType Type = E->getLHS()->getType();
10335 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10336
10337 CharUnits ElementSize;
10338 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10339 return false;
10340
10341 // As an extension, a type may have zero size (empty struct or union in
10342 // C, array of zero length). Pointer subtraction in such cases has
10343 // undefined behavior, so is not constant.
10344 if (ElementSize.isZero()) {
10345 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10346 << ElementType;
10347 return false;
10348 }
10349
10350 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10351 // and produce incorrect results when it overflows. Such behavior
10352 // appears to be non-conforming, but is common, so perhaps we should
10353 // assume the standard intended for such cases to be undefined behavior
10354 // and check for them.
10355
10356 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10357 // overflow in the final conversion to ptrdiff_t.
10358 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10359 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10360 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10361 false);
10362 APSInt TrueResult = (LHS - RHS) / ElemSize;
10363 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10364
10365 if (Result.extend(65) != TrueResult &&
10366 !HandleOverflow(Info, E, TrueResult, E->getType()))
10367 return false;
10368 return Success(Result, E);
10369 }
10370
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010371 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010372}
10373
Peter Collingbournee190dee2011-03-11 19:24:49 +000010374/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10375/// a result as the expression's type.
10376bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10377 const UnaryExprOrTypeTraitExpr *E) {
10378 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010379 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010380 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010381 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010382 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10383 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010384 else
Richard Smith6822bd72018-10-26 19:26:45 +000010385 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10386 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010387 }
Eli Friedman64004332009-03-23 04:38:34 +000010388
Peter Collingbournee190dee2011-03-11 19:24:49 +000010389 case UETT_VecStep: {
10390 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010391
Peter Collingbournee190dee2011-03-11 19:24:49 +000010392 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010393 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010394
Peter Collingbournee190dee2011-03-11 19:24:49 +000010395 // The vec_step built-in functions that take a 3-component
10396 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10397 if (n == 3)
10398 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010399
Peter Collingbournee190dee2011-03-11 19:24:49 +000010400 return Success(n, E);
10401 } else
10402 return Success(1, E);
10403 }
10404
10405 case UETT_SizeOf: {
10406 QualType SrcTy = E->getTypeOfArgument();
10407 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10408 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010409 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10410 SrcTy = Ref->getPointeeType();
10411
Richard Smithd62306a2011-11-10 06:34:14 +000010412 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010413 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010414 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010415 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010416 }
Alexey Bataev00396512015-07-02 03:40:19 +000010417 case UETT_OpenMPRequiredSimdAlign:
10418 assert(E->isArgumentType());
10419 return Success(
10420 Info.Ctx.toCharUnitsFromBits(
10421 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10422 .getQuantity(),
10423 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010424 }
10425
10426 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010427}
10428
Peter Collingbournee9200682011-05-13 03:29:01 +000010429bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010430 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010431 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010432 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010433 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010434 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010435 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010436 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010437 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010438 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010439 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010440 APSInt IdxResult;
10441 if (!EvaluateInteger(Idx, IdxResult, Info))
10442 return false;
10443 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10444 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010445 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010446 CurrentType = AT->getElementType();
10447 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10448 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010449 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010450 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010451
James Y Knight7281c352015-12-29 22:31:18 +000010452 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010453 FieldDecl *MemberDecl = ON.getField();
10454 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010455 if (!RT)
10456 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010457 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010458 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010459 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010460 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010461 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010462 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010463 CurrentType = MemberDecl->getType().getNonReferenceType();
10464 break;
10465 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010466
James Y Knight7281c352015-12-29 22:31:18 +000010467 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010468 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010469
James Y Knight7281c352015-12-29 22:31:18 +000010470 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010471 CXXBaseSpecifier *BaseSpec = ON.getBase();
10472 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010473 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010474
10475 // Find the layout of the class whose base we are looking into.
10476 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010477 if (!RT)
10478 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010479 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010480 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010481 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10482
10483 // Find the base class itself.
10484 CurrentType = BaseSpec->getType();
10485 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10486 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010487 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010488
Douglas Gregord1702062010-04-29 00:18:15 +000010489 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010490 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010491 break;
10492 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010493 }
10494 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010495 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010496}
10497
Chris Lattnere13042c2008-07-11 19:10:17 +000010498bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010499 switch (E->getOpcode()) {
10500 default:
10501 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10502 // See C99 6.6p3.
10503 return Error(E);
10504 case UO_Extension:
10505 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10506 // If so, we could clear the diagnostic ID.
10507 return Visit(E->getSubExpr());
10508 case UO_Plus:
10509 // The result is just the value.
10510 return Visit(E->getSubExpr());
10511 case UO_Minus: {
10512 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000010513 return false;
10514 if (!Result.isInt()) return Error(E);
10515 const APSInt &Value = Result.getInt();
10516 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10517 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10518 E->getType()))
10519 return false;
Richard Smithfe800032012-01-31 04:08:20 +000010520 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010521 }
10522 case UO_Not: {
10523 if (!Visit(E->getSubExpr()))
10524 return false;
10525 if (!Result.isInt()) return Error(E);
10526 return Success(~Result.getInt(), E);
10527 }
10528 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000010529 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000010530 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000010531 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000010532 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000010533 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010534 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010535}
Mike Stump11289f42009-09-09 15:08:12 +000010536
Chris Lattner477c4be2008-07-12 01:15:53 +000010537/// HandleCast - This is used to evaluate implicit or explicit casts where the
10538/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000010539bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10540 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010541 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000010542 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010543
Eli Friedmanc757de22011-03-25 00:43:55 +000010544 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000010545 case CK_BaseToDerived:
10546 case CK_DerivedToBase:
10547 case CK_UncheckedDerivedToBase:
10548 case CK_Dynamic:
10549 case CK_ToUnion:
10550 case CK_ArrayToPointerDecay:
10551 case CK_FunctionToPointerDecay:
10552 case CK_NullToPointer:
10553 case CK_NullToMemberPointer:
10554 case CK_BaseToDerivedMemberPointer:
10555 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000010556 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000010557 case CK_ConstructorConversion:
10558 case CK_IntegralToPointer:
10559 case CK_ToVoid:
10560 case CK_VectorSplat:
10561 case CK_IntegralToFloating:
10562 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010563 case CK_CPointerToObjCPointerCast:
10564 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010565 case CK_AnyPointerToBlockPointerCast:
10566 case CK_ObjCObjectLValueCast:
10567 case CK_FloatingRealToComplex:
10568 case CK_FloatingComplexToReal:
10569 case CK_FloatingComplexCast:
10570 case CK_FloatingComplexToIntegralComplex:
10571 case CK_IntegralRealToComplex:
10572 case CK_IntegralComplexCast:
10573 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000010574 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010575 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010576 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010577 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010578 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010579 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010580 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000010581 llvm_unreachable("invalid cast kind for integral value");
10582
Eli Friedman9faf2f92011-03-25 19:07:11 +000010583 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010584 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010585 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000010586 case CK_ARCProduceObject:
10587 case CK_ARCConsumeObject:
10588 case CK_ARCReclaimReturnedObject:
10589 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010590 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010591 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010592
Richard Smith4ef685b2012-01-17 21:17:26 +000010593 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000010594 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010595 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000010596 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010597 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010598
10599 case CK_MemberPointerToBoolean:
10600 case CK_PointerToBoolean:
10601 case CK_IntegralToBoolean:
10602 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010603 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000010604 case CK_FloatingComplexToBoolean:
10605 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010606 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000010607 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000010608 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000010609 uint64_t IntResult = BoolResult;
10610 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10611 IntResult = (uint64_t)-1;
10612 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010613 }
10614
Leonard Chan8f7caae2019-03-06 00:28:43 +000010615 case CK_FixedPointToIntegral: {
10616 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10617 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10618 return false;
10619 bool Overflowed;
10620 llvm::APSInt Result = Src.convertToInt(
10621 Info.Ctx.getIntWidth(DestType),
10622 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10623 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10624 return false;
10625 return Success(Result, E);
10626 }
10627
Leonard Chanb4ba4672018-10-23 17:55:35 +000010628 case CK_FixedPointToBoolean: {
10629 // Unsigned padding does not affect this.
10630 APValue Val;
10631 if (!Evaluate(Val, Info, SubExpr))
10632 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010633 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000010634 }
10635
Eli Friedmanc757de22011-03-25 00:43:55 +000010636 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000010637 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000010638 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000010639
Eli Friedman742421e2009-02-20 01:15:07 +000010640 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000010641 // Allow casts of address-of-label differences if they are no-ops
10642 // or narrowing. (The narrowing case isn't actually guaranteed to
10643 // be constant-evaluatable except in some narrow cases which are hard
10644 // to detect here. We let it through on the assumption the user knows
10645 // what they are doing.)
10646 if (Result.isAddrLabelDiff())
10647 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000010648 // Only allow casts of lvalues if they are lossless.
10649 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10650 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000010651
Richard Smith911e1422012-01-30 22:27:01 +000010652 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10653 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000010654 }
Mike Stump11289f42009-09-09 15:08:12 +000010655
Eli Friedmanc757de22011-03-25 00:43:55 +000010656 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000010657 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10658
John McCall45d55e42010-05-07 21:00:08 +000010659 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000010660 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000010661 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000010662
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010663 if (LV.getLValueBase()) {
10664 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000010665 // FIXME: Allow a larger integer size than the pointer size, and allow
10666 // narrowing back down to pointer width in subsequent integral casts.
10667 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010668 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010669 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010670
Richard Smithcf74da72011-11-16 07:18:12 +000010671 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000010672 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010673 return true;
10674 }
10675
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000010676 APSInt AsInt;
10677 APValue V;
10678 LV.moveInto(V);
10679 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10680 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000010681
Richard Smith911e1422012-01-30 22:27:01 +000010682 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010683 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010684
Eli Friedmanc757de22011-03-25 00:43:55 +000010685 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000010686 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010687 if (!EvaluateComplex(SubExpr, C, Info))
10688 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000010689 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010690 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000010691
Eli Friedmanc757de22011-03-25 00:43:55 +000010692 case CK_FloatingToIntegral: {
10693 APFloat F(0.0);
10694 if (!EvaluateFloat(SubExpr, F, Info))
10695 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000010696
Richard Smith357362d2011-12-13 06:39:58 +000010697 APSInt Value;
10698 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10699 return false;
10700 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010701 }
10702 }
Mike Stump11289f42009-09-09 15:08:12 +000010703
Eli Friedmanc757de22011-03-25 00:43:55 +000010704 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000010705}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010706
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010707bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10708 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010709 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010710 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10711 return false;
10712 if (!LV.isComplexInt())
10713 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010714 return Success(LV.getComplexIntReal(), E);
10715 }
10716
10717 return Visit(E->getSubExpr());
10718}
10719
Eli Friedman4e7a2412009-02-27 04:45:43 +000010720bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010721 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010722 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010723 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10724 return false;
10725 if (!LV.isComplexInt())
10726 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010727 return Success(LV.getComplexIntImag(), E);
10728 }
10729
Richard Smith4a678122011-10-24 18:44:57 +000010730 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000010731 return Success(0, E);
10732}
10733
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010734bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10735 return Success(E->getPackLength(), E);
10736}
10737
Sebastian Redl5f0180d2010-09-10 20:55:47 +000010738bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10739 return Success(E->getValue(), E);
10740}
10741
Leonard Chandb01c3a2018-06-20 17:19:40 +000010742bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10743 switch (E->getOpcode()) {
10744 default:
10745 // Invalid unary operators
10746 return Error(E);
10747 case UO_Plus:
10748 // The result is just the value.
10749 return Visit(E->getSubExpr());
10750 case UO_Minus: {
10751 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010752 if (!Result.isFixedPoint())
10753 return Error(E);
10754 bool Overflowed;
10755 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10756 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10757 return false;
10758 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010759 }
10760 case UO_LNot: {
10761 bool bres;
10762 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10763 return false;
10764 return Success(!bres, E);
10765 }
10766 }
10767}
10768
Leonard Chand3f3e162019-01-18 21:04:25 +000010769bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10770 const Expr *SubExpr = E->getSubExpr();
10771 QualType DestType = E->getType();
10772 assert(DestType->isFixedPointType() &&
10773 "Expected destination type to be a fixed point type");
10774 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10775
10776 switch (E->getCastKind()) {
10777 case CK_FixedPointCast: {
10778 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10779 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10780 return false;
10781 bool Overflowed;
10782 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10783 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10784 return false;
10785 return Success(Result, E);
10786 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010787 case CK_IntegralToFixedPoint: {
10788 APSInt Src;
10789 if (!EvaluateInteger(SubExpr, Src, Info))
10790 return false;
10791
10792 bool Overflowed;
10793 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10794 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10795
10796 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10797 return false;
10798
10799 return Success(IntResult, E);
10800 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010801 case CK_NoOp:
10802 case CK_LValueToRValue:
10803 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10804 default:
10805 return Error(E);
10806 }
10807}
10808
10809bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10810 const Expr *LHS = E->getLHS();
10811 const Expr *RHS = E->getRHS();
10812 FixedPointSemantics ResultFXSema =
10813 Info.Ctx.getFixedPointSemantics(E->getType());
10814
10815 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10816 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10817 return false;
10818 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10819 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10820 return false;
10821
10822 switch (E->getOpcode()) {
10823 case BO_Add: {
10824 bool AddOverflow, ConversionOverflow;
10825 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10826 .convert(ResultFXSema, &ConversionOverflow);
10827 if ((AddOverflow || ConversionOverflow) &&
10828 !HandleOverflow(Info, E, Result, E->getType()))
10829 return false;
10830 return Success(Result, E);
10831 }
10832 default:
10833 return false;
10834 }
10835 llvm_unreachable("Should've exited before this");
10836}
10837
Chris Lattner05706e882008-07-11 18:11:29 +000010838//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010839// Float Evaluation
10840//===----------------------------------------------------------------------===//
10841
10842namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010843class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010844 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010845 APFloat &Result;
10846public:
10847 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010848 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010849
Richard Smith2e312c82012-03-03 22:46:17 +000010850 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010851 Result = V.getFloat();
10852 return true;
10853 }
Eli Friedman24c01542008-08-22 00:06:13 +000010854
Richard Smithfddd3842011-12-30 21:15:51 +000010855 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010856 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10857 return true;
10858 }
10859
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010860 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010861
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010862 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010863 bool VisitBinaryOperator(const BinaryOperator *E);
10864 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010865 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010866
John McCallb1fb0d32010-05-07 22:08:54 +000010867 bool VisitUnaryReal(const UnaryOperator *E);
10868 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010869
Richard Smithfddd3842011-12-30 21:15:51 +000010870 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010871};
10872} // end anonymous namespace
10873
10874static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010875 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010876 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010877}
10878
Jay Foad39c79802011-01-12 09:06:06 +000010879static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010880 QualType ResultTy,
10881 const Expr *Arg,
10882 bool SNaN,
10883 llvm::APFloat &Result) {
10884 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10885 if (!S) return false;
10886
10887 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10888
10889 llvm::APInt fill;
10890
10891 // Treat empty strings as if they were zero.
10892 if (S->getString().empty())
10893 fill = llvm::APInt(32, 0);
10894 else if (S->getString().getAsInteger(0, fill))
10895 return false;
10896
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010897 if (Context.getTargetInfo().isNan2008()) {
10898 if (SNaN)
10899 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10900 else
10901 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10902 } else {
10903 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10904 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10905 // a different encoding to what became a standard in 2008, and for pre-
10906 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10907 // sNaN. This is now known as "legacy NaN" encoding.
10908 if (SNaN)
10909 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10910 else
10911 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10912 }
10913
John McCall16291492010-02-28 13:00:19 +000010914 return true;
10915}
10916
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010917bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010918 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010919 default:
10920 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10921
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010922 case Builtin::BI__builtin_huge_val:
10923 case Builtin::BI__builtin_huge_valf:
10924 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010925 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010926 case Builtin::BI__builtin_inf:
10927 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010928 case Builtin::BI__builtin_infl:
10929 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010930 const llvm::fltSemantics &Sem =
10931 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010932 Result = llvm::APFloat::getInf(Sem);
10933 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010934 }
Mike Stump11289f42009-09-09 15:08:12 +000010935
John McCall16291492010-02-28 13:00:19 +000010936 case Builtin::BI__builtin_nans:
10937 case Builtin::BI__builtin_nansf:
10938 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010939 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010940 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10941 true, Result))
10942 return Error(E);
10943 return true;
John McCall16291492010-02-28 13:00:19 +000010944
Chris Lattner0b7282e2008-10-06 06:31:58 +000010945 case Builtin::BI__builtin_nan:
10946 case Builtin::BI__builtin_nanf:
10947 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010948 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010949 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010950 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010951 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10952 false, Result))
10953 return Error(E);
10954 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010955
10956 case Builtin::BI__builtin_fabs:
10957 case Builtin::BI__builtin_fabsf:
10958 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010959 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010960 if (!EvaluateFloat(E->getArg(0), Result, Info))
10961 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010962
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010963 if (Result.isNegative())
10964 Result.changeSign();
10965 return true;
10966
Richard Smith8889a3d2013-06-13 06:26:32 +000010967 // FIXME: Builtin::BI__builtin_powi
10968 // FIXME: Builtin::BI__builtin_powif
10969 // FIXME: Builtin::BI__builtin_powil
10970
Mike Stump11289f42009-09-09 15:08:12 +000010971 case Builtin::BI__builtin_copysign:
10972 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010973 case Builtin::BI__builtin_copysignl:
10974 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010975 APFloat RHS(0.);
10976 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10977 !EvaluateFloat(E->getArg(1), RHS, Info))
10978 return false;
10979 Result.copySign(RHS);
10980 return true;
10981 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010982 }
10983}
10984
John McCallb1fb0d32010-05-07 22:08:54 +000010985bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010986 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10987 ComplexValue CV;
10988 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10989 return false;
10990 Result = CV.FloatReal;
10991 return true;
10992 }
10993
10994 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010995}
10996
10997bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010998 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10999 ComplexValue CV;
11000 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11001 return false;
11002 Result = CV.FloatImag;
11003 return true;
11004 }
11005
Richard Smith4a678122011-10-24 18:44:57 +000011006 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011007 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11008 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011009 return true;
11010}
11011
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011012bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011013 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011014 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011015 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011016 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011017 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011018 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11019 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011020 Result.changeSign();
11021 return true;
11022 }
11023}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011024
Eli Friedman24c01542008-08-22 00:06:13 +000011025bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011026 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11027 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011028
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011029 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011030 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011031 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011032 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011033 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11034 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011035}
11036
11037bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11038 Result = E->getValue();
11039 return true;
11040}
11041
Peter Collingbournee9200682011-05-13 03:29:01 +000011042bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11043 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011044
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011045 switch (E->getCastKind()) {
11046 default:
Richard Smith11562c52011-10-28 17:51:58 +000011047 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011048
11049 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011050 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011051 return EvaluateInteger(SubExpr, IntResult, Info) &&
11052 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11053 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011054 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011055
11056 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011057 if (!Visit(SubExpr))
11058 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011059 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11060 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011061 }
John McCalld7646252010-11-14 08:17:51 +000011062
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011063 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011064 ComplexValue V;
11065 if (!EvaluateComplex(SubExpr, V, Info))
11066 return false;
11067 Result = V.getComplexFloatReal();
11068 return true;
11069 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011070 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011071}
11072
Eli Friedman24c01542008-08-22 00:06:13 +000011073//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011074// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011075//===----------------------------------------------------------------------===//
11076
11077namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011078class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011079 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011080 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011081
Anders Carlsson537969c2008-11-16 20:27:53 +000011082public:
John McCall93d91dc2010-05-07 17:22:02 +000011083 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011084 : ExprEvaluatorBaseTy(info), Result(Result) {}
11085
Richard Smith2e312c82012-03-03 22:46:17 +000011086 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011087 Result.setFrom(V);
11088 return true;
11089 }
Mike Stump11289f42009-09-09 15:08:12 +000011090
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011091 bool ZeroInitialization(const Expr *E);
11092
Anders Carlsson537969c2008-11-16 20:27:53 +000011093 //===--------------------------------------------------------------------===//
11094 // Visitor Methods
11095 //===--------------------------------------------------------------------===//
11096
Peter Collingbournee9200682011-05-13 03:29:01 +000011097 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011098 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011099 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011100 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011101 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011102};
11103} // end anonymous namespace
11104
John McCall93d91dc2010-05-07 17:22:02 +000011105static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11106 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011107 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011108 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011109}
11110
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011111bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011112 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011113 if (ElemTy->isRealFloatingType()) {
11114 Result.makeComplexFloat();
11115 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11116 Result.FloatReal = Zero;
11117 Result.FloatImag = Zero;
11118 } else {
11119 Result.makeComplexInt();
11120 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11121 Result.IntReal = Zero;
11122 Result.IntImag = Zero;
11123 }
11124 return true;
11125}
11126
Peter Collingbournee9200682011-05-13 03:29:01 +000011127bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11128 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011129
11130 if (SubExpr->getType()->isRealFloatingType()) {
11131 Result.makeComplexFloat();
11132 APFloat &Imag = Result.FloatImag;
11133 if (!EvaluateFloat(SubExpr, Imag, Info))
11134 return false;
11135
11136 Result.FloatReal = APFloat(Imag.getSemantics());
11137 return true;
11138 } else {
11139 assert(SubExpr->getType()->isIntegerType() &&
11140 "Unexpected imaginary literal.");
11141
11142 Result.makeComplexInt();
11143 APSInt &Imag = Result.IntImag;
11144 if (!EvaluateInteger(SubExpr, Imag, Info))
11145 return false;
11146
11147 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11148 return true;
11149 }
11150}
11151
Peter Collingbournee9200682011-05-13 03:29:01 +000011152bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011153
John McCallfcef3cf2010-12-14 17:51:41 +000011154 switch (E->getCastKind()) {
11155 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011156 case CK_BaseToDerived:
11157 case CK_DerivedToBase:
11158 case CK_UncheckedDerivedToBase:
11159 case CK_Dynamic:
11160 case CK_ToUnion:
11161 case CK_ArrayToPointerDecay:
11162 case CK_FunctionToPointerDecay:
11163 case CK_NullToPointer:
11164 case CK_NullToMemberPointer:
11165 case CK_BaseToDerivedMemberPointer:
11166 case CK_DerivedToBaseMemberPointer:
11167 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011168 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011169 case CK_ConstructorConversion:
11170 case CK_IntegralToPointer:
11171 case CK_PointerToIntegral:
11172 case CK_PointerToBoolean:
11173 case CK_ToVoid:
11174 case CK_VectorSplat:
11175 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011176 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011177 case CK_IntegralToBoolean:
11178 case CK_IntegralToFloating:
11179 case CK_FloatingToIntegral:
11180 case CK_FloatingToBoolean:
11181 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011182 case CK_CPointerToObjCPointerCast:
11183 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011184 case CK_AnyPointerToBlockPointerCast:
11185 case CK_ObjCObjectLValueCast:
11186 case CK_FloatingComplexToReal:
11187 case CK_FloatingComplexToBoolean:
11188 case CK_IntegralComplexToReal:
11189 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011190 case CK_ARCProduceObject:
11191 case CK_ARCConsumeObject:
11192 case CK_ARCReclaimReturnedObject:
11193 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011194 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011195 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011196 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011197 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011198 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011199 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011200 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011201 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011202 case CK_FixedPointToIntegral:
11203 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011204 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011205
John McCallfcef3cf2010-12-14 17:51:41 +000011206 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011207 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011208 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000011209 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011210
11211 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011212 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011213 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011214 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011215
11216 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011217 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011218 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011219 return false;
11220
John McCallfcef3cf2010-12-14 17:51:41 +000011221 Result.makeComplexFloat();
11222 Result.FloatImag = APFloat(Real.getSemantics());
11223 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011224 }
11225
John McCallfcef3cf2010-12-14 17:51:41 +000011226 case CK_FloatingComplexCast: {
11227 if (!Visit(E->getSubExpr()))
11228 return false;
11229
11230 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11231 QualType From
11232 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11233
Richard Smith357362d2011-12-13 06:39:58 +000011234 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11235 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011236 }
11237
11238 case CK_FloatingComplexToIntegralComplex: {
11239 if (!Visit(E->getSubExpr()))
11240 return false;
11241
11242 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11243 QualType From
11244 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11245 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011246 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11247 To, Result.IntReal) &&
11248 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11249 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011250 }
11251
11252 case CK_IntegralRealToComplex: {
11253 APSInt &Real = Result.IntReal;
11254 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11255 return false;
11256
11257 Result.makeComplexInt();
11258 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11259 return true;
11260 }
11261
11262 case CK_IntegralComplexCast: {
11263 if (!Visit(E->getSubExpr()))
11264 return false;
11265
11266 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11267 QualType From
11268 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11269
Richard Smith911e1422012-01-30 22:27:01 +000011270 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11271 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011272 return true;
11273 }
11274
11275 case CK_IntegralComplexToFloatingComplex: {
11276 if (!Visit(E->getSubExpr()))
11277 return false;
11278
Ted Kremenek28831752012-08-23 20:46:57 +000011279 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011280 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011281 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011282 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011283 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11284 To, Result.FloatReal) &&
11285 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11286 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011287 }
11288 }
11289
11290 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011291}
11292
John McCall93d91dc2010-05-07 17:22:02 +000011293bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011294 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011295 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11296
Chandler Carrutha216cad2014-10-11 00:57:18 +000011297 // Track whether the LHS or RHS is real at the type system level. When this is
11298 // the case we can simplify our evaluation strategy.
11299 bool LHSReal = false, RHSReal = false;
11300
11301 bool LHSOK;
11302 if (E->getLHS()->getType()->isRealFloatingType()) {
11303 LHSReal = true;
11304 APFloat &Real = Result.FloatReal;
11305 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11306 if (LHSOK) {
11307 Result.makeComplexFloat();
11308 Result.FloatImag = APFloat(Real.getSemantics());
11309 }
11310 } else {
11311 LHSOK = Visit(E->getLHS());
11312 }
George Burgess IVa145e252016-05-25 22:38:36 +000011313 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011314 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011315
John McCall93d91dc2010-05-07 17:22:02 +000011316 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011317 if (E->getRHS()->getType()->isRealFloatingType()) {
11318 RHSReal = true;
11319 APFloat &Real = RHS.FloatReal;
11320 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11321 return false;
11322 RHS.makeComplexFloat();
11323 RHS.FloatImag = APFloat(Real.getSemantics());
11324 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011325 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011326
Chandler Carrutha216cad2014-10-11 00:57:18 +000011327 assert(!(LHSReal && RHSReal) &&
11328 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011329 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011330 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011331 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011332 if (Result.isComplexFloat()) {
11333 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11334 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011335 if (LHSReal)
11336 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11337 else if (!RHSReal)
11338 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11339 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011340 } else {
11341 Result.getComplexIntReal() += RHS.getComplexIntReal();
11342 Result.getComplexIntImag() += RHS.getComplexIntImag();
11343 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011344 break;
John McCalle3027922010-08-25 11:45:40 +000011345 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011346 if (Result.isComplexFloat()) {
11347 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11348 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011349 if (LHSReal) {
11350 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11351 Result.getComplexFloatImag().changeSign();
11352 } else if (!RHSReal) {
11353 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11354 APFloat::rmNearestTiesToEven);
11355 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011356 } else {
11357 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11358 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11359 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011360 break;
John McCalle3027922010-08-25 11:45:40 +000011361 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011362 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011363 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011364 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011365 // following naming scheme:
11366 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011367 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011368 APFloat &A = LHS.getComplexFloatReal();
11369 APFloat &B = LHS.getComplexFloatImag();
11370 APFloat &C = RHS.getComplexFloatReal();
11371 APFloat &D = RHS.getComplexFloatImag();
11372 APFloat &ResR = Result.getComplexFloatReal();
11373 APFloat &ResI = Result.getComplexFloatImag();
11374 if (LHSReal) {
11375 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11376 ResR = A * C;
11377 ResI = A * D;
11378 } else if (RHSReal) {
11379 ResR = C * A;
11380 ResI = C * B;
11381 } else {
11382 // In the fully general case, we need to handle NaNs and infinities
11383 // robustly.
11384 APFloat AC = A * C;
11385 APFloat BD = B * D;
11386 APFloat AD = A * D;
11387 APFloat BC = B * C;
11388 ResR = AC - BD;
11389 ResI = AD + BC;
11390 if (ResR.isNaN() && ResI.isNaN()) {
11391 bool Recalc = false;
11392 if (A.isInfinity() || B.isInfinity()) {
11393 A = APFloat::copySign(
11394 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11395 B = APFloat::copySign(
11396 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11397 if (C.isNaN())
11398 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11399 if (D.isNaN())
11400 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11401 Recalc = true;
11402 }
11403 if (C.isInfinity() || D.isInfinity()) {
11404 C = APFloat::copySign(
11405 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11406 D = APFloat::copySign(
11407 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11408 if (A.isNaN())
11409 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11410 if (B.isNaN())
11411 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11412 Recalc = true;
11413 }
11414 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11415 AD.isInfinity() || BC.isInfinity())) {
11416 if (A.isNaN())
11417 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11418 if (B.isNaN())
11419 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11420 if (C.isNaN())
11421 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11422 if (D.isNaN())
11423 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11424 Recalc = true;
11425 }
11426 if (Recalc) {
11427 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11428 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11429 }
11430 }
11431 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011432 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011433 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011434 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011435 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11436 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011437 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011438 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11439 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11440 }
11441 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011442 case BO_Div:
11443 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011444 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011445 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011446 // following naming scheme:
11447 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011448 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011449 APFloat &A = LHS.getComplexFloatReal();
11450 APFloat &B = LHS.getComplexFloatImag();
11451 APFloat &C = RHS.getComplexFloatReal();
11452 APFloat &D = RHS.getComplexFloatImag();
11453 APFloat &ResR = Result.getComplexFloatReal();
11454 APFloat &ResI = Result.getComplexFloatImag();
11455 if (RHSReal) {
11456 ResR = A / C;
11457 ResI = B / C;
11458 } else {
11459 if (LHSReal) {
11460 // No real optimizations we can do here, stub out with zero.
11461 B = APFloat::getZero(A.getSemantics());
11462 }
11463 int DenomLogB = 0;
11464 APFloat MaxCD = maxnum(abs(C), abs(D));
11465 if (MaxCD.isFinite()) {
11466 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011467 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11468 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011469 }
11470 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011471 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11472 APFloat::rmNearestTiesToEven);
11473 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11474 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011475 if (ResR.isNaN() && ResI.isNaN()) {
11476 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11477 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11478 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11479 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11480 D.isFinite()) {
11481 A = APFloat::copySign(
11482 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11483 B = APFloat::copySign(
11484 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11485 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11486 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11487 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11488 C = APFloat::copySign(
11489 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11490 D = APFloat::copySign(
11491 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11492 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11493 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11494 }
11495 }
11496 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011497 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011498 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11499 return Error(E, diag::note_expr_divide_by_zero);
11500
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011501 ComplexValue LHS = Result;
11502 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11503 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11504 Result.getComplexIntReal() =
11505 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11506 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11507 Result.getComplexIntImag() =
11508 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11509 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11510 }
11511 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011512 }
11513
John McCall93d91dc2010-05-07 17:22:02 +000011514 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011515}
11516
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011517bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11518 // Get the operand value into 'Result'.
11519 if (!Visit(E->getSubExpr()))
11520 return false;
11521
11522 switch (E->getOpcode()) {
11523 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011524 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011525 case UO_Extension:
11526 return true;
11527 case UO_Plus:
11528 // The result is always just the subexpr.
11529 return true;
11530 case UO_Minus:
11531 if (Result.isComplexFloat()) {
11532 Result.getComplexFloatReal().changeSign();
11533 Result.getComplexFloatImag().changeSign();
11534 }
11535 else {
11536 Result.getComplexIntReal() = -Result.getComplexIntReal();
11537 Result.getComplexIntImag() = -Result.getComplexIntImag();
11538 }
11539 return true;
11540 case UO_Not:
11541 if (Result.isComplexFloat())
11542 Result.getComplexFloatImag().changeSign();
11543 else
11544 Result.getComplexIntImag() = -Result.getComplexIntImag();
11545 return true;
11546 }
11547}
11548
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011549bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11550 if (E->getNumInits() == 2) {
11551 if (E->getType()->isComplexType()) {
11552 Result.makeComplexFloat();
11553 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11554 return false;
11555 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11556 return false;
11557 } else {
11558 Result.makeComplexInt();
11559 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11560 return false;
11561 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11562 return false;
11563 }
11564 return true;
11565 }
11566 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11567}
11568
Anders Carlsson537969c2008-11-16 20:27:53 +000011569//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000011570// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11571// implicit conversion.
11572//===----------------------------------------------------------------------===//
11573
11574namespace {
11575class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000011576 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011577 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000011578 APValue &Result;
11579public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011580 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11581 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000011582
11583 bool Success(const APValue &V, const Expr *E) {
11584 Result = V;
11585 return true;
11586 }
11587
11588 bool ZeroInitialization(const Expr *E) {
11589 ImplicitValueInitExpr VIE(
11590 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011591 // For atomic-qualified class (and array) types in C++, initialize the
11592 // _Atomic-wrapped subobject directly, in-place.
11593 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11594 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000011595 }
11596
11597 bool VisitCastExpr(const CastExpr *E) {
11598 switch (E->getCastKind()) {
11599 default:
11600 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11601 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011602 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11603 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000011604 }
11605 }
11606};
11607} // end anonymous namespace
11608
Richard Smith64cb9ca2017-02-22 22:09:50 +000011609static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11610 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000011611 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011612 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000011613}
11614
11615//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000011616// Void expression evaluation, primarily for a cast to void on the LHS of a
11617// comma operator
11618//===----------------------------------------------------------------------===//
11619
11620namespace {
11621class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011622 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000011623public:
11624 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11625
Richard Smith2e312c82012-03-03 22:46:17 +000011626 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000011627
Richard Smith7cd577b2017-08-17 19:35:50 +000011628 bool ZeroInitialization(const Expr *E) { return true; }
11629
Richard Smith42d3af92011-12-07 00:43:50 +000011630 bool VisitCastExpr(const CastExpr *E) {
11631 switch (E->getCastKind()) {
11632 default:
11633 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11634 case CK_ToVoid:
11635 VisitIgnoredValue(E->getSubExpr());
11636 return true;
11637 }
11638 }
Hal Finkela8443c32014-07-17 14:49:58 +000011639
11640 bool VisitCallExpr(const CallExpr *E) {
11641 switch (E->getBuiltinCallee()) {
11642 default:
11643 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11644 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000011645 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000011646 // The argument is not evaluated!
11647 return true;
11648 }
11649 }
Richard Smith42d3af92011-12-07 00:43:50 +000011650};
11651} // end anonymous namespace
11652
11653static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11654 assert(E->isRValue() && E->getType()->isVoidType());
11655 return VoidExprEvaluator(Info).Visit(E);
11656}
11657
11658//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000011659// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000011660//===----------------------------------------------------------------------===//
11661
Richard Smith2e312c82012-03-03 22:46:17 +000011662static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000011663 // In C, function designators are not lvalues, but we evaluate them as if they
11664 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000011665 QualType T = E->getType();
11666 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000011667 LValue LV;
11668 if (!EvaluateLValue(E, LV, Info))
11669 return false;
11670 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011671 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011672 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000011673 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011674 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011675 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011676 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011677 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000011678 LValue LV;
11679 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011680 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011681 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011682 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000011683 llvm::APFloat F(0.0);
11684 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011685 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000011686 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000011687 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000011688 ComplexValue C;
11689 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011690 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011691 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011692 } else if (T->isFixedPointType()) {
11693 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011694 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000011695 MemberPtr P;
11696 if (!EvaluateMemberPointer(E, P, Info))
11697 return false;
11698 P.moveInto(Result);
11699 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000011700 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011701 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011702 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011703 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000011704 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011705 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011706 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011707 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011708 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011709 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000011710 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011711 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011712 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011713 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000011714 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000011715 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000011716 if (!EvaluateVoid(E, Info))
11717 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011718 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011719 QualType Unqual = T.getAtomicUnqualifiedType();
11720 if (Unqual->isArrayType() || Unqual->isRecordType()) {
11721 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011722 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011723 if (!EvaluateAtomic(E, &LV, Value, Info))
11724 return false;
11725 } else {
11726 if (!EvaluateAtomic(E, nullptr, Result, Info))
11727 return false;
11728 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011729 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000011730 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000011731 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011732 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000011733 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000011734 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011735 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011736
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000011737 return true;
11738}
11739
Richard Smithb228a862012-02-15 02:18:13 +000011740/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11741/// cases, the in-place evaluation is essential, since later initializers for
11742/// an object can indirectly refer to subobjects which were initialized earlier.
11743static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000011744 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000011745 assert(!E->isValueDependent());
11746
Richard Smith7525ff62013-05-09 07:14:00 +000011747 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000011748 return false;
11749
11750 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000011751 // Evaluate arrays and record types in-place, so that later initializers can
11752 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000011753 QualType T = E->getType();
11754 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000011755 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011756 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000011757 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011758 else if (T->isAtomicType()) {
11759 QualType Unqual = T.getAtomicUnqualifiedType();
11760 if (Unqual->isArrayType() || Unqual->isRecordType())
11761 return EvaluateAtomic(E, &This, Result, Info);
11762 }
Richard Smithed5165f2011-11-04 05:33:44 +000011763 }
11764
11765 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000011766 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000011767}
11768
Richard Smithf57d8cb2011-12-09 22:58:01 +000011769/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11770/// lvalue-to-rvalue cast if it is an lvalue.
11771static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011772 if (E->getType().isNull())
11773 return false;
11774
Nick Lewyckyc190f962017-05-02 01:06:16 +000011775 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011776 return false;
11777
Richard Smith2e312c82012-03-03 22:46:17 +000011778 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011779 return false;
11780
11781 if (E->isGLValue()) {
11782 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011783 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011784 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011785 return false;
11786 }
11787
Richard Smith2e312c82012-03-03 22:46:17 +000011788 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011789 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011790}
Richard Smith11562c52011-10-28 17:51:58 +000011791
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011792static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011793 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011794 // Fast-path evaluations of integer literals, since we sometimes see files
11795 // containing vast quantities of these.
11796 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11797 Result.Val = APValue(APSInt(L->getValue(),
11798 L->getType()->isUnsignedIntegerType()));
11799 IsConst = true;
11800 return true;
11801 }
James Dennett0492ef02014-03-14 17:44:10 +000011802
11803 // This case should be rare, but we need to check it before we check on
11804 // the type below.
11805 if (Exp->getType().isNull()) {
11806 IsConst = false;
11807 return true;
11808 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011809
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011810 // FIXME: Evaluating values of large array and record types can cause
11811 // performance problems. Only do so in C++11 for now.
11812 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11813 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011814 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011815 IsConst = false;
11816 return true;
11817 }
11818 return false;
11819}
11820
Fangrui Song407659a2018-11-30 23:41:18 +000011821static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11822 Expr::SideEffectsKind SEK) {
11823 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11824 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11825}
11826
11827static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11828 const ASTContext &Ctx, EvalInfo &Info) {
11829 bool IsConst;
11830 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11831 return IsConst;
11832
11833 return EvaluateAsRValue(Info, E, Result.Val);
11834}
11835
11836static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11837 const ASTContext &Ctx,
11838 Expr::SideEffectsKind AllowSideEffects,
11839 EvalInfo &Info) {
11840 if (!E->getType()->isIntegralOrEnumerationType())
11841 return false;
11842
11843 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11844 !ExprResult.Val.isInt() ||
11845 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11846 return false;
11847
11848 return true;
11849}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011850
Leonard Chand3f3e162019-01-18 21:04:25 +000011851static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11852 const ASTContext &Ctx,
11853 Expr::SideEffectsKind AllowSideEffects,
11854 EvalInfo &Info) {
11855 if (!E->getType()->isFixedPointType())
11856 return false;
11857
11858 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11859 return false;
11860
11861 if (!ExprResult.Val.isFixedPoint() ||
11862 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11863 return false;
11864
11865 return true;
11866}
11867
Richard Smith7b553f12011-10-29 00:50:52 +000011868/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011869/// any crazy technique (that has nothing to do with language standards) that
11870/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011871/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11872/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011873bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11874 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011875 assert(!isValueDependent() &&
11876 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000011877 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011878 Info.InConstantContext = InConstantContext;
11879 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011880}
11881
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011882bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
11883 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011884 assert(!isValueDependent() &&
11885 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000011886 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011887 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011888 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011889}
11890
Fangrui Song407659a2018-11-30 23:41:18 +000011891bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011892 SideEffectsKind AllowSideEffects,
11893 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011894 assert(!isValueDependent() &&
11895 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000011896 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011897 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000011898 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011899}
11900
Leonard Chand3f3e162019-01-18 21:04:25 +000011901bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011902 SideEffectsKind AllowSideEffects,
11903 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011904 assert(!isValueDependent() &&
11905 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000011906 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011907 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000011908 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11909}
11910
Richard Trieube234c32016-04-21 21:04:55 +000011911bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011912 SideEffectsKind AllowSideEffects,
11913 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011914 assert(!isValueDependent() &&
11915 "Expression evaluator can't be called on a dependent expression.");
11916
Richard Trieube234c32016-04-21 21:04:55 +000011917 if (!getType()->isRealFloatingType())
11918 return false;
11919
11920 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011921 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
11922 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011923 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011924 return false;
11925
11926 Result = ExprResult.Val.getFloat();
11927 return true;
11928}
11929
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011930bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
11931 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011932 assert(!isValueDependent() &&
11933 "Expression evaluator can't be called on a dependent expression.");
11934
Richard Smith6d4c6582013-11-05 22:18:15 +000011935 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011936 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000011937 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011938 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11939 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011940 Ctx.getLValueReferenceType(getType()), LV,
11941 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011942 return false;
11943
Richard Smith2e312c82012-03-03 22:46:17 +000011944 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011945 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011946}
11947
Reid Kleckner1a840d22018-05-10 18:57:35 +000011948bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11949 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011950 assert(!isValueDependent() &&
11951 "Expression evaluator can't be called on a dependent expression.");
11952
Reid Kleckner1a840d22018-05-10 18:57:35 +000011953 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11954 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011955 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011956
Reid Kleckner1a840d22018-05-10 18:57:35 +000011957 if (!::Evaluate(Result.Val, Info, this))
11958 return false;
11959
11960 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11961 Usage);
11962}
11963
Richard Smithd0b4dd62011-12-19 06:19:21 +000011964bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11965 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011966 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011967 assert(!isValueDependent() &&
11968 "Expression evaluator can't be called on a dependent expression.");
11969
Richard Smithdafff942012-01-14 04:30:29 +000011970 // FIXME: Evaluating initializers for large array and record types can cause
11971 // performance problems. Only do so in C++11 for now.
11972 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011973 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011974 return false;
11975
Richard Smithd0b4dd62011-12-19 06:19:21 +000011976 Expr::EvalStatus EStatus;
11977 EStatus.Diag = &Notes;
11978
Richard Smith0c6124b2015-12-03 01:36:22 +000011979 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11980 ? EvalInfo::EM_ConstantExpression
11981 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011982 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011983 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011984
11985 LValue LVal;
11986 LVal.set(VD);
11987
Richard Smithfddd3842011-12-30 21:15:51 +000011988 // C++11 [basic.start.init]p2:
11989 // Variables with static storage duration or thread storage duration shall be
11990 // zero-initialized before any other initialization takes place.
11991 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011992 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011993 !VD->getType()->isReferenceType()) {
11994 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011995 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011996 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011997 return false;
11998 }
11999
Richard Smith7525ff62013-05-09 07:14:00 +000012000 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12001 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012002 EStatus.HasSideEffects)
12003 return false;
12004
12005 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12006 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012007}
12008
Richard Smith7b553f12011-10-29 00:50:52 +000012009/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12010/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012011bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012012 assert(!isValueDependent() &&
12013 "Expression evaluator can't be called on a dependent expression.");
12014
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012015 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012016 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012017 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012018}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012019
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012020APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012021 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012022 assert(!isValueDependent() &&
12023 "Expression evaluator can't be called on a dependent expression.");
12024
Fangrui Song407659a2018-11-30 23:41:18 +000012025 EvalResult EVResult;
12026 EVResult.Diag = Diag;
12027 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12028 Info.InConstantContext = true;
12029
12030 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012031 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012032 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012033 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012034
Fangrui Song407659a2018-11-30 23:41:18 +000012035 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012036}
John McCall864e3962010-05-07 05:32:02 +000012037
David Bolvansky3b6ae572018-10-18 20:49:06 +000012038APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12039 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012040 assert(!isValueDependent() &&
12041 "Expression evaluator can't be called on a dependent expression.");
12042
Fangrui Song407659a2018-11-30 23:41:18 +000012043 EvalResult EVResult;
12044 EVResult.Diag = Diag;
12045 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12046 Info.InConstantContext = true;
12047
12048 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012049 (void)Result;
12050 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012051 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012052
Fangrui Song407659a2018-11-30 23:41:18 +000012053 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012054}
12055
Richard Smithe9ff7702013-11-05 22:23:30 +000012056void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012057 assert(!isValueDependent() &&
12058 "Expression evaluator can't be called on a dependent expression.");
12059
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012060 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012061 EvalResult EVResult;
12062 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12063 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12064 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012065 }
12066}
12067
Richard Smithe6c01442013-06-05 00:46:14 +000012068bool Expr::EvalResult::isGlobalLValue() const {
12069 assert(Val.isLValue());
12070 return IsGlobalLValue(Val.getLValueBase());
12071}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012072
12073
John McCall864e3962010-05-07 05:32:02 +000012074/// isIntegerConstantExpr - this recursive routine will test if an expression is
12075/// an integer constant expression.
12076
12077/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12078/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012079
12080// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012081// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12082// and a (possibly null) SourceLocation indicating the location of the problem.
12083//
John McCall864e3962010-05-07 05:32:02 +000012084// Note that to reduce code duplication, this helper does no evaluation
12085// itself; the caller checks whether the expression is evaluatable, and
12086// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012087// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012088
Dan Gohman28ade552010-07-26 21:25:24 +000012089namespace {
12090
Richard Smith9e575da2012-12-28 13:25:52 +000012091enum ICEKind {
12092 /// This expression is an ICE.
12093 IK_ICE,
12094 /// This expression is not an ICE, but if it isn't evaluated, it's
12095 /// a legal subexpression for an ICE. This return value is used to handle
12096 /// the comma operator in C99 mode, and non-constant subexpressions.
12097 IK_ICEIfUnevaluated,
12098 /// This expression is not an ICE, and is not a legal subexpression for one.
12099 IK_NotICE
12100};
12101
John McCall864e3962010-05-07 05:32:02 +000012102struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012103 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012104 SourceLocation Loc;
12105
Richard Smith9e575da2012-12-28 13:25:52 +000012106 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012107};
12108
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012109}
Dan Gohman28ade552010-07-26 21:25:24 +000012110
Richard Smith9e575da2012-12-28 13:25:52 +000012111static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12112
12113static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012114
Craig Toppera31a8822013-08-22 07:09:37 +000012115static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012116 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012117 Expr::EvalStatus Status;
12118 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12119
12120 Info.InConstantContext = true;
12121 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012122 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012123 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012124
John McCall864e3962010-05-07 05:32:02 +000012125 return NoDiag();
12126}
12127
Craig Toppera31a8822013-08-22 07:09:37 +000012128static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012129 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012130 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012131 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012132
12133 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012134#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012135#define STMT(Node, Base) case Expr::Node##Class:
12136#define EXPR(Node, Base)
12137#include "clang/AST/StmtNodes.inc"
12138 case Expr::PredefinedExprClass:
12139 case Expr::FloatingLiteralClass:
12140 case Expr::ImaginaryLiteralClass:
12141 case Expr::StringLiteralClass:
12142 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012143 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012144 case Expr::MemberExprClass:
12145 case Expr::CompoundAssignOperatorClass:
12146 case Expr::CompoundLiteralExprClass:
12147 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012148 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012149 case Expr::ArrayInitLoopExprClass:
12150 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012151 case Expr::NoInitExprClass:
12152 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012153 case Expr::ImplicitValueInitExprClass:
12154 case Expr::ParenListExprClass:
12155 case Expr::VAArgExprClass:
12156 case Expr::AddrLabelExprClass:
12157 case Expr::StmtExprClass:
12158 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012159 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012160 case Expr::CXXDynamicCastExprClass:
12161 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012162 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012163 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012164 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012165 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012166 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012167 case Expr::CXXThisExprClass:
12168 case Expr::CXXThrowExprClass:
12169 case Expr::CXXNewExprClass:
12170 case Expr::CXXDeleteExprClass:
12171 case Expr::CXXPseudoDestructorExprClass:
12172 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012173 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012174 case Expr::DependentScopeDeclRefExprClass:
12175 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012176 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012177 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012178 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012179 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012180 case Expr::CXXTemporaryObjectExprClass:
12181 case Expr::CXXUnresolvedConstructExprClass:
12182 case Expr::CXXDependentScopeMemberExprClass:
12183 case Expr::UnresolvedMemberExprClass:
12184 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012185 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012186 case Expr::ObjCArrayLiteralClass:
12187 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012188 case Expr::ObjCEncodeExprClass:
12189 case Expr::ObjCMessageExprClass:
12190 case Expr::ObjCSelectorExprClass:
12191 case Expr::ObjCProtocolExprClass:
12192 case Expr::ObjCIvarRefExprClass:
12193 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012194 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012195 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012196 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012197 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012198 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012199 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012200 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012201 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012202 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012203 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012204 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012205 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012206 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012207 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012208 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012209 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012210 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012211 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012212 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012213 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012214 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012215 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012216
Richard Smithf137f932014-01-25 20:50:08 +000012217 case Expr::InitListExprClass: {
12218 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12219 // form "T x = { a };" is equivalent to "T x = a;".
12220 // Unless we're initializing a reference, T is a scalar as it is known to be
12221 // of integral or enumeration type.
12222 if (E->isRValue())
12223 if (cast<InitListExpr>(E)->getNumInits() == 1)
12224 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012225 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012226 }
12227
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012228 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012229 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012230 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012231 return NoDiag();
12232
John McCall7c454bb2011-07-15 05:09:51 +000012233 case Expr::SubstNonTypeTemplateParmExprClass:
12234 return
12235 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12236
Bill Wendling7c44da22018-10-31 03:48:47 +000012237 case Expr::ConstantExprClass:
12238 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12239
John McCall864e3962010-05-07 05:32:02 +000012240 case Expr::ParenExprClass:
12241 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012242 case Expr::GenericSelectionExprClass:
12243 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012244 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012245 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012246 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012247 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012248 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012249 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012250 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012251 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012252 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012253 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012254 return NoDiag();
12255 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012256 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012257 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12258 // constant expressions, but they can never be ICEs because an ICE cannot
12259 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012260 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012261 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012262 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012263 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012264 }
Richard Smith6365c912012-02-24 22:12:32 +000012265 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012266 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12267 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012268 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012269 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012270 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012271 // Parameter variables are never constants. Without this check,
12272 // getAnyInitializer() can find a default argument, which leads
12273 // to chaos.
12274 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012275 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012276
12277 // C++ 7.1.5.1p2
12278 // A variable of non-volatile const-qualified integral or enumeration
12279 // type initialized by an ICE can be used in ICEs.
12280 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012281 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012282 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012283
Richard Smithd0b4dd62011-12-19 06:19:21 +000012284 const VarDecl *VD;
12285 // Look for a declaration of this variable that has an initializer, and
12286 // check whether it is an ICE.
12287 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12288 return NoDiag();
12289 else
Richard Smith9e575da2012-12-28 13:25:52 +000012290 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012291 }
12292 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012293 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012294 }
John McCall864e3962010-05-07 05:32:02 +000012295 case Expr::UnaryOperatorClass: {
12296 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12297 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012298 case UO_PostInc:
12299 case UO_PostDec:
12300 case UO_PreInc:
12301 case UO_PreDec:
12302 case UO_AddrOf:
12303 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012304 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012305 // C99 6.6/3 allows increment and decrement within unevaluated
12306 // subexpressions of constant expressions, but they can never be ICEs
12307 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012308 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012309 case UO_Extension:
12310 case UO_LNot:
12311 case UO_Plus:
12312 case UO_Minus:
12313 case UO_Not:
12314 case UO_Real:
12315 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012316 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012317 }
Reid Klecknere540d972018-11-01 17:51:48 +000012318 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012319 }
12320 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012321 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12322 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12323 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12324 // compliance: we should warn earlier for offsetof expressions with
12325 // array subscripts that aren't ICEs, and if the array subscripts
12326 // are ICEs, the value of the offsetof must be an integer constant.
12327 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012328 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012329 case Expr::UnaryExprOrTypeTraitExprClass: {
12330 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12331 if ((Exp->getKind() == UETT_SizeOf) &&
12332 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012333 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012334 return NoDiag();
12335 }
12336 case Expr::BinaryOperatorClass: {
12337 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12338 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012339 case BO_PtrMemD:
12340 case BO_PtrMemI:
12341 case BO_Assign:
12342 case BO_MulAssign:
12343 case BO_DivAssign:
12344 case BO_RemAssign:
12345 case BO_AddAssign:
12346 case BO_SubAssign:
12347 case BO_ShlAssign:
12348 case BO_ShrAssign:
12349 case BO_AndAssign:
12350 case BO_XorAssign:
12351 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012352 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12353 // constant expressions, but they can never be ICEs because an ICE cannot
12354 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012355 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012356
John McCalle3027922010-08-25 11:45:40 +000012357 case BO_Mul:
12358 case BO_Div:
12359 case BO_Rem:
12360 case BO_Add:
12361 case BO_Sub:
12362 case BO_Shl:
12363 case BO_Shr:
12364 case BO_LT:
12365 case BO_GT:
12366 case BO_LE:
12367 case BO_GE:
12368 case BO_EQ:
12369 case BO_NE:
12370 case BO_And:
12371 case BO_Xor:
12372 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012373 case BO_Comma:
12374 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012375 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12376 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012377 if (Exp->getOpcode() == BO_Div ||
12378 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012379 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012380 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012381 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012382 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012383 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012384 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012385 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012386 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012387 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012388 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012389 }
12390 }
12391 }
John McCalle3027922010-08-25 11:45:40 +000012392 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012393 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012394 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12395 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012396 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012397 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012398 } else {
12399 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012400 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012401 }
12402 }
Richard Smith9e575da2012-12-28 13:25:52 +000012403 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012404 }
John McCalle3027922010-08-25 11:45:40 +000012405 case BO_LAnd:
12406 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012407 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12408 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012409 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012410 // Rare case where the RHS has a comma "side-effect"; we need
12411 // to actually check the condition to see whether the side
12412 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012413 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012414 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012415 return RHSResult;
12416 return NoDiag();
12417 }
12418
Richard Smith9e575da2012-12-28 13:25:52 +000012419 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012420 }
12421 }
Reid Klecknere540d972018-11-01 17:51:48 +000012422 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012423 }
12424 case Expr::ImplicitCastExprClass:
12425 case Expr::CStyleCastExprClass:
12426 case Expr::CXXFunctionalCastExprClass:
12427 case Expr::CXXStaticCastExprClass:
12428 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012429 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012430 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012431 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012432 if (isa<ExplicitCastExpr>(E)) {
12433 if (const FloatingLiteral *FL
12434 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12435 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12436 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12437 APSInt IgnoredVal(DestWidth, !DestSigned);
12438 bool Ignored;
12439 // If the value does not fit in the destination type, the behavior is
12440 // undefined, so we are not required to treat it as a constant
12441 // expression.
12442 if (FL->getValue().convertToInteger(IgnoredVal,
12443 llvm::APFloat::rmTowardZero,
12444 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012445 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012446 return NoDiag();
12447 }
12448 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012449 switch (cast<CastExpr>(E)->getCastKind()) {
12450 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012451 case CK_AtomicToNonAtomic:
12452 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012453 case CK_NoOp:
12454 case CK_IntegralToBoolean:
12455 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012456 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012457 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012458 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012459 }
John McCall864e3962010-05-07 05:32:02 +000012460 }
John McCallc07a0c72011-02-17 10:25:35 +000012461 case Expr::BinaryConditionalOperatorClass: {
12462 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12463 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012464 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012465 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012466 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12467 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12468 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012469 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012470 return FalseResult;
12471 }
John McCall864e3962010-05-07 05:32:02 +000012472 case Expr::ConditionalOperatorClass: {
12473 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12474 // If the condition (ignoring parens) is a __builtin_constant_p call,
12475 // then only the true side is actually considered in an integer constant
12476 // expression, and it is fully evaluated. This is an important GNU
12477 // extension. See GCC PR38377 for discussion.
12478 if (const CallExpr *CallCE
12479 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012480 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012481 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012482 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012483 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012484 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012485
Richard Smithf57d8cb2011-12-09 22:58:01 +000012486 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12487 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012488
Richard Smith9e575da2012-12-28 13:25:52 +000012489 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012490 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012491 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012492 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012493 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012494 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012495 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012496 return NoDiag();
12497 // Rare case where the diagnostics depend on which side is evaluated
12498 // Note that if we get here, CondResult is 0, and at least one of
12499 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000012500 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000012501 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000012502 return TrueResult;
12503 }
12504 case Expr::CXXDefaultArgExprClass:
12505 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000012506 case Expr::CXXDefaultInitExprClass:
12507 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012508 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000012509 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012510 }
12511 }
12512
David Blaikiee4d798f2012-01-20 21:50:17 +000012513 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000012514}
12515
Richard Smithf57d8cb2011-12-09 22:58:01 +000012516/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000012517static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012518 const Expr *E,
12519 llvm::APSInt *Value,
12520 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000012521 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012522 if (Loc) *Loc = E->getExprLoc();
12523 return false;
12524 }
12525
Richard Smith66e05fe2012-01-18 05:21:49 +000012526 APValue Result;
12527 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000012528 return false;
12529
Richard Smith98710fc2014-11-13 23:03:19 +000012530 if (!Result.isInt()) {
12531 if (Loc) *Loc = E->getExprLoc();
12532 return false;
12533 }
12534
Richard Smith66e05fe2012-01-18 05:21:49 +000012535 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000012536 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012537}
12538
Craig Toppera31a8822013-08-22 07:09:37 +000012539bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12540 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012541 assert(!isValueDependent() &&
12542 "Expression evaluator can't be called on a dependent expression.");
12543
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012544 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000012545 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012546
Richard Smith9e575da2012-12-28 13:25:52 +000012547 ICEDiag D = CheckICE(this, Ctx);
12548 if (D.Kind != IK_ICE) {
12549 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000012550 return false;
12551 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000012552 return true;
12553}
12554
Craig Toppera31a8822013-08-22 07:09:37 +000012555bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012556 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012557 assert(!isValueDependent() &&
12558 "Expression evaluator can't be called on a dependent expression.");
12559
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012560 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000012561 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12562
12563 if (!isIntegerConstantExpr(Ctx, Loc))
12564 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000012565
Richard Smith5c40f092015-12-04 03:00:44 +000012566 // The only possible side-effects here are due to UB discovered in the
12567 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12568 // required to treat the expression as an ICE, so we produce the folded
12569 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000012570 EvalResult ExprResult;
12571 Expr::EvalStatus Status;
12572 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12573 Info.InConstantContext = true;
12574
12575 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000012576 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000012577
12578 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000012579 return true;
12580}
Richard Smith66e05fe2012-01-18 05:21:49 +000012581
Craig Toppera31a8822013-08-22 07:09:37 +000012582bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012583 assert(!isValueDependent() &&
12584 "Expression evaluator can't be called on a dependent expression.");
12585
Richard Smith9e575da2012-12-28 13:25:52 +000012586 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000012587}
12588
Craig Toppera31a8822013-08-22 07:09:37 +000012589bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000012590 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012591 assert(!isValueDependent() &&
12592 "Expression evaluator can't be called on a dependent expression.");
12593
Richard Smith66e05fe2012-01-18 05:21:49 +000012594 // We support this checking in C++98 mode in order to diagnose compatibility
12595 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012596 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000012597
Richard Smith98a0a492012-02-14 21:38:30 +000012598 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000012599 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012600 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000012601 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000012602 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000012603
12604 APValue Scratch;
12605 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12606
12607 if (!Diags.empty()) {
12608 IsConstExpr = false;
12609 if (Loc) *Loc = Diags[0].first;
12610 } else if (!IsConstExpr) {
12611 // FIXME: This shouldn't happen.
12612 if (Loc) *Loc = getExprLoc();
12613 }
12614
12615 return IsConstExpr;
12616}
Richard Smith253c2a32012-01-27 01:14:48 +000012617
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012618bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12619 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000012620 ArrayRef<const Expr*> Args,
12621 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012622 assert(!isValueDependent() &&
12623 "Expression evaluator can't be called on a dependent expression.");
12624
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012625 Expr::EvalStatus Status;
12626 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012627 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012628
George Burgess IV177399e2017-01-09 04:12:14 +000012629 LValue ThisVal;
12630 const LValue *ThisPtr = nullptr;
12631 if (This) {
12632#ifndef NDEBUG
12633 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12634 assert(MD && "Don't provide `this` for non-methods.");
12635 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12636#endif
12637 if (EvaluateObjectArgument(Info, This, ThisVal))
12638 ThisPtr = &ThisVal;
12639 if (Info.EvalStatus.HasSideEffects)
12640 return false;
12641 }
12642
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012643 ArgVector ArgValues(Args.size());
12644 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12645 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000012646 if ((*I)->isValueDependent() ||
12647 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012648 // If evaluation fails, throw away the argument entirely.
12649 ArgValues[I - Args.begin()] = APValue();
12650 if (Info.EvalStatus.HasSideEffects)
12651 return false;
12652 }
12653
12654 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000012655 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012656 ArgValues.data());
12657 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12658}
12659
Richard Smith253c2a32012-01-27 01:14:48 +000012660bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012661 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000012662 PartialDiagnosticAt> &Diags) {
12663 // FIXME: It would be useful to check constexpr function templates, but at the
12664 // moment the constant expression evaluator cannot cope with the non-rigorous
12665 // ASTs which we build for dependent expressions.
12666 if (FD->isDependentContext())
12667 return true;
12668
12669 Expr::EvalStatus Status;
12670 Status.Diag = &Diags;
12671
Richard Smith6d4c6582013-11-05 22:18:15 +000012672 EvalInfo Info(FD->getASTContext(), Status,
12673 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000012674 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000012675
12676 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000012677 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000012678
Richard Smith7525ff62013-05-09 07:14:00 +000012679 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000012680 // is a temporary being used as the 'this' pointer.
12681 LValue This;
12682 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012683 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000012684
Richard Smith253c2a32012-01-27 01:14:48 +000012685 ArrayRef<const Expr*> Args;
12686
Richard Smith2e312c82012-03-03 22:46:17 +000012687 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000012688 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12689 // Evaluate the call as a constant initializer, to allow the construction
12690 // of objects of non-literal types.
12691 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000012692 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12693 } else {
12694 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000012695 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000012696 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000012697 }
Richard Smith253c2a32012-01-27 01:14:48 +000012698
12699 return Diags.empty();
12700}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012701
12702bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12703 const FunctionDecl *FD,
12704 SmallVectorImpl<
12705 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012706 assert(!E->isValueDependent() &&
12707 "Expression evaluator can't be called on a dependent expression.");
12708
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012709 Expr::EvalStatus Status;
12710 Status.Diag = &Diags;
12711
12712 EvalInfo Info(FD->getASTContext(), Status,
12713 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012714 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012715
12716 // Fabricate a call stack frame to give the arguments a plausible cover story.
12717 ArrayRef<const Expr*> Args;
12718 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012719 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012720 (void)Success;
12721 assert(Success &&
12722 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000012723 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012724
12725 APValue ResultScratch;
12726 Evaluate(ResultScratch, Info, E);
12727 return Diags.empty();
12728}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012729
12730bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12731 unsigned Type) const {
12732 if (!getType()->isPointerType())
12733 return false;
12734
12735 Expr::EvalStatus Status;
12736 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000012737 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012738}