blob: b4d02459746715f33df86816bf465f4d4fb490d1 [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"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000050#include "llvm/ADT/Optional.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000051#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000052#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000053#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000054#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000055#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000056
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000057#define DEBUG_TYPE "exprconstant"
58
Anders Carlsson7a241ba2008-07-03 04:20:39 +000059using namespace clang;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000060using llvm::APInt;
Chris Lattner05706e882008-07-11 18:11:29 +000061using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000062using llvm::APFloat;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000063using llvm::Optional;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000064
Richard Smithb228a862012-02-15 02:18:13 +000065static bool IsGlobalLValue(APValue::LValueBase B);
66
John McCall93d91dc2010-05-07 17:22:02 +000067namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000068 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000069 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000070 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000071
Eric Fiselier708afb52019-05-16 21:04:15 +000072 using SourceLocExprScopeGuard =
73 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
74
Richard Smithb228a862012-02-15 02:18:13 +000075 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000076 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000077 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000078 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000079 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000080 //
81 // extern int arr[]; void f() { extern int arr[3]; };
82 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000083 //
84 // For now, we take the array bound from the most recent declaration.
85 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
86 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
87 QualType T = Redecl->getType();
88 if (!T->isIncompleteArrayType())
89 return T;
90 }
91 return D->getType();
92 }
Richard Smith84401042013-06-03 05:03:02 +000093
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000094 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000095 return B.getTypeInfoType();
96
Richard Smith84401042013-06-03 05:03:02 +000097 const Expr *Base = B.get<const Expr*>();
98
99 // For a materialized temporary, the type of the temporary we materialized
100 // may not be the type of the expression.
101 if (const MaterializeTemporaryExpr *MTE =
102 dyn_cast<MaterializeTemporaryExpr>(Base)) {
103 SmallVector<const Expr *, 2> CommaLHSs;
104 SmallVector<SubobjectAdjustment, 2> Adjustments;
105 const Expr *Temp = MTE->GetTemporaryExpr();
106 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
107 Adjustments);
108 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000109 // for it directly. Otherwise use the type after adjustment.
110 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000111 return Inner->getType();
112 }
113
114 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000115 }
116
Richard Smithd62306a2011-11-10 06:34:14 +0000117 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000118 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000120 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Get an LValue path entry, which is known to not be an array index, as a
123 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000125 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127 /// Determine whether this LValue path entry for a base class names a virtual
128 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000129 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000130 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000131 }
132
George Burgess IVe3763372016-12-22 02:50:20 +0000133 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
134 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
135 const FunctionDecl *Callee = CE->getDirectCallee();
136 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
137 }
138
139 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
140 /// This will look through a single cast.
141 ///
142 /// Returns null if we couldn't unwrap a function with alloc_size.
143 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
144 if (!E->getType()->isPointerType())
145 return nullptr;
146
147 E = E->IgnoreParens();
148 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000149 // probably be a cast of some kind. In exotic cases, we might also see a
150 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000151 if (const auto *FE = dyn_cast<FullExpr>(E))
152 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000153
George Burgess IVe3763372016-12-22 02:50:20 +0000154 if (const auto *Cast = dyn_cast<CastExpr>(E))
155 E = Cast->getSubExpr()->IgnoreParens();
156
157 if (const auto *CE = dyn_cast<CallExpr>(E))
158 return getAllocSizeAttr(CE) ? CE : nullptr;
159 return nullptr;
160 }
161
162 /// Determines whether or not the given Base contains a call to a function
163 /// with the alloc_size attribute.
164 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
165 const auto *E = Base.dyn_cast<const Expr *>();
166 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
167 }
168
Richard Smith6f4f0f12017-10-20 22:56:25 +0000169 /// The bound to claim that an array of unknown bound has.
170 /// The value in MostDerivedArraySize is undefined in this case. So, set it
171 /// to an arbitrary value that's likely to loudly break things if it's used.
172 static const uint64_t AssumedSizeForUnsizedArray =
173 std::numeric_limits<uint64_t>::max() / 2;
174
George Burgess IVe3763372016-12-22 02:50:20 +0000175 /// Determines if an LValue with the given LValueBase will have an unsized
176 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000177 /// Find the path length and type of the most-derived subobject in the given
178 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000179 static unsigned
180 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
181 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000182 uint64_t &ArraySize, QualType &Type, bool &IsArray,
183 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000184 // This only accepts LValueBases from APValues, and APValues don't support
185 // arrays that lack size info.
186 assert(!isBaseAnAllocSizeCall(Base) &&
187 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000189 Type = getType(Base);
190
Richard Smith80815602011-11-07 05:07:52 +0000191 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000192 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000193 const ArrayType *AT = Ctx.getAsArrayType(Type);
194 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000195 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000196 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000197
198 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
199 ArraySize = CAT->getSize().getZExtValue();
200 } else {
201 assert(I == 0 && "unexpected unsized array designator");
202 FirstEntryIsUnsizedArray = true;
203 ArraySize = AssumedSizeForUnsizedArray;
204 }
Richard Smith66c96992012-02-18 22:04:06 +0000205 } else if (Type->isAnyComplexType()) {
206 const ComplexType *CT = Type->castAs<ComplexType>();
207 Type = CT->getElementType();
208 ArraySize = 2;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else if (const FieldDecl *FD = getAsField(Path[I])) {
212 Type = FD->getType();
213 ArraySize = 0;
214 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000215 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 } else {
Richard Smith80815602011-11-07 05:07:52 +0000217 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000218 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000219 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 }
Richard Smith80815602011-11-07 05:07:52 +0000221 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000223 }
224
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 // The order of this enum is important for diagnostics.
226 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000227 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smithdebad642019-05-12 09:39:08 +0000228 CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000229 };
230
Richard Smith96e0c102011-11-04 02:25:55 +0000231 /// A path from a glvalue to a subobject of that glvalue.
232 struct SubobjectDesignator {
233 /// True if the subobject was named in a manner not supported by C++11. Such
234 /// lvalues can still be folded, but they are not core constant expressions
235 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Richard Smitha8105bc2012-01-06 16:39:00 +0000238 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000239 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000240
Daniel Jasperffdee092017-05-02 19:21:42 +0000241 /// Indicator of whether the first entry is an unsized array.
242 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000243
George Burgess IVa51c4072015-10-16 01:49:01 +0000244 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000245 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000246
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 /// The length of the path to the most-derived object of which this is a
248 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000249 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000250
George Burgess IVa51c4072015-10-16 01:49:01 +0000251 /// The size of the array of which the most-derived object is an element.
252 /// This will always be 0 if the most-derived object is not an array
253 /// element. 0 is not an indicator of whether or not the most-derived object
254 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000255 ///
256 /// If the current array is an unsized array, the value of this is
257 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000258 uint64_t MostDerivedArraySize;
259
260 /// The type of the most derived object referred to by this address.
261 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000262
Richard Smith80815602011-11-07 05:07:52 +0000263 typedef APValue::LValuePathEntry PathEntry;
264
Richard Smith96e0c102011-11-04 02:25:55 +0000265 /// The entries on the path from the glvalue to the designated subobject.
266 SmallVector<PathEntry, 8> Entries;
267
Richard Smitha8105bc2012-01-06 16:39:00 +0000268 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000269
Richard Smitha8105bc2012-01-06 16:39:00 +0000270 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000271 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000273 MostDerivedPathLength(0), MostDerivedArraySize(0),
274 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000275
276 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000277 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000279 MostDerivedPathLength(0), MostDerivedArraySize(0) {
280 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000281 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000283 ArrayRef<PathEntry> VEntries = V.getLValuePath();
284 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 if (V.getLValueBase()) {
286 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000288 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000290 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000291 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000292 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000293 }
Richard Smith80815602011-11-07 05:07:52 +0000294 }
295 }
296
Richard Smith31c69a32019-05-21 23:15:20 +0000297 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
298 unsigned NewLength) {
299 if (Invalid)
300 return;
301
302 assert(Base && "cannot truncate path for null pointer");
303 assert(NewLength <= Entries.size() && "not a truncation");
304
305 if (NewLength == Entries.size())
306 return;
307 Entries.resize(NewLength);
308
309 bool IsArray = false;
310 bool FirstIsUnsizedArray = false;
311 MostDerivedPathLength = findMostDerivedSubobject(
312 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
313 FirstIsUnsizedArray);
314 MostDerivedIsArrayElement = IsArray;
315 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
316 }
317
Richard Smith96e0c102011-11-04 02:25:55 +0000318 void setInvalid() {
319 Invalid = true;
320 Entries.clear();
321 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000322
George Burgess IVe3763372016-12-22 02:50:20 +0000323 /// Determine whether the most derived subobject is an array without a
324 /// known bound.
325 bool isMostDerivedAnUnsizedArray() const {
326 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000327 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000328 }
329
330 /// Determine what the most derived array's size is. Results in an assertion
331 /// failure if the most derived array lacks a size.
332 uint64_t getMostDerivedArraySize() const {
333 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
334 return MostDerivedArraySize;
335 }
336
Richard Smitha8105bc2012-01-06 16:39:00 +0000337 /// Determine whether this is a one-past-the-end pointer.
338 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000339 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000340 if (IsOnePastTheEnd)
341 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000342 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000343 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
344 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000345 return true;
346 return false;
347 }
348
Richard Smith06f71b52018-08-04 00:57:17 +0000349 /// Get the range of valid index adjustments in the form
350 /// {maximum value that can be subtracted from this pointer,
351 /// maximum value that can be added to this pointer}
352 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
353 if (Invalid || isMostDerivedAnUnsizedArray())
354 return {0, 0};
355
356 // [expr.add]p4: For the purposes of these operators, a pointer to a
357 // nonarray object behaves the same as a pointer to the first element of
358 // an array of length one with the type of the object as its element type.
359 bool IsArray = MostDerivedPathLength == Entries.size() &&
360 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000361 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
362 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000363 uint64_t ArraySize =
364 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
365 return {ArrayIndex, ArraySize - ArrayIndex};
366 }
367
Richard Smitha8105bc2012-01-06 16:39:00 +0000368 /// Check that this refers to a valid subobject.
369 bool isValidSubobject() const {
370 if (Invalid)
371 return false;
372 return !isOnePastTheEnd();
373 }
374 /// Check that this refers to a valid subobject, and if not, produce a
375 /// relevant diagnostic and set the designator as invalid.
376 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
377
Richard Smith06f71b52018-08-04 00:57:17 +0000378 /// Get the type of the designated object.
379 QualType getType(ASTContext &Ctx) const {
380 assert(!Invalid && "invalid designator has no subobject type");
381 return MostDerivedPathLength == Entries.size()
382 ? MostDerivedType
383 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
384 }
385
Richard Smitha8105bc2012-01-06 16:39:00 +0000386 /// Update this designator to refer to the first element within this array.
387 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000388 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000389
390 // This is a most-derived object.
391 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000392 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000393 MostDerivedArraySize = CAT->getSize().getZExtValue();
394 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000395 }
George Burgess IVe3763372016-12-22 02:50:20 +0000396 /// Update this designator to refer to the first element within the array of
397 /// elements of type T. This is an array of unknown size.
398 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000399 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000400
401 MostDerivedType = ElemTy;
402 MostDerivedIsArrayElement = true;
403 // The value in MostDerivedArraySize is undefined in this case. So, set it
404 // to an arbitrary value that's likely to loudly break things if it's
405 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000406 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000407 MostDerivedPathLength = Entries.size();
408 }
Richard Smith96e0c102011-11-04 02:25:55 +0000409 /// Update this designator to refer to the given base or member of this
410 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000411 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000412 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000413
414 // If this isn't a base class, it's a new most-derived object.
415 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
416 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000417 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000418 MostDerivedArraySize = 0;
419 MostDerivedPathLength = Entries.size();
420 }
Richard Smith96e0c102011-11-04 02:25:55 +0000421 }
Richard Smith66c96992012-02-18 22:04:06 +0000422 /// Update this designator to refer to the given complex component.
423 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000424 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000425
426 // This is technically a most-derived object, though in practice this
427 // is unlikely to matter.
428 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000429 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000430 MostDerivedArraySize = 2;
431 MostDerivedPathLength = Entries.size();
432 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000433 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000434 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
435 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000436 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000437 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
438 if (Invalid || !N) return;
439 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
440 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000441 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000442 // Can't verify -- trust that the user is doing the right thing (or if
443 // not, trust that the caller will catch the bad behavior).
444 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000445 Entries.back() = PathEntry::ArrayIndex(
446 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000447 return;
448 }
449
450 // [expr.add]p4: For the purposes of these operators, a pointer to a
451 // nonarray object behaves the same as a pointer to the first element of
452 // an array of length one with the type of the object as its element type.
453 bool IsArray = MostDerivedPathLength == Entries.size() &&
454 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000455 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
456 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000457 uint64_t ArraySize =
458 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
459
460 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
461 // Calculate the actual index in a wide enough type, so we can include
462 // it in the note.
463 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
464 (llvm::APInt&)N += ArrayIndex;
465 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
466 diagnosePointerArithmetic(Info, E, N);
467 setInvalid();
468 return;
469 }
470
471 ArrayIndex += TruncatedN;
472 assert(ArrayIndex <= ArraySize &&
473 "bounds check succeeded for out-of-bounds index");
474
475 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000476 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000477 else
478 IsOnePastTheEnd = (ArrayIndex != 0);
479 }
Richard Smith96e0c102011-11-04 02:25:55 +0000480 };
481
Richard Smith254a73d2011-10-28 22:34:42 +0000482 /// A stack frame in the constexpr call stack.
483 struct CallStackFrame {
484 EvalInfo &Info;
485
486 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000487 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000488
Richard Smithf6f003a2011-12-16 19:06:07 +0000489 /// Callee - The function which was called.
490 const FunctionDecl *Callee;
491
Richard Smithd62306a2011-11-10 06:34:14 +0000492 /// This - The binding for the this pointer in this call, if any.
493 const LValue *This;
494
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000495 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000496 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000497 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000498
Eric Fiselier708afb52019-05-16 21:04:15 +0000499 /// Source location information about the default argument or default
500 /// initializer expression we're evaluating, if any.
501 CurrentSourceLocExprScope CurSourceLocExprScope;
502
Eli Friedman4830ec82012-06-25 21:21:08 +0000503 // Note that we intentionally use std::map here so that references to
504 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000505 typedef std::pair<const void *, unsigned> MapKeyTy;
506 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000507 /// Temporaries - Temporary lvalues materialized within this stack frame.
508 MapTy Temporaries;
509
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000510 /// CallLoc - The location of the call expression for this call.
511 SourceLocation CallLoc;
512
513 /// Index - The call index of this call.
514 unsigned Index;
515
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000516 /// The stack of integers for tracking version numbers for temporaries.
517 SmallVector<unsigned, 2> TempVersionStack = {1};
518 unsigned CurTempVersion = TempVersionStack.back();
519
520 unsigned getTempVersion() const { return TempVersionStack.back(); }
521
522 void pushTempVersion() {
523 TempVersionStack.push_back(++CurTempVersion);
524 }
525
526 void popTempVersion() {
527 TempVersionStack.pop_back();
528 }
529
Faisal Vali051e3a22017-02-16 04:12:21 +0000530 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000531 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000532 // (We should cache this map rather than recomputing it repeatedly.)
533 // But let's try this and see how it goes; we can look into caching the map
534 // as a later change.
535
536 /// LambdaCaptureFields - Mapping from captured variables/this to
537 /// corresponding data members in the closure class.
538 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
539 FieldDecl *LambdaThisCaptureField;
540
Richard Smithf6f003a2011-12-16 19:06:07 +0000541 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000543 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000544 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000545
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000546 // Return the temporary for Key whose version number is Version.
547 APValue *getTemporary(const void *Key, unsigned Version) {
548 MapKeyTy KV(Key, Version);
549 auto LB = Temporaries.lower_bound(KV);
550 if (LB != Temporaries.end() && LB->first == KV)
551 return &LB->second;
552 // Pair (Key,Version) wasn't found in the map. Check that no elements
553 // in the map have 'Key' as their key.
554 assert((LB == Temporaries.end() || LB->first.first != Key) &&
555 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
556 "Element with key 'Key' found in map");
557 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000558 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000559
560 // Return the current temporary for Key in the map.
561 APValue *getCurrentTemporary(const void *Key) {
562 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
563 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
564 return &std::prev(UB)->second;
565 return nullptr;
566 }
567
568 // Return the version number of the current temporary for Key.
569 unsigned getCurrentTemporaryVersion(const void *Key) const {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return std::prev(UB)->first.second;
573 return 0;
574 }
575
Richard Smith08d6a2c2013-07-24 07:11:57 +0000576 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000577 };
578
Richard Smith852c9db2013-04-20 22:23:05 +0000579 /// Temporarily override 'this'.
580 class ThisOverrideRAII {
581 public:
582 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
583 : Frame(Frame), OldThis(Frame.This) {
584 if (Enable)
585 Frame.This = NewThis;
586 }
587 ~ThisOverrideRAII() {
588 Frame.This = OldThis;
589 }
590 private:
591 CallStackFrame &Frame;
592 const LValue *OldThis;
593 };
594
Richard Smith92b1ce02011-12-12 09:28:41 +0000595 /// A partial diagnostic which we might know in advance that we are not going
596 /// to emit.
597 class OptionalDiagnostic {
598 PartialDiagnostic *Diag;
599
600 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000601 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
602 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000603
604 template<typename T>
605 OptionalDiagnostic &operator<<(const T &v) {
606 if (Diag)
607 *Diag << v;
608 return *this;
609 }
Richard Smithfe800032012-01-31 04:08:20 +0000610
611 OptionalDiagnostic &operator<<(const APSInt &I) {
612 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000613 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000614 I.toString(Buffer);
615 *Diag << StringRef(Buffer.data(), Buffer.size());
616 }
617 return *this;
618 }
619
620 OptionalDiagnostic &operator<<(const APFloat &F) {
621 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000622 // FIXME: Force the precision of the source value down so we don't
623 // print digits which are usually useless (we don't really care here if
624 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000625 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000626 // representation which rounds to the correct value, but it's a bit
627 // tricky to implement.
628 unsigned precision =
629 llvm::APFloat::semanticsPrecision(F.getSemantics());
630 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000631 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000632 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000633 *Diag << StringRef(Buffer.data(), Buffer.size());
634 }
635 return *this;
636 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000637
638 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
639 if (Diag) {
640 SmallVector<char, 32> Buffer;
641 FX.toString(Buffer);
642 *Diag << StringRef(Buffer.data(), Buffer.size());
643 }
644 return *this;
645 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 };
647
Richard Smith08d6a2c2013-07-24 07:11:57 +0000648 /// A cleanup, and a flag indicating whether it is lifetime-extended.
649 class Cleanup {
650 llvm::PointerIntPair<APValue*, 1, bool> Value;
651
652 public:
653 Cleanup(APValue *Val, bool IsLifetimeExtended)
654 : Value(Val, IsLifetimeExtended) {}
655
656 bool isLifetimeExtended() const { return Value.getInt(); }
657 void endLifetime() {
658 *Value.getPointer() = APValue();
659 }
660 };
661
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000662 /// A reference to an object whose construction we are currently evaluating.
663 struct ObjectUnderConstruction {
664 APValue::LValueBase Base;
665 ArrayRef<APValue::LValuePathEntry> Path;
666 friend bool operator==(const ObjectUnderConstruction &LHS,
667 const ObjectUnderConstruction &RHS) {
668 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669 }
670 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671 return llvm::hash_combine(Obj.Base, Obj.Path);
672 }
673 };
674 enum class ConstructionPhase { None, Bases, AfterBases };
675}
676
677namespace llvm {
678template<> struct DenseMapInfo<ObjectUnderConstruction> {
679 using Base = DenseMapInfo<APValue::LValueBase>;
680 static ObjectUnderConstruction getEmptyKey() {
681 return {Base::getEmptyKey(), {}}; }
682 static ObjectUnderConstruction getTombstoneKey() {
683 return {Base::getTombstoneKey(), {}};
684 }
685 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
686 return hash_value(Object);
687 }
688 static bool isEqual(const ObjectUnderConstruction &LHS,
689 const ObjectUnderConstruction &RHS) {
690 return LHS == RHS;
691 }
692};
693}
694
695namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000696 /// EvalInfo - This is a private struct used by the evaluator to capture
697 /// information about a subexpression as it is folded. It retains information
698 /// about the AST context, but also maintains information about the folded
699 /// expression.
700 ///
701 /// If an expression could be evaluated, it is still possible it is not a C
702 /// "integer constant expression" or constant expression. If not, this struct
703 /// captures information about how and why not.
704 ///
705 /// One bit of information passed *into* the request for constant folding
706 /// indicates whether the subexpression is "evaluated" or not according to C
707 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
708 /// evaluate the expression regardless of what the RHS is, but C only allows
709 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000710 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000711 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000712
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000713 /// EvalStatus - Contains information about the evaluation.
714 Expr::EvalStatus &EvalStatus;
715
716 /// CurrentCall - The top of the constexpr call stack.
717 CallStackFrame *CurrentCall;
718
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000719 /// CallStackDepth - The number of calls in the call stack right now.
720 unsigned CallStackDepth;
721
Richard Smithb228a862012-02-15 02:18:13 +0000722 /// NextCallIndex - The next call index to assign.
723 unsigned NextCallIndex;
724
Richard Smitha3d3bd22013-05-08 02:12:03 +0000725 /// StepsLeft - The remaining number of evaluation steps we're permitted
726 /// to perform. This is essentially a limit for the number of statements
727 /// we will evaluate.
728 unsigned StepsLeft;
729
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000730 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000731 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000732 CallStackFrame BottomFrame;
733
Richard Smith08d6a2c2013-07-24 07:11:57 +0000734 /// A stack of values whose lifetimes end at the end of some surrounding
735 /// evaluation frame.
736 llvm::SmallVector<Cleanup, 16> CleanupStack;
737
Richard Smithd62306a2011-11-10 06:34:14 +0000738 /// EvaluatingDecl - This is the declaration whose initializer is being
739 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000740 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000741
742 /// EvaluatingDeclValue - This is the value being constructed for the
743 /// declaration whose initializer is being evaluated, if any.
744 APValue *EvaluatingDeclValue;
745
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000746 /// Set of objects that are currently being constructed.
747 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
748 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000749
750 struct EvaluatingConstructorRAII {
751 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000752 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000753 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000754 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
755 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000756 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000757 DidInsert =
758 EI.ObjectsUnderConstruction
759 .insert({Object, HasBases ? ConstructionPhase::Bases
760 : ConstructionPhase::AfterBases})
761 .second;
762 }
763 void finishedConstructingBases() {
764 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000765 }
766 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000767 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000768 }
769 };
770
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000771 ConstructionPhase
772 isEvaluatingConstructor(APValue::LValueBase Base,
773 ArrayRef<APValue::LValuePathEntry> Path) {
774 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000775 }
776
Richard Smith37be3362019-05-04 04:00:45 +0000777 /// If we're currently speculatively evaluating, the outermost call stack
778 /// depth at which we can mutate state, otherwise 0.
779 unsigned SpeculativeEvaluationDepth = 0;
780
Richard Smith410306b2016-12-12 02:53:20 +0000781 /// The current array initialization index, if we're performing array
782 /// initialization.
783 uint64_t ArrayInitIndex = -1;
784
Richard Smith357362d2011-12-13 06:39:58 +0000785 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
786 /// notes attached to it will also be stored, otherwise they will not be.
787 bool HasActiveDiagnostic;
788
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000789 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000790 /// fold (not just why it's not strictly a constant expression)?
791 bool HasFoldFailureDiagnostic;
792
Fangrui Song407659a2018-11-30 23:41:18 +0000793 /// Whether or not we're in a context where the front end requires a
794 /// constant value.
795 bool InConstantContext;
796
Richard Smith6d4c6582013-11-05 22:18:15 +0000797 enum EvaluationMode {
798 /// Evaluate as a constant expression. Stop if we find that the expression
799 /// is not a constant expression.
800 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000801
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 /// Evaluate as a potential constant expression. Keep going if we hit a
803 /// construct that we can't evaluate yet (because we don't yet know the
804 /// value of something) but stop if we hit something that could never be
805 /// a constant expression.
806 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000807
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 /// Fold the expression to a constant. Stop if we hit a side-effect that
809 /// we can't model.
810 EM_ConstantFold,
811
812 /// Evaluate the expression looking for integer overflow and similar
813 /// issues. Don't worry about side-effects, and try to visit all
814 /// subexpressions.
815 EM_EvaluateForOverflow,
816
817 /// Evaluate in any way we know how. Don't worry about side-effects that
818 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000819 EM_IgnoreSideEffects,
820
821 /// Evaluate as a constant expression. Stop if we find that the expression
822 /// is not a constant expression. Some expressions can be retried in the
823 /// optimizer if we don't constant fold them here, but in an unevaluated
824 /// context we try to fold them immediately since the optimizer never
825 /// gets a chance to look at it.
826 EM_ConstantExpressionUnevaluated,
827
828 /// Evaluate as a potential constant expression. Keep going if we hit a
829 /// construct that we can't evaluate yet (because we don't yet know the
830 /// value of something) but stop if we hit something that could never be
831 /// a constant expression. Some expressions can be retried in the
832 /// optimizer if we don't constant fold them here, but in an unevaluated
833 /// context we try to fold them immediately since the optimizer never
834 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000835 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000836 } EvalMode;
837
838 /// Are we checking whether the expression is a potential constant
839 /// expression?
840 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000841 return EvalMode == EM_PotentialConstantExpression ||
842 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000843 }
844
845 /// Are we checking an expression for overflow?
846 // FIXME: We should check for any kind of undefined or suspicious behavior
847 // in such constructs, not just overflow.
848 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
849
850 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000851 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000852 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000853 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000854 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
855 EvaluatingDecl((const ValueDecl *)nullptr),
856 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000857 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000858 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000859
Richard Smith7525ff62013-05-09 07:14:00 +0000860 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
861 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000862 EvaluatingDeclValue = &Value;
863 }
864
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000866
Richard Smith357362d2011-12-13 06:39:58 +0000867 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000868 // Don't perform any constexpr calls (other than the call we're checking)
869 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000870 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000871 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000872 if (NextCallIndex == 0) {
873 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000874 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000875 return false;
876 }
Richard Smith357362d2011-12-13 06:39:58 +0000877 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
878 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000879 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000880 << getLangOpts().ConstexprCallDepth;
881 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000882 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000883
Richard Smith37be3362019-05-04 04:00:45 +0000884 std::pair<CallStackFrame *, unsigned>
885 getCallFrameAndDepth(unsigned CallIndex) {
886 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000887 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
888 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000889 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000890 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000891 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000892 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000893 --Depth;
894 }
895 if (Frame->Index == CallIndex)
896 return {Frame, Depth};
897 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000898 }
899
Richard Smitha3d3bd22013-05-08 02:12:03 +0000900 bool nextStep(const Stmt *S) {
901 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000902 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000903 return false;
904 }
905 --StepsLeft;
906 return true;
907 }
908
Richard Smith357362d2011-12-13 06:39:58 +0000909 private:
910 /// Add a diagnostic to the diagnostics list.
911 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
912 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
913 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
914 return EvalStatus.Diag->back().second;
915 }
916
Richard Smithf6f003a2011-12-16 19:06:07 +0000917 /// Add notes containing a call stack to the current point of evaluation.
918 void addCallStack(unsigned Limit);
919
Faisal Valie690b7a2016-07-02 22:34:24 +0000920 private:
921 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
922 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000923
Richard Smith92b1ce02011-12-12 09:28:41 +0000924 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000925 // If we have a prior diagnostic, it will be noting that the expression
926 // isn't a constant expression. This diagnostic is more important,
927 // unless we require this evaluation to produce a constant expression.
928 //
929 // FIXME: We might want to show both diagnostics to the user in
930 // EM_ConstantFold mode.
931 if (!EvalStatus.Diag->empty()) {
932 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000933 case EM_ConstantFold:
934 case EM_IgnoreSideEffects:
935 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000936 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000937 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000938 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000939 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 case EM_ConstantExpression:
941 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000942 case EM_ConstantExpressionUnevaluated:
943 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000944 HasActiveDiagnostic = false;
945 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000946 }
947 }
948
Richard Smithf6f003a2011-12-16 19:06:07 +0000949 unsigned CallStackNotes = CallStackDepth - 1;
950 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
951 if (Limit)
952 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000954 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000955
Richard Smith357362d2011-12-13 06:39:58 +0000956 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000957 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000958 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000959 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
960 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000961 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000962 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000963 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000964 }
Richard Smith357362d2011-12-13 06:39:58 +0000965 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000966 return OptionalDiagnostic();
967 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000968 public:
969 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
970 OptionalDiagnostic
971 FFDiag(SourceLocation Loc,
972 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
973 unsigned ExtraNotes = 0) {
974 return Diag(Loc, DiagId, ExtraNotes, false);
975 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000976
Faisal Valie690b7a2016-07-02 22:34:24 +0000977 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000978 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000979 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000981 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000982 HasActiveDiagnostic = false;
983 return OptionalDiagnostic();
984 }
985
Richard Smith92b1ce02011-12-12 09:28:41 +0000986 /// Diagnose that the evaluation does not produce a C++11 core constant
987 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 ///
989 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
990 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000991 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000992 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000993 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000994 // Don't override a previous diagnostic. Don't bother collecting
995 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000996 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000997 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000998 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000999 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001000 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +00001001 }
Faisal Valie690b7a2016-07-02 22:34:24 +00001002 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1003 = diag::note_invalid_subexpr_in_const_expr,
1004 unsigned ExtraNotes = 0) {
1005 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1006 }
Richard Smith357362d2011-12-13 06:39:58 +00001007 /// Add a note to a prior diagnostic.
1008 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1009 if (!HasActiveDiagnostic)
1010 return OptionalDiagnostic();
1011 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +00001012 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00001013
1014 /// Add a stack of notes to a prior diagnostic.
1015 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1016 if (HasActiveDiagnostic) {
1017 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1018 Diags.begin(), Diags.end());
1019 }
1020 }
Richard Smith253c2a32012-01-27 01:14:48 +00001021
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 /// Should we continue evaluation after encountering a side-effect that we
1023 /// couldn't model?
1024 bool keepEvaluatingAfterSideEffect() {
1025 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00001026 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001027 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001028 case EM_EvaluateForOverflow:
1029 case EM_IgnoreSideEffects:
1030 return true;
1031
Richard Smith6d4c6582013-11-05 22:18:15 +00001032 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001033 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001034 case EM_ConstantFold:
1035 return false;
1036 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001037 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001038 }
1039
1040 /// Note that we have had a side-effect, and determine whether we should
1041 /// keep evaluating.
1042 bool noteSideEffect() {
1043 EvalStatus.HasSideEffects = true;
1044 return keepEvaluatingAfterSideEffect();
1045 }
1046
Richard Smithce8eca52015-12-08 03:21:47 +00001047 /// Should we continue evaluation after encountering undefined behavior?
1048 bool keepEvaluatingAfterUndefinedBehavior() {
1049 switch (EvalMode) {
1050 case EM_EvaluateForOverflow:
1051 case EM_IgnoreSideEffects:
1052 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001053 return true;
1054
1055 case EM_PotentialConstantExpression:
1056 case EM_PotentialConstantExpressionUnevaluated:
1057 case EM_ConstantExpression:
1058 case EM_ConstantExpressionUnevaluated:
1059 return false;
1060 }
1061 llvm_unreachable("Missed EvalMode case");
1062 }
1063
1064 /// Note that we hit something that was technically undefined behavior, but
1065 /// that we can evaluate past it (such as signed overflow or floating-point
1066 /// division by zero.)
1067 bool noteUndefinedBehavior() {
1068 EvalStatus.HasUndefinedBehavior = true;
1069 return keepEvaluatingAfterUndefinedBehavior();
1070 }
1071
Richard Smith253c2a32012-01-27 01:14:48 +00001072 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001073 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001074 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001075 if (!StepsLeft)
1076 return false;
1077
1078 switch (EvalMode) {
1079 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001080 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001081 case EM_EvaluateForOverflow:
1082 return true;
1083
1084 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001085 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001086 case EM_ConstantFold:
1087 case EM_IgnoreSideEffects:
1088 return false;
1089 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001090 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001091 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092
George Burgess IV8c892b52016-05-25 22:31:54 +00001093 /// Notes that we failed to evaluate an expression that other expressions
1094 /// directly depend on, and determine if we should keep evaluating. This
1095 /// should only be called if we actually intend to keep evaluating.
1096 ///
1097 /// Call noteSideEffect() instead if we may be able to ignore the value that
1098 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1099 ///
1100 /// (Foo(), 1) // use noteSideEffect
1101 /// (Foo() || true) // use noteSideEffect
1102 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001103 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001104 // Failure when evaluating some expression often means there is some
1105 // subexpression whose evaluation was skipped. Therefore, (because we
1106 // don't track whether we skipped an expression when unwinding after an
1107 // evaluation failure) every evaluation failure that bubbles up from a
1108 // subexpression implies that a side-effect has potentially happened. We
1109 // skip setting the HasSideEffects flag to true until we decide to
1110 // continue evaluating after that point, which happens here.
1111 bool KeepGoing = keepEvaluatingAfterFailure();
1112 EvalStatus.HasSideEffects |= KeepGoing;
1113 return KeepGoing;
1114 }
1115
Richard Smith410306b2016-12-12 02:53:20 +00001116 class ArrayInitLoopIndex {
1117 EvalInfo &Info;
1118 uint64_t OuterIndex;
1119
1120 public:
1121 ArrayInitLoopIndex(EvalInfo &Info)
1122 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1123 Info.ArrayInitIndex = 0;
1124 }
1125 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1126
1127 operator uint64_t&() { return Info.ArrayInitIndex; }
1128 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001129 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001130
1131 /// Object used to treat all foldable expressions as constant expressions.
1132 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001133 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001134 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001135 bool HadNoPriorDiags;
1136 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001137
Richard Smith6d4c6582013-11-05 22:18:15 +00001138 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1139 : Info(Info),
1140 Enabled(Enabled),
1141 HadNoPriorDiags(Info.EvalStatus.Diag &&
1142 Info.EvalStatus.Diag->empty() &&
1143 !Info.EvalStatus.HasSideEffects),
1144 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001145 if (Enabled &&
1146 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1147 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001148 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001149 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001150 void keepDiagnostics() { Enabled = false; }
1151 ~FoldConstant() {
1152 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001153 !Info.EvalStatus.HasSideEffects)
1154 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001155 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001156 }
1157 };
Richard Smith17100ba2012-02-16 02:46:34 +00001158
James Y Knight892b09b2018-10-10 02:53:43 +00001159 /// RAII object used to set the current evaluation mode to ignore
1160 /// side-effects.
1161 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001162 EvalInfo &Info;
1163 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001164 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001165 : Info(Info), OldMode(Info.EvalMode) {
1166 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001167 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001168 }
1169
James Y Knight892b09b2018-10-10 02:53:43 +00001170 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001171 };
1172
George Burgess IV8c892b52016-05-25 22:31:54 +00001173 /// RAII object used to optionally suppress diagnostics and side-effects from
1174 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001175 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001176 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001177 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001178 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001179
George Burgess IV8c892b52016-05-25 22:31:54 +00001180 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001181 Info = Other.Info;
1182 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001183 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001184 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001185 }
1186
1187 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001188 if (!Info)
1189 return;
1190
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001191 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001192 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001193 }
1194
Richard Smith17100ba2012-02-16 02:46:34 +00001195 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001196 SpeculativeEvaluationRAII() = default;
1197
1198 SpeculativeEvaluationRAII(
1199 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001200 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001201 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001202 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001203 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001204 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001205
1206 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1207 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1208 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001209 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001210
1211 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1212 maybeRestoreState();
1213 moveFromAndCancel(std::move(Other));
1214 return *this;
1215 }
1216
1217 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001218 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001219
1220 /// RAII object wrapping a full-expression or block scope, and handling
1221 /// the ending of the lifetime of temporaries created within it.
1222 template<bool IsFullExpression>
1223 class ScopeRAII {
1224 EvalInfo &Info;
1225 unsigned OldStackSize;
1226 public:
1227 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001228 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1229 // Push a new temporary version. This is needed to distinguish between
1230 // temporaries created in different iterations of a loop.
1231 Info.CurrentCall->pushTempVersion();
1232 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001233 ~ScopeRAII() {
1234 // Body moved to a static method to encourage the compiler to inline away
1235 // instances of this class.
1236 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001237 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001238 }
1239 private:
1240 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1241 unsigned NewEnd = OldStackSize;
1242 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1243 I != N; ++I) {
1244 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1245 // Full-expression cleanup of a lifetime-extended temporary: nothing
1246 // to do, just move this cleanup to the right place in the stack.
1247 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1248 ++NewEnd;
1249 } else {
1250 // End the lifetime of the object.
1251 Info.CleanupStack[I].endLifetime();
1252 }
1253 }
1254 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1255 Info.CleanupStack.end());
1256 }
1257 };
1258 typedef ScopeRAII<false> BlockScopeRAII;
1259 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001260}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001261
Richard Smitha8105bc2012-01-06 16:39:00 +00001262bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1263 CheckSubobjectKind CSK) {
1264 if (Invalid)
1265 return false;
1266 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001267 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001268 << CSK;
1269 setInvalid();
1270 return false;
1271 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001272 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1273 // must actually be at least one array element; even a VLA cannot have a
1274 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001275 return true;
1276}
1277
Richard Smith6f4f0f12017-10-20 22:56:25 +00001278void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1279 const Expr *E) {
1280 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1281 // Do not set the designator as invalid: we can represent this situation,
1282 // and correct handling of __builtin_object_size requires us to do so.
1283}
1284
Richard Smitha8105bc2012-01-06 16:39:00 +00001285void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001286 const Expr *E,
1287 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001288 // If we're complaining, we must be able to statically determine the size of
1289 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001290 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001291 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001292 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001293 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001294 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001295 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001296 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001297 setInvalid();
1298}
1299
Richard Smithf6f003a2011-12-16 19:06:07 +00001300CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1301 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001302 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001303 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1304 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001305 Info.CurrentCall = this;
1306 ++Info.CallStackDepth;
1307}
1308
1309CallStackFrame::~CallStackFrame() {
1310 assert(Info.CurrentCall == this && "calls retired out of order");
1311 --Info.CallStackDepth;
1312 Info.CurrentCall = Caller;
1313}
1314
Richard Smith08d6a2c2013-07-24 07:11:57 +00001315APValue &CallStackFrame::createTemporary(const void *Key,
1316 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001317 unsigned Version = Info.CurrentCall->getTempVersion();
1318 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001319 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001320 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1321 return Result;
1322}
1323
Richard Smith84401042013-06-03 05:03:02 +00001324static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001325
1326void EvalInfo::addCallStack(unsigned Limit) {
1327 // Determine which calls to skip, if any.
1328 unsigned ActiveCalls = CallStackDepth - 1;
1329 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1330 if (Limit && Limit < ActiveCalls) {
1331 SkipStart = Limit / 2 + Limit % 2;
1332 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001333 }
1334
Richard Smithf6f003a2011-12-16 19:06:07 +00001335 // Walk the call stack and add the diagnostics.
1336 unsigned CallIdx = 0;
1337 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1338 Frame = Frame->Caller, ++CallIdx) {
1339 // Skip this call?
1340 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1341 if (CallIdx == SkipStart) {
1342 // Note that we're skipping calls.
1343 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1344 << unsigned(ActiveCalls - Limit);
1345 }
1346 continue;
1347 }
1348
Richard Smith5179eb72016-06-28 19:03:57 +00001349 // Use a different note for an inheriting constructor, because from the
1350 // user's perspective it's not really a function at all.
1351 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1352 if (CD->isInheritingConstructor()) {
1353 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1354 << CD->getParent();
1355 continue;
1356 }
1357 }
1358
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001359 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001360 llvm::raw_svector_ostream Out(Buffer);
1361 describeCall(Frame, Out);
1362 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1363 }
1364}
1365
Richard Smithdebad642019-05-12 09:39:08 +00001366/// Kinds of access we can perform on an object, for diagnostics. Note that
1367/// we consider a member function call to be a kind of access, even though
1368/// it is not formally an access of the object, because it has (largely) the
1369/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001370enum AccessKinds {
1371 AK_Read,
1372 AK_Assign,
1373 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001374 AK_Decrement,
1375 AK_MemberCall,
Richard Smith7bd54ab2019-05-15 20:22:21 +00001376 AK_DynamicCast,
Richard Smitha9330302019-05-17 19:19:28 +00001377 AK_TypeId,
Hubert Tong147b7432018-12-12 16:53:43 +00001378};
1379
Richard Smithdebad642019-05-12 09:39:08 +00001380static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001381 switch (AK) {
1382 case AK_Read:
1383 case AK_MemberCall:
1384 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001385 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001386 return false;
1387 case AK_Assign:
1388 case AK_Increment:
1389 case AK_Decrement:
1390 return true;
1391 }
1392 llvm_unreachable("unknown access kind");
1393}
1394
1395/// Is this an access per the C++ definition?
1396static bool isFormalAccess(AccessKinds AK) {
1397 return AK == AK_Read || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001398}
1399
Richard Smithf6f003a2011-12-16 19:06:07 +00001400namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001401 struct ComplexValue {
1402 private:
1403 bool IsInt;
1404
1405 public:
1406 APSInt IntReal, IntImag;
1407 APFloat FloatReal, FloatImag;
1408
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001409 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001410
1411 void makeComplexFloat() { IsInt = false; }
1412 bool isComplexFloat() const { return !IsInt; }
1413 APFloat &getComplexFloatReal() { return FloatReal; }
1414 APFloat &getComplexFloatImag() { return FloatImag; }
1415
1416 void makeComplexInt() { IsInt = true; }
1417 bool isComplexInt() const { return IsInt; }
1418 APSInt &getComplexIntReal() { return IntReal; }
1419 APSInt &getComplexIntImag() { return IntImag; }
1420
Richard Smith2e312c82012-03-03 22:46:17 +00001421 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001422 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001423 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001424 else
Richard Smith2e312c82012-03-03 22:46:17 +00001425 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001426 }
Richard Smith2e312c82012-03-03 22:46:17 +00001427 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001428 assert(v.isComplexFloat() || v.isComplexInt());
1429 if (v.isComplexFloat()) {
1430 makeComplexFloat();
1431 FloatReal = v.getComplexFloatReal();
1432 FloatImag = v.getComplexFloatImag();
1433 } else {
1434 makeComplexInt();
1435 IntReal = v.getComplexIntReal();
1436 IntImag = v.getComplexIntImag();
1437 }
1438 }
John McCall93d91dc2010-05-07 17:22:02 +00001439 };
John McCall45d55e42010-05-07 21:00:08 +00001440
1441 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001442 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001443 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001444 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001445 bool IsNullPtr : 1;
1446 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001447
Richard Smithce40ad62011-11-12 22:28:03 +00001448 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001449 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001450 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001451 SubobjectDesignator &getLValueDesignator() { return Designator; }
1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001453 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001454
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456 unsigned getLValueVersion() const { return Base.getVersion(); }
1457
Richard Smith2e312c82012-03-03 22:46:17 +00001458 void moveInto(APValue &V) const {
1459 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001460 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001461 else {
1462 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001463 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001464 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001465 }
John McCall45d55e42010-05-07 21:00:08 +00001466 }
Richard Smith2e312c82012-03-03 22:46:17 +00001467 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001468 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001469 Base = V.getLValueBase();
1470 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001471 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001472 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001473 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001474 }
1475
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001476 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001477#ifndef NDEBUG
1478 // We only allow a few types of invalid bases. Enforce that here.
1479 if (BInvalid) {
1480 const auto *E = B.get<const Expr *>();
1481 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1482 "Unexpected type of invalid base");
1483 }
1484#endif
1485
Richard Smithce40ad62011-11-12 22:28:03 +00001486 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001487 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001488 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001489 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001490 IsNullPtr = false;
1491 }
1492
1493 void setNull(QualType PointerTy, uint64_t TargetVal) {
1494 Base = (Expr *)nullptr;
1495 Offset = CharUnits::fromQuantity(TargetVal);
1496 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001497 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1498 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001499 }
1500
George Burgess IV3a03fab2015-09-04 21:28:13 +00001501 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001502 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001503 }
1504
Hubert Tong147b7432018-12-12 16:53:43 +00001505 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001506 // Check that this LValue is not based on a null pointer. If it is, produce
1507 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001508 template <typename GenDiagType>
1509 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001510 if (Designator.Invalid)
1511 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001512 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001513 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001514 Designator.setInvalid();
1515 return false;
1516 }
1517 return true;
1518 }
1519
Hubert Tong147b7432018-12-12 16:53:43 +00001520 public:
1521 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1522 CheckSubobjectKind CSK) {
1523 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1524 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1525 });
1526 }
1527
1528 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1529 AccessKinds AK) {
1530 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1531 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1532 });
1533 }
1534
Richard Smitha8105bc2012-01-06 16:39:00 +00001535 // Check this LValue refers to an object. If not, set the designator to be
1536 // invalid and emit a diagnostic.
1537 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001538 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001539 Designator.checkSubobject(Info, E, CSK);
1540 }
1541
1542 void addDecl(EvalInfo &Info, const Expr *E,
1543 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001544 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1545 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001546 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001547 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1548 if (!Designator.Entries.empty()) {
1549 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1550 Designator.setInvalid();
1551 return;
1552 }
Richard Smithefdb5032017-11-15 03:03:56 +00001553 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1554 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1555 Designator.FirstEntryIsAnUnsizedArray = true;
1556 Designator.addUnsizedArrayUnchecked(ElemTy);
1557 }
George Burgess IVe3763372016-12-22 02:50:20 +00001558 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001559 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001560 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1561 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001562 }
Richard Smith66c96992012-02-18 22:04:06 +00001563 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001564 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1565 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001566 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001567 void clearIsNullPointer() {
1568 IsNullPtr = false;
1569 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001570 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1571 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001572 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1573 // but we're not required to diagnose it and it's valid in C++.)
1574 if (!Index)
1575 return;
1576
1577 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1578 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1579 // offsets.
1580 uint64_t Offset64 = Offset.getQuantity();
1581 uint64_t ElemSize64 = ElementSize.getQuantity();
1582 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1583 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1584
1585 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001586 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001587 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001588 }
1589 void adjustOffset(CharUnits N) {
1590 Offset += N;
1591 if (N.getQuantity())
1592 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001593 }
John McCall45d55e42010-05-07 21:00:08 +00001594 };
Richard Smith027bf112011-11-17 22:56:20 +00001595
1596 struct MemberPtr {
1597 MemberPtr() {}
1598 explicit MemberPtr(const ValueDecl *Decl) :
1599 DeclAndIsDerivedMember(Decl, false), Path() {}
1600
1601 /// The member or (direct or indirect) field referred to by this member
1602 /// pointer, or 0 if this is a null member pointer.
1603 const ValueDecl *getDecl() const {
1604 return DeclAndIsDerivedMember.getPointer();
1605 }
1606 /// Is this actually a member of some type derived from the relevant class?
1607 bool isDerivedMember() const {
1608 return DeclAndIsDerivedMember.getInt();
1609 }
1610 /// Get the class which the declaration actually lives in.
1611 const CXXRecordDecl *getContainingRecord() const {
1612 return cast<CXXRecordDecl>(
1613 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1614 }
1615
Richard Smith2e312c82012-03-03 22:46:17 +00001616 void moveInto(APValue &V) const {
1617 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001618 }
Richard Smith2e312c82012-03-03 22:46:17 +00001619 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001620 assert(V.isMemberPointer());
1621 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1622 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1623 Path.clear();
1624 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1625 Path.insert(Path.end(), P.begin(), P.end());
1626 }
1627
1628 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1629 /// whether the member is a member of some class derived from the class type
1630 /// of the member pointer.
1631 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1632 /// Path - The path of base/derived classes from the member declaration's
1633 /// class (exclusive) to the class type of the member pointer (inclusive).
1634 SmallVector<const CXXRecordDecl*, 4> Path;
1635
1636 /// Perform a cast towards the class of the Decl (either up or down the
1637 /// hierarchy).
1638 bool castBack(const CXXRecordDecl *Class) {
1639 assert(!Path.empty());
1640 const CXXRecordDecl *Expected;
1641 if (Path.size() >= 2)
1642 Expected = Path[Path.size() - 2];
1643 else
1644 Expected = getContainingRecord();
1645 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1646 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1647 // if B does not contain the original member and is not a base or
1648 // derived class of the class containing the original member, the result
1649 // of the cast is undefined.
1650 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1651 // (D::*). We consider that to be a language defect.
1652 return false;
1653 }
1654 Path.pop_back();
1655 return true;
1656 }
1657 /// Perform a base-to-derived member pointer cast.
1658 bool castToDerived(const CXXRecordDecl *Derived) {
1659 if (!getDecl())
1660 return true;
1661 if (!isDerivedMember()) {
1662 Path.push_back(Derived);
1663 return true;
1664 }
1665 if (!castBack(Derived))
1666 return false;
1667 if (Path.empty())
1668 DeclAndIsDerivedMember.setInt(false);
1669 return true;
1670 }
1671 /// Perform a derived-to-base member pointer cast.
1672 bool castToBase(const CXXRecordDecl *Base) {
1673 if (!getDecl())
1674 return true;
1675 if (Path.empty())
1676 DeclAndIsDerivedMember.setInt(true);
1677 if (isDerivedMember()) {
1678 Path.push_back(Base);
1679 return true;
1680 }
1681 return castBack(Base);
1682 }
1683 };
Richard Smith357362d2011-12-13 06:39:58 +00001684
Richard Smith7bb00672012-02-01 01:42:44 +00001685 /// Compare two member pointers, which are assumed to be of the same type.
1686 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1687 if (!LHS.getDecl() || !RHS.getDecl())
1688 return !LHS.getDecl() && !RHS.getDecl();
1689 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1690 return false;
1691 return LHS.Path == RHS.Path;
1692 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001693}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001694
Richard Smith2e312c82012-03-03 22:46:17 +00001695static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001696static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1697 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001698 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001699static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1700 bool InvalidBaseOK = false);
1701static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1702 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001703static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1704 EvalInfo &Info);
1705static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001706static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001707static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001708 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001709static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001710static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001711static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1712 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001713static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001714
Leonard Chand3f3e162019-01-18 21:04:25 +00001715/// Evaluate an integer or fixed point expression into an APResult.
1716static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1717 EvalInfo &Info);
1718
1719/// Evaluate only a fixed point expression into an APResult.
1720static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1721 EvalInfo &Info);
1722
Chris Lattner05706e882008-07-11 18:11:29 +00001723//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001724// Misc utilities
1725//===----------------------------------------------------------------------===//
1726
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001727/// A helper function to create a temporary and set an LValue.
1728template <class KeyTy>
1729static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1730 LValue &LV, CallStackFrame &Frame) {
1731 LV.set({Key, Frame.Info.CurrentCall->Index,
1732 Frame.Info.CurrentCall->getTempVersion()});
1733 return Frame.createTemporary(Key, IsLifetimeExtended);
1734}
1735
Richard Smithd6cc1982017-01-31 02:23:02 +00001736/// Negate an APSInt in place, converting it to a signed form if necessary, and
1737/// preserving its value (by extending by up to one bit as needed).
1738static void negateAsSigned(APSInt &Int) {
1739 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1740 Int = Int.extend(Int.getBitWidth() + 1);
1741 Int.setIsSigned(true);
1742 }
1743 Int = -Int;
1744}
1745
Richard Smith84401042013-06-03 05:03:02 +00001746/// Produce a string describing the given constexpr call.
1747static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1748 unsigned ArgIndex = 0;
1749 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1750 !isa<CXXConstructorDecl>(Frame->Callee) &&
1751 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1752
1753 if (!IsMemberCall)
1754 Out << *Frame->Callee << '(';
1755
1756 if (Frame->This && IsMemberCall) {
1757 APValue Val;
1758 Frame->This->moveInto(Val);
1759 Val.printPretty(Out, Frame->Info.Ctx,
1760 Frame->This->Designator.MostDerivedType);
1761 // FIXME: Add parens around Val if needed.
1762 Out << "->" << *Frame->Callee << '(';
1763 IsMemberCall = false;
1764 }
1765
1766 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1767 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1768 if (ArgIndex > (unsigned)IsMemberCall)
1769 Out << ", ";
1770
1771 const ParmVarDecl *Param = *I;
1772 const APValue &Arg = Frame->Arguments[ArgIndex];
1773 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1774
1775 if (ArgIndex == 0 && IsMemberCall)
1776 Out << "->" << *Frame->Callee << '(';
1777 }
1778
1779 Out << ')';
1780}
1781
Richard Smithd9f663b2013-04-22 15:31:51 +00001782/// Evaluate an expression to see if it had side-effects, and discard its
1783/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001784/// \return \c true if the caller should keep evaluating.
1785static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001786 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001787 if (!Evaluate(Scratch, Info, E))
1788 // We don't need the value, but we might have skipped a side effect here.
1789 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001790 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001791}
1792
Richard Smithd62306a2011-11-10 06:34:14 +00001793/// Should this call expression be treated as a string literal?
1794static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001795 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001796 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1797 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1798}
1799
Richard Smithce40ad62011-11-12 22:28:03 +00001800static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001801 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1802 // constant expression of pointer type that evaluates to...
1803
1804 // ... a null pointer value, or a prvalue core constant expression of type
1805 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001806 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001807
Richard Smithce40ad62011-11-12 22:28:03 +00001808 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1809 // ... the address of an object with static storage duration,
1810 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1811 return VD->hasGlobalStorage();
1812 // ... the address of a function,
1813 return isa<FunctionDecl>(D);
1814 }
1815
Richard Smithee0ce3022019-05-17 07:06:46 +00001816 if (B.is<TypeInfoLValue>())
1817 return true;
1818
Richard Smithce40ad62011-11-12 22:28:03 +00001819 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001820 switch (E->getStmtClass()) {
1821 default:
1822 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001823 case Expr::CompoundLiteralExprClass: {
1824 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1825 return CLE->isFileScope() && CLE->isLValue();
1826 }
Richard Smithe6c01442013-06-05 00:46:14 +00001827 case Expr::MaterializeTemporaryExprClass:
1828 // A materialized temporary might have been lifetime-extended to static
1829 // storage duration.
1830 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001831 // A string literal has static storage duration.
1832 case Expr::StringLiteralClass:
1833 case Expr::PredefinedExprClass:
1834 case Expr::ObjCStringLiteralClass:
1835 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001836 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001837 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001838 case Expr::ObjCBoxedExprClass:
1839 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001840 case Expr::CallExprClass:
1841 return IsStringLiteralCall(cast<CallExpr>(E));
1842 // For GCC compatibility, &&label has static storage duration.
1843 case Expr::AddrLabelExprClass:
1844 return true;
1845 // A Block literal expression may be used as the initialization value for
1846 // Block variables at global or local static scope.
1847 case Expr::BlockExprClass:
1848 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001849 case Expr::ImplicitValueInitExprClass:
1850 // FIXME:
1851 // We can never form an lvalue with an implicit value initialization as its
1852 // base through expression evaluation, so these only appear in one case: the
1853 // implicit variable declaration we invent when checking whether a constexpr
1854 // constructor can produce a constant expression. We must assume that such
1855 // an expression might be a global lvalue.
1856 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001857 }
John McCall95007602010-05-10 23:27:23 +00001858}
1859
Richard Smith06f71b52018-08-04 00:57:17 +00001860static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1861 return LVal.Base.dyn_cast<const ValueDecl*>();
1862}
1863
1864static bool IsLiteralLValue(const LValue &Value) {
1865 if (Value.getLValueCallIndex())
1866 return false;
1867 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1868 return E && !isa<MaterializeTemporaryExpr>(E);
1869}
1870
1871static bool IsWeakLValue(const LValue &Value) {
1872 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1873 return Decl && Decl->isWeak();
1874}
1875
1876static bool isZeroSized(const LValue &Value) {
1877 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1878 if (Decl && isa<VarDecl>(Decl)) {
1879 QualType Ty = Decl->getType();
1880 if (Ty->isArrayType())
1881 return Ty->isIncompleteType() ||
1882 Decl->getASTContext().getTypeSize(Ty) == 0;
1883 }
1884 return false;
1885}
1886
1887static bool HasSameBase(const LValue &A, const LValue &B) {
1888 if (!A.getLValueBase())
1889 return !B.getLValueBase();
1890 if (!B.getLValueBase())
1891 return false;
1892
1893 if (A.getLValueBase().getOpaqueValue() !=
1894 B.getLValueBase().getOpaqueValue()) {
1895 const Decl *ADecl = GetLValueBaseDecl(A);
1896 if (!ADecl)
1897 return false;
1898 const Decl *BDecl = GetLValueBaseDecl(B);
1899 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1900 return false;
1901 }
1902
1903 return IsGlobalLValue(A.getLValueBase()) ||
1904 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1905 A.getLValueVersion() == B.getLValueVersion());
1906}
1907
Richard Smithb228a862012-02-15 02:18:13 +00001908static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1909 assert(Base && "no location for a null lvalue");
1910 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1911 if (VD)
1912 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001913 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1914 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1915 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001916}
1917
Richard Smith80815602011-11-07 05:07:52 +00001918/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001919/// value for an address or reference constant expression. Return true if we
1920/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001921static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001922 QualType Type, const LValue &LVal,
1923 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001924 bool IsReferenceType = Type->isReferenceType();
1925
Richard Smith357362d2011-12-13 06:39:58 +00001926 APValue::LValueBase Base = LVal.getLValueBase();
1927 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1928
Richard Smith0dea49e2012-02-18 04:58:18 +00001929 // Check that the object is a global. Note that the fake 'this' object we
1930 // manufacture when checking potential constant expressions is conservatively
1931 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001932 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001933 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001934 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001935 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001936 << IsReferenceType << !Designator.Entries.empty()
1937 << !!VD << VD;
1938 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001939 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001940 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001941 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001942 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001943 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001945 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001946 LVal.getLValueCallIndex() == 0) &&
1947 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001948
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001949 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1950 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001951 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001952 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001953 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001954
Hans Wennborg82dd8772014-06-25 22:19:48 +00001955 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001956 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001957 return false;
1958 }
1959 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1960 // __declspec(dllimport) must be handled very carefully:
1961 // We must never initialize an expression with the thunk in C++.
1962 // Doing otherwise would allow the same id-expression to yield
1963 // different addresses for the same function in different translation
1964 // units. However, this means that we must dynamically initialize the
1965 // expression with the contents of the import address table at runtime.
1966 //
1967 // The C language has no notion of ODR; furthermore, it has no notion of
1968 // dynamic initialization. This means that we are permitted to
1969 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001970 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1971 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001972 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001973 }
1974 }
1975
Richard Smitha8105bc2012-01-06 16:39:00 +00001976 // Allow address constant expressions to be past-the-end pointers. This is
1977 // an extension: the standard requires them to point to an object.
1978 if (!IsReferenceType)
1979 return true;
1980
1981 // A reference constant expression must refer to an object.
1982 if (!Base) {
1983 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001984 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001985 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001986 }
1987
Richard Smith357362d2011-12-13 06:39:58 +00001988 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001989 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001991 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001992 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001993 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001994 }
1995
Richard Smith80815602011-11-07 05:07:52 +00001996 return true;
1997}
1998
Reid Klecknercd016d82017-07-07 22:04:29 +00001999/// Member pointers are constant expressions unless they point to a
2000/// non-virtual dllimport member function.
2001static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2002 SourceLocation Loc,
2003 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002004 const APValue &Value,
2005 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002006 const ValueDecl *Member = Value.getMemberPointerDecl();
2007 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2008 if (!FD)
2009 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002010 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2011 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002012}
2013
Richard Smithfddd3842011-12-30 21:15:51 +00002014/// Check that this core constant expression is of literal type, and if not,
2015/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002016static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002017 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002018 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002019 return true;
2020
Richard Smith7525ff62013-05-09 07:14:00 +00002021 // C++1y: A constant initializer for an object o [...] may also invoke
2022 // constexpr constructors for o and its subobjects even if those objects
2023 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002024 //
2025 // C++11 missed this detail for aggregates, so classes like this:
2026 // struct foo_t { union { int i; volatile int j; } u; };
2027 // are not (obviously) initializable like so:
2028 // __attribute__((__require_constant_initialization__))
2029 // static const foo_t x = {{0}};
2030 // because "i" is a subobject with non-literal initialization (due to the
2031 // volatile member of the union). See:
2032 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2033 // Therefore, we use the C++1y behavior.
2034 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002035 return true;
2036
Richard Smithfddd3842011-12-30 21:15:51 +00002037 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002038 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002039 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002040 << E->getType();
2041 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002042 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002043 return false;
2044}
2045
Richard Smith0b0a0b62011-10-29 20:57:55 +00002046/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00002047/// constant expression. If not, report an appropriate diagnostic. Does not
2048/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002049static bool
2050CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2051 const APValue &Value,
Richard Smith31c69a32019-05-21 23:15:20 +00002052 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2053 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002054 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002055 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002056 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002057 if (SubobjectLoc.isValid())
2058 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002059 return false;
2060 }
2061
Richard Smith77be48a2014-07-31 06:31:19 +00002062 // We allow _Atomic(T) to be initialized from anything that T can be
2063 // initialized from.
2064 if (const AtomicType *AT = Type->getAs<AtomicType>())
2065 Type = AT->getValueType();
2066
Richard Smithb228a862012-02-15 02:18:13 +00002067 // Core issue 1454: For a literal constant expression of array or class type,
2068 // each subobject of its value shall have been initialized by a constant
2069 // expression.
2070 if (Value.isArray()) {
2071 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2072 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2073 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Richard Smith31c69a32019-05-21 23:15:20 +00002074 Value.getArrayInitializedElt(I), Usage,
2075 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00002076 return false;
2077 }
2078 if (!Value.hasArrayFiller())
2079 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002080 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
Richard Smith31c69a32019-05-21 23:15:20 +00002081 Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00002082 }
Richard Smithb228a862012-02-15 02:18:13 +00002083 if (Value.isUnion() && Value.getUnionField()) {
2084 return CheckConstantExpression(Info, DiagLoc,
2085 Value.getUnionField()->getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002086 Value.getUnionValue(), Usage,
2087 Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00002088 }
2089 if (Value.isStruct()) {
2090 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2091 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2092 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002093 for (const CXXBaseSpecifier &BS : CD->bases()) {
2094 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002095 Value.getStructBase(BaseIndex), Usage,
2096 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00002097 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002098 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002099 }
2100 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002101 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002102 if (I->isUnnamedBitfield())
2103 continue;
2104
David Blaikie2d7c57e2012-04-30 02:36:29 +00002105 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002106 Value.getStructField(I->getFieldIndex()),
Richard Smith31c69a32019-05-21 23:15:20 +00002107 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002108 return false;
2109 }
2110 }
2111
2112 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002113 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002114 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002115 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002116 }
2117
Reid Klecknercd016d82017-07-07 22:04:29 +00002118 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002119 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002120
Richard Smithb228a862012-02-15 02:18:13 +00002121 // Everything else is fine.
2122 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002123}
2124
Richard Smith2e312c82012-03-03 22:46:17 +00002125static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002126 // A null base expression indicates a null pointer. These are always
2127 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002128 if (!Value.getLValueBase()) {
2129 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002130 return true;
2131 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002132
Richard Smith027bf112011-11-17 22:56:20 +00002133 // We have a non-null base. These are generally known to be true, but if it's
2134 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002135 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002136 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002137 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002138}
2139
Richard Smith2e312c82012-03-03 22:46:17 +00002140static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002141 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002142 case APValue::None:
2143 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002144 return false;
2145 case APValue::Int:
2146 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002147 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002148 case APValue::FixedPoint:
2149 Result = Val.getFixedPoint().getBoolValue();
2150 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002151 case APValue::Float:
2152 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002153 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002154 case APValue::ComplexInt:
2155 Result = Val.getComplexIntReal().getBoolValue() ||
2156 Val.getComplexIntImag().getBoolValue();
2157 return true;
2158 case APValue::ComplexFloat:
2159 Result = !Val.getComplexFloatReal().isZero() ||
2160 !Val.getComplexFloatImag().isZero();
2161 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002162 case APValue::LValue:
2163 return EvalPointerValueAsBool(Val, Result);
2164 case APValue::MemberPointer:
2165 Result = Val.getMemberPointerDecl();
2166 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002167 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002168 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002169 case APValue::Struct:
2170 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002171 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002172 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002173 }
2174
Richard Smith11562c52011-10-28 17:51:58 +00002175 llvm_unreachable("unknown APValue kind");
2176}
2177
2178static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2179 EvalInfo &Info) {
2180 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002181 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002182 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002183 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002184 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002185}
2186
Richard Smith357362d2011-12-13 06:39:58 +00002187template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002188static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002189 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002190 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002191 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002192 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002193}
2194
2195static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2196 QualType SrcType, const APFloat &Value,
2197 QualType DestType, APSInt &Result) {
2198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002199 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002200 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002201
Richard Smith357362d2011-12-13 06:39:58 +00002202 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002203 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002204 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2205 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002206 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002207 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002208}
2209
Richard Smith357362d2011-12-13 06:39:58 +00002210static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2211 QualType SrcType, QualType DestType,
2212 APFloat &Result) {
2213 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002214 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002215 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2216 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002218}
2219
Richard Smith911e1422012-01-30 22:27:01 +00002220static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2221 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002222 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002224 // Figure out if this is a truncate, extend or noop cast.
2225 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002226 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002227 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002228 if (DestType->isBooleanType())
2229 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002230 return Result;
2231}
2232
Richard Smith357362d2011-12-13 06:39:58 +00002233static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2234 QualType SrcType, const APSInt &Value,
2235 QualType DestType, APFloat &Result) {
2236 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002237 Result.convertFromAPInt(Value, Value.isSigned(),
2238 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002239 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002240}
2241
Richard Smith49ca8aa2013-08-06 07:09:20 +00002242static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2243 APValue &Value, const FieldDecl *FD) {
2244 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2245
2246 if (!Value.isInt()) {
2247 // Trying to store a pointer-cast-to-integer into a bitfield.
2248 // FIXME: In this case, we should provide the diagnostic for casting
2249 // a pointer to an integer.
2250 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002251 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002252 return false;
2253 }
2254
2255 APSInt &Int = Value.getInt();
2256 unsigned OldBitWidth = Int.getBitWidth();
2257 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2258 if (NewBitWidth < OldBitWidth)
2259 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2260 return true;
2261}
2262
Eli Friedman803acb32011-12-22 03:51:45 +00002263static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2264 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002265 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002266 if (!Evaluate(SVal, Info, E))
2267 return false;
2268 if (SVal.isInt()) {
2269 Res = SVal.getInt();
2270 return true;
2271 }
2272 if (SVal.isFloat()) {
2273 Res = SVal.getFloat().bitcastToAPInt();
2274 return true;
2275 }
2276 if (SVal.isVector()) {
2277 QualType VecTy = E->getType();
2278 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2279 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2280 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2281 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2282 Res = llvm::APInt::getNullValue(VecSize);
2283 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2284 APValue &Elt = SVal.getVectorElt(i);
2285 llvm::APInt EltAsInt;
2286 if (Elt.isInt()) {
2287 EltAsInt = Elt.getInt();
2288 } else if (Elt.isFloat()) {
2289 EltAsInt = Elt.getFloat().bitcastToAPInt();
2290 } else {
2291 // Don't try to handle vectors of anything other than int or float
2292 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002293 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002294 return false;
2295 }
2296 unsigned BaseEltSize = EltAsInt.getBitWidth();
2297 if (BigEndian)
2298 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2299 else
2300 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2301 }
2302 return true;
2303 }
2304 // Give up if the input isn't an int, float, or vector. For example, we
2305 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002306 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002307 return false;
2308}
2309
Richard Smith43e77732013-05-07 04:50:00 +00002310/// Perform the given integer operation, which is known to need at most BitWidth
2311/// bits, and check for overflow in the original type (if that type was not an
2312/// unsigned type).
2313template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002314static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2315 const APSInt &LHS, const APSInt &RHS,
2316 unsigned BitWidth, Operation Op,
2317 APSInt &Result) {
2318 if (LHS.isUnsigned()) {
2319 Result = Op(LHS, RHS);
2320 return true;
2321 }
Richard Smith43e77732013-05-07 04:50:00 +00002322
2323 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002324 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002325 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002326 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002327 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002328 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002329 << Result.toString(10) << E->getType();
2330 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002331 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002332 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002333 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002334}
2335
2336/// Perform the given binary integer operation.
2337static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2338 BinaryOperatorKind Opcode, APSInt RHS,
2339 APSInt &Result) {
2340 switch (Opcode) {
2341 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002342 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002343 return false;
2344 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002345 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2346 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002347 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002348 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2349 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002350 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002351 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2352 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002353 case BO_And: Result = LHS & RHS; return true;
2354 case BO_Xor: Result = LHS ^ RHS; return true;
2355 case BO_Or: Result = LHS | RHS; return true;
2356 case BO_Div:
2357 case BO_Rem:
2358 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002359 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002360 return false;
2361 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002362 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2363 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2364 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002365 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2366 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002367 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2368 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002369 return true;
2370 case BO_Shl: {
2371 if (Info.getLangOpts().OpenCL)
2372 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2373 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2374 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2375 RHS.isUnsigned());
2376 else if (RHS.isSigned() && RHS.isNegative()) {
2377 // During constant-folding, a negative shift is an opposite shift. Such
2378 // a shift is not a constant expression.
2379 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2380 RHS = -RHS;
2381 goto shift_right;
2382 }
2383 shift_left:
2384 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2385 // the shifted type.
2386 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2387 if (SA != RHS) {
2388 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2389 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002390 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002391 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2392 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002393 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2394 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002395 if (LHS.isNegative())
2396 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2397 else if (LHS.countLeadingZeros() < SA)
2398 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2399 }
2400 Result = LHS << SA;
2401 return true;
2402 }
2403 case BO_Shr: {
2404 if (Info.getLangOpts().OpenCL)
2405 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2406 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2407 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2408 RHS.isUnsigned());
2409 else if (RHS.isSigned() && RHS.isNegative()) {
2410 // During constant-folding, a negative shift is an opposite shift. Such a
2411 // shift is not a constant expression.
2412 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2413 RHS = -RHS;
2414 goto shift_left;
2415 }
2416 shift_right:
2417 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2418 // shifted type.
2419 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2420 if (SA != RHS)
2421 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2422 << RHS << E->getType() << LHS.getBitWidth();
2423 Result = LHS >> SA;
2424 return true;
2425 }
2426
2427 case BO_LT: Result = LHS < RHS; return true;
2428 case BO_GT: Result = LHS > RHS; return true;
2429 case BO_LE: Result = LHS <= RHS; return true;
2430 case BO_GE: Result = LHS >= RHS; return true;
2431 case BO_EQ: Result = LHS == RHS; return true;
2432 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002433 case BO_Cmp:
2434 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002435 }
2436}
2437
Richard Smith861b5b52013-05-07 23:34:45 +00002438/// Perform the given binary floating-point operation, in-place, on LHS.
2439static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2440 APFloat &LHS, BinaryOperatorKind Opcode,
2441 const APFloat &RHS) {
2442 switch (Opcode) {
2443 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002444 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002445 return false;
2446 case BO_Mul:
2447 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2448 break;
2449 case BO_Add:
2450 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2451 break;
2452 case BO_Sub:
2453 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2454 break;
2455 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002456 // [expr.mul]p4:
2457 // If the second operand of / or % is zero the behavior is undefined.
2458 if (RHS.isZero())
2459 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002460 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2461 break;
2462 }
2463
Richard Smith9e52c432019-07-06 21:05:52 +00002464 // [expr.pre]p4:
2465 // If during the evaluation of an expression, the result is not
2466 // mathematically defined [...], the behavior is undefined.
2467 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2468 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002469 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002470 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002471 }
Richard Smith861b5b52013-05-07 23:34:45 +00002472 return true;
2473}
2474
Richard Smitha8105bc2012-01-06 16:39:00 +00002475/// Cast an lvalue referring to a base subobject to a derived class, by
2476/// truncating the lvalue's path to the given length.
2477static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2478 const RecordDecl *TruncatedType,
2479 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002480 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002481
2482 // Check we actually point to a derived class object.
2483 if (TruncatedElements == D.Entries.size())
2484 return true;
2485 assert(TruncatedElements >= D.MostDerivedPathLength &&
2486 "not casting to a derived class");
2487 if (!Result.checkSubobject(Info, E, CSK_Derived))
2488 return false;
2489
2490 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002491 const RecordDecl *RD = TruncatedType;
2492 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002493 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002494 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2495 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002496 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002497 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002498 else
Richard Smithd62306a2011-11-10 06:34:14 +00002499 Result.Offset -= Layout.getBaseClassOffset(Base);
2500 RD = Base;
2501 }
Richard Smith027bf112011-11-17 22:56:20 +00002502 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002503 return true;
2504}
2505
John McCalld7bca762012-05-01 00:38:49 +00002506static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002507 const CXXRecordDecl *Derived,
2508 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002509 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002510 if (!RL) {
2511 if (Derived->isInvalidDecl()) return false;
2512 RL = &Info.Ctx.getASTRecordLayout(Derived);
2513 }
2514
Richard Smithd62306a2011-11-10 06:34:14 +00002515 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002516 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002517 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002518}
2519
Richard Smitha8105bc2012-01-06 16:39:00 +00002520static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002521 const CXXRecordDecl *DerivedDecl,
2522 const CXXBaseSpecifier *Base) {
2523 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2524
John McCalld7bca762012-05-01 00:38:49 +00002525 if (!Base->isVirtual())
2526 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002527
Richard Smitha8105bc2012-01-06 16:39:00 +00002528 SubobjectDesignator &D = Obj.Designator;
2529 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002530 return false;
2531
Richard Smitha8105bc2012-01-06 16:39:00 +00002532 // Extract most-derived object and corresponding type.
2533 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2534 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2535 return false;
2536
2537 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002538 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002539 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2540 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002541 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002542 return true;
2543}
2544
Richard Smith84401042013-06-03 05:03:02 +00002545static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2546 QualType Type, LValue &Result) {
2547 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2548 PathE = E->path_end();
2549 PathI != PathE; ++PathI) {
2550 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2551 *PathI))
2552 return false;
2553 Type = (*PathI)->getType();
2554 }
2555 return true;
2556}
2557
Richard Smith921f1322019-05-13 23:35:21 +00002558/// Cast an lvalue referring to a derived class to a known base subobject.
2559static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2560 const CXXRecordDecl *DerivedRD,
2561 const CXXRecordDecl *BaseRD) {
2562 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2563 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2564 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2565 llvm_unreachable("Class must be derived from the passed in base class!");
2566
2567 for (CXXBasePathElement &Elem : Paths.front())
2568 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2569 return false;
2570 return true;
2571}
2572
Richard Smithd62306a2011-11-10 06:34:14 +00002573/// Update LVal to refer to the given field, which must be a member of the type
2574/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002575static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002576 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002577 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002578 if (!RL) {
2579 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002580 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002581 }
Richard Smithd62306a2011-11-10 06:34:14 +00002582
2583 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002584 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002585 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002586 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002587}
2588
Richard Smith1b78b3d2012-01-25 22:15:11 +00002589/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002590static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002591 LValue &LVal,
2592 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002593 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002594 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002595 return false;
2596 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002597}
2598
Richard Smithd62306a2011-11-10 06:34:14 +00002599/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002600static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2601 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002602 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2603 // extension.
2604 if (Type->isVoidType() || Type->isFunctionType()) {
2605 Size = CharUnits::One();
2606 return true;
2607 }
2608
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002609 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002610 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002611 return false;
2612 }
2613
Richard Smithd62306a2011-11-10 06:34:14 +00002614 if (!Type->isConstantSizeType()) {
2615 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002616 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002617 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002618 return false;
2619 }
2620
2621 Size = Info.Ctx.getTypeSizeInChars(Type);
2622 return true;
2623}
2624
2625/// Update a pointer value to model pointer arithmetic.
2626/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002627/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002628/// \param LVal - The pointer value to be updated.
2629/// \param EltTy - The pointee type represented by LVal.
2630/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002631static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2632 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002633 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002634 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002635 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002636 return false;
2637
Yaxun Liu402804b2016-12-15 08:09:08 +00002638 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002639 return true;
2640}
2641
Richard Smithd6cc1982017-01-31 02:23:02 +00002642static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2643 LValue &LVal, QualType EltTy,
2644 int64_t Adjustment) {
2645 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2646 APSInt::get(Adjustment));
2647}
2648
Richard Smith66c96992012-02-18 22:04:06 +00002649/// Update an lvalue to refer to a component of a complex number.
2650/// \param Info - Information about the ongoing evaluation.
2651/// \param LVal - The lvalue to be updated.
2652/// \param EltTy - The complex number's component type.
2653/// \param Imag - False for the real component, true for the imaginary.
2654static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2655 LValue &LVal, QualType EltTy,
2656 bool Imag) {
2657 if (Imag) {
2658 CharUnits SizeOfComponent;
2659 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2660 return false;
2661 LVal.Offset += SizeOfComponent;
2662 }
2663 LVal.addComplex(Info, E, EltTy, Imag);
2664 return true;
2665}
2666
Richard Smith27908702011-10-24 17:54:18 +00002667/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002668///
2669/// \param Info Information about the ongoing evaluation.
2670/// \param E An expression to be used when printing diagnostics.
2671/// \param VD The variable whose initializer should be obtained.
2672/// \param Frame The frame in which the variable was created. Must be null
2673/// if this variable is not local to the evaluation.
2674/// \param Result Filled in with a pointer to the value of the variable.
2675static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2676 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002677 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002678
Richard Smith254a73d2011-10-28 22:34:42 +00002679 // If this is a parameter to an active constexpr function call, perform
2680 // argument substitution.
2681 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002682 // Assume arguments of a potential constant expression are unknown
2683 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002684 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002685 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002686 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002688 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002689 }
Richard Smith3229b742013-05-05 21:17:10 +00002690 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002691 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002692 }
Richard Smith27908702011-10-24 17:54:18 +00002693
Richard Smithd9f663b2013-04-22 15:31:51 +00002694 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002695 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002696 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2697 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002698 if (!Result) {
2699 // Assume variables referenced within a lambda's call operator that were
2700 // not declared within the call operator are captures and during checking
2701 // of a potential constant expression, assume they are unknown constant
2702 // expressions.
2703 assert(isLambdaCallOperator(Frame->Callee) &&
2704 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2705 "missing value for local variable");
2706 if (Info.checkingPotentialConstantExpression())
2707 return false;
2708 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 Info.FFDiag(E->getBeginLoc(),
2710 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002711 << "captures not currently allowed";
2712 return false;
2713 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002714 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002715 }
2716
Richard Smithd0b4dd62011-12-19 06:19:21 +00002717 // Dig out the initializer, and use the declaration which it's attached to.
2718 const Expr *Init = VD->getAnyInitializer(VD);
2719 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002720 // If we're checking a potential constant expression, the variable could be
2721 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002722 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002723 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002724 return false;
2725 }
2726
Richard Smithd62306a2011-11-10 06:34:14 +00002727 // If we're currently evaluating the initializer of this declaration, use that
2728 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002729 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002730 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002731 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002732 }
2733
Richard Smithcecf1842011-11-01 21:06:14 +00002734 // Never evaluate the initializer of a weak variable. We can't be sure that
2735 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002736 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002737 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002738 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002739 }
Richard Smithcecf1842011-11-01 21:06:14 +00002740
Richard Smithd0b4dd62011-12-19 06:19:21 +00002741 // Check that we can fold the initializer. In C++, we will have already done
2742 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002743 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002744 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002745 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002746 Notes.size() + 1) << VD;
2747 Info.Note(VD->getLocation(), diag::note_declared_at);
2748 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002749 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002750 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002751 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002752 Notes.size() + 1) << VD;
2753 Info.Note(VD->getLocation(), diag::note_declared_at);
2754 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002755 }
Richard Smith27908702011-10-24 17:54:18 +00002756
Richard Smith3229b742013-05-05 21:17:10 +00002757 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002758 return true;
Richard Smith27908702011-10-24 17:54:18 +00002759}
2760
Richard Smith11562c52011-10-28 17:51:58 +00002761static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002762 Qualifiers Quals = T.getQualifiers();
2763 return Quals.hasConst() && !Quals.hasVolatile();
2764}
2765
Richard Smithe97cbd72011-11-11 04:05:33 +00002766/// Get the base index of the given base class within an APValue representing
2767/// the given derived class.
2768static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2769 const CXXRecordDecl *Base) {
2770 Base = Base->getCanonicalDecl();
2771 unsigned Index = 0;
2772 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2773 E = Derived->bases_end(); I != E; ++I, ++Index) {
2774 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2775 return Index;
2776 }
2777
2778 llvm_unreachable("base class missing from derived class's bases list");
2779}
2780
Richard Smith3da88fa2013-04-26 14:36:30 +00002781/// Extract the value of a character from a string literal.
2782static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2783 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002784 assert(!isa<SourceLocExpr>(Lit) &&
2785 "SourceLocExpr should have already been converted to a StringLiteral");
2786
Akira Hatanakabc332642017-01-31 02:31:39 +00002787 // FIXME: Support MakeStringConstant
2788 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2789 std::string Str;
2790 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2791 assert(Index <= Str.size() && "Index too large");
2792 return APSInt::getUnsigned(Str.c_str()[Index]);
2793 }
2794
Alexey Bataevec474782014-10-09 08:45:04 +00002795 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2796 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002797 const StringLiteral *S = cast<StringLiteral>(Lit);
2798 const ConstantArrayType *CAT =
2799 Info.Ctx.getAsConstantArrayType(S->getType());
2800 assert(CAT && "string literal isn't an array");
2801 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002802 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002803
2804 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002805 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002806 if (Index < S->getLength())
2807 Value = S->getCodeUnit(Index);
2808 return Value;
2809}
2810
Richard Smith3da88fa2013-04-26 14:36:30 +00002811// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002812//
2813// FIXME: This is inefficient; we should probably introduce something similar
2814// to the LLVM ConstantDataArray to make this cheaper.
2815static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002816 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002817 const ConstantArrayType *CAT =
2818 Info.Ctx.getAsConstantArrayType(S->getType());
2819 assert(CAT && "string literal isn't an array");
2820 QualType CharType = CAT->getElementType();
2821 assert(CharType->isIntegerType() && "unexpected character type");
2822
2823 unsigned Elts = CAT->getSize().getZExtValue();
2824 Result = APValue(APValue::UninitArray(),
2825 std::min(S->getLength(), Elts), Elts);
2826 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2827 CharType->isUnsignedIntegerType());
2828 if (Result.hasArrayFiller())
2829 Result.getArrayFiller() = APValue(Value);
2830 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2831 Value = S->getCodeUnit(I);
2832 Result.getArrayInitializedElt(I) = APValue(Value);
2833 }
2834}
2835
2836// Expand an array so that it has more than Index filled elements.
2837static void expandArray(APValue &Array, unsigned Index) {
2838 unsigned Size = Array.getArraySize();
2839 assert(Index < Size);
2840
2841 // Always at least double the number of elements for which we store a value.
2842 unsigned OldElts = Array.getArrayInitializedElts();
2843 unsigned NewElts = std::max(Index+1, OldElts * 2);
2844 NewElts = std::min(Size, std::max(NewElts, 8u));
2845
2846 // Copy the data across.
2847 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2848 for (unsigned I = 0; I != OldElts; ++I)
2849 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2850 for (unsigned I = OldElts; I != NewElts; ++I)
2851 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2852 if (NewValue.hasArrayFiller())
2853 NewValue.getArrayFiller() = Array.getArrayFiller();
2854 Array.swap(NewValue);
2855}
2856
Richard Smithb01fe402014-09-16 01:24:02 +00002857/// Determine whether a type would actually be read by an lvalue-to-rvalue
2858/// conversion. If it's of class type, we may assume that the copy operation
2859/// is trivial. Note that this is never true for a union type with fields
2860/// (because the copy always "reads" the active member) and always true for
2861/// a non-class type.
2862static bool isReadByLvalueToRvalueConversion(QualType T) {
2863 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2864 if (!RD || (RD->isUnion() && !RD->field_empty()))
2865 return true;
2866 if (RD->isEmpty())
2867 return false;
2868
2869 for (auto *Field : RD->fields())
2870 if (isReadByLvalueToRvalueConversion(Field->getType()))
2871 return true;
2872
2873 for (auto &BaseSpec : RD->bases())
2874 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2875 return true;
2876
2877 return false;
2878}
2879
2880/// Diagnose an attempt to read from any unreadable field within the specified
2881/// type, which might be a class type.
2882static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2883 QualType T) {
2884 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2885 if (!RD)
2886 return false;
2887
2888 if (!RD->hasMutableFields())
2889 return false;
2890
2891 for (auto *Field : RD->fields()) {
2892 // If we're actually going to read this field in some way, then it can't
2893 // be mutable. If we're in a union, then assigning to a mutable field
2894 // (even an empty one) can change the active member, so that's not OK.
2895 // FIXME: Add core issue number for the union case.
2896 if (Field->isMutable() &&
2897 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002898 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002899 Info.Note(Field->getLocation(), diag::note_declared_at);
2900 return true;
2901 }
2902
2903 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2904 return true;
2905 }
2906
2907 for (auto &BaseSpec : RD->bases())
2908 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2909 return true;
2910
2911 // All mutable fields were empty, and thus not actually read.
2912 return false;
2913}
2914
Richard Smithdebad642019-05-12 09:39:08 +00002915static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2916 APValue::LValueBase Base) {
2917 // A temporary we created.
2918 if (Base.getCallIndex())
2919 return true;
2920
2921 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2922 if (!Evaluating)
2923 return false;
2924
2925 // The variable whose initializer we're evaluating.
2926 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2927 if (declaresSameEntity(Evaluating, BaseD))
2928 return true;
2929
2930 // A temporary lifetime-extended by the variable whose initializer we're
2931 // evaluating.
2932 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2933 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2934 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2935 return true;
2936
2937 return false;
2938}
2939
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002940namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002941/// A handle to a complete object (an object that is not a subobject of
2942/// another object).
2943struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002944 /// The identity of the object.
2945 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002946 /// The value of the complete object.
2947 APValue *Value;
2948 /// The type of the complete object.
2949 QualType Type;
2950
Craig Topper36250ad2014-05-12 05:36:57 +00002951 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002952 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2953 : Base(Base), Value(Value), Type(Type) {}
2954
2955 bool mayReadMutableMembers(EvalInfo &Info) const {
2956 // In C++14 onwards, it is permitted to read a mutable member whose
2957 // lifetime began within the evaluation.
2958 // FIXME: Should we also allow this in C++11?
2959 if (!Info.getLangOpts().CPlusPlus14)
2960 return false;
2961 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002962 }
2963
Richard Smithdebad642019-05-12 09:39:08 +00002964 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002965};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002966} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002967
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002968static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2969 bool IsMutable = false) {
2970 // C++ [basic.type.qualifier]p1:
2971 // - A const object is an object of type const T or a non-mutable subobject
2972 // of a const object.
2973 if (ObjType.isConstQualified() && !IsMutable)
2974 SubobjType.addConst();
2975 // - A volatile object is an object of type const T or a subobject of a
2976 // volatile object.
2977 if (ObjType.isVolatileQualified())
2978 SubobjType.addVolatile();
2979 return SubobjType;
2980}
2981
Richard Smith3da88fa2013-04-26 14:36:30 +00002982/// Find the designated sub-object of an rvalue.
2983template<typename SubobjectHandler>
2984typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002985findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002986 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002987 if (Sub.Invalid)
2988 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002989 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002990 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002991 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002992 Info.FFDiag(E, Sub.isOnePastTheEnd()
2993 ? diag::note_constexpr_access_past_end
2994 : diag::note_constexpr_access_unsized_array)
2995 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002996 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002997 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002998 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002999 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003000
Richard Smith3229b742013-05-05 21:17:10 +00003001 APValue *O = Obj.Value;
3002 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00003003 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003004 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003005
Richard Smithd62306a2011-11-10 06:34:14 +00003006 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003007 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003008 // Reading an indeterminate value is undefined, but assigning over one is OK.
3009 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003010 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003011 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003012 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003013 return handler.failed();
3014 }
3015
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003016 // C++ [class.ctor]p5:
3017 // const and volatile semantics are not applied on an object under
3018 // construction.
3019 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3020 ObjType->isRecordType() &&
3021 Info.isEvaluatingConstructor(
3022 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3023 Sub.Entries.begin() + I)) !=
3024 ConstructionPhase::None) {
3025 ObjType = Info.Ctx.getCanonicalType(ObjType);
3026 ObjType.removeLocalConst();
3027 ObjType.removeLocalVolatile();
3028 }
3029
3030 // If this is our last pass, check that the final object type is OK.
3031 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3032 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003033 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003034 if (Info.getLangOpts().CPlusPlus) {
3035 int DiagKind;
3036 SourceLocation Loc;
3037 const NamedDecl *Decl = nullptr;
3038 if (VolatileField) {
3039 DiagKind = 2;
3040 Loc = VolatileField->getLocation();
3041 Decl = VolatileField;
3042 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3043 DiagKind = 1;
3044 Loc = VD->getLocation();
3045 Decl = VD;
3046 } else {
3047 DiagKind = 0;
3048 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3049 Loc = E->getExprLoc();
3050 }
3051 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3052 << handler.AccessKind << DiagKind << Decl;
3053 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3054 } else {
3055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3056 }
3057 return handler.failed();
3058 }
3059
Richard Smithb01fe402014-09-16 01:24:02 +00003060 // If we are reading an object of class type, there may still be more
3061 // things we need to check: if there are any mutable subobjects, we
3062 // cannot perform this read. (This only happens when performing a trivial
3063 // copy or assignment.)
3064 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003065 !Obj.mayReadMutableMembers(Info) &&
3066 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003067 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003068 }
Richard Smithb01fe402014-09-16 01:24:02 +00003069
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003070 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003071 if (!handler.found(*O, ObjType))
3072 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003073
Richard Smith49ca8aa2013-08-06 07:09:20 +00003074 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003075 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003076 LastField && LastField->isBitField() &&
3077 !truncateBitfieldValue(Info, E, *O, LastField))
3078 return false;
3079
3080 return true;
3081 }
3082
Craig Topper36250ad2014-05-12 05:36:57 +00003083 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003084 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003085 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003086 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003087 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003088 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003089 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003090 // Note, it should not be possible to form a pointer with a valid
3091 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003092 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003093 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003094 << handler.AccessKind;
3095 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003096 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003097 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003098 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003099
3100 ObjType = CAT->getElementType();
3101
Richard Smith3da88fa2013-04-26 14:36:30 +00003102 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003103 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003104 else if (handler.AccessKind != AK_Read) {
3105 expandArray(*O, Index);
3106 O = &O->getArrayInitializedElt(Index);
3107 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003108 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003109 } else if (ObjType->isAnyComplexType()) {
3110 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003111 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003112 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003113 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003114 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003115 << handler.AccessKind;
3116 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003117 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003118 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003119 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003120
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003121 ObjType = getSubobjectType(
3122 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003123
Richard Smith66c96992012-02-18 22:04:06 +00003124 assert(I == N - 1 && "extracting subobject of scalar?");
3125 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003126 return handler.found(Index ? O->getComplexIntImag()
3127 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003128 } else {
3129 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003130 return handler.found(Index ? O->getComplexFloatImag()
3131 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003132 }
Richard Smithd62306a2011-11-10 06:34:14 +00003133 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003134 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003135 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003136 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003137 << Field;
3138 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003139 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003140 }
3141
Richard Smithd62306a2011-11-10 06:34:14 +00003142 // Next subobject is a class, struct or union field.
3143 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3144 if (RD->isUnion()) {
3145 const FieldDecl *UnionField = O->getUnionField();
3146 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003147 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003148 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003149 << handler.AccessKind << Field << !UnionField << UnionField;
3150 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003151 }
Richard Smithd62306a2011-11-10 06:34:14 +00003152 O = &O->getUnionValue();
3153 } else
3154 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003155
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003156 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003157 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003158 if (Field->getType().isVolatileQualified())
3159 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003160 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003161 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003162 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3163 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3164 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003165
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003166 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003167 }
3168 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003169}
3170
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003171namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003172struct ExtractSubobjectHandler {
3173 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003174 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003175
3176 static const AccessKinds AccessKind = AK_Read;
3177
3178 typedef bool result_type;
3179 bool failed() { return false; }
3180 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003181 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003182 return true;
3183 }
3184 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003185 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003186 return true;
3187 }
3188 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003189 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003190 return true;
3191 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003192};
Richard Smith3229b742013-05-05 21:17:10 +00003193} // end anonymous namespace
3194
Richard Smith3da88fa2013-04-26 14:36:30 +00003195const AccessKinds ExtractSubobjectHandler::AccessKind;
3196
3197/// Extract the designated sub-object of an rvalue.
3198static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003199 const CompleteObject &Obj,
3200 const SubobjectDesignator &Sub,
3201 APValue &Result) {
3202 ExtractSubobjectHandler Handler = { Info, Result };
3203 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003204}
3205
Richard Smith3229b742013-05-05 21:17:10 +00003206namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003207struct ModifySubobjectHandler {
3208 EvalInfo &Info;
3209 APValue &NewVal;
3210 const Expr *E;
3211
3212 typedef bool result_type;
3213 static const AccessKinds AccessKind = AK_Assign;
3214
3215 bool checkConst(QualType QT) {
3216 // Assigning to a const object has undefined behavior.
3217 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003219 return false;
3220 }
3221 return true;
3222 }
3223
3224 bool failed() { return false; }
3225 bool found(APValue &Subobj, QualType SubobjType) {
3226 if (!checkConst(SubobjType))
3227 return false;
3228 // We've been given ownership of NewVal, so just swap it in.
3229 Subobj.swap(NewVal);
3230 return true;
3231 }
3232 bool found(APSInt &Value, QualType SubobjType) {
3233 if (!checkConst(SubobjType))
3234 return false;
3235 if (!NewVal.isInt()) {
3236 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003237 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003238 return false;
3239 }
3240 Value = NewVal.getInt();
3241 return true;
3242 }
3243 bool found(APFloat &Value, QualType SubobjType) {
3244 if (!checkConst(SubobjType))
3245 return false;
3246 Value = NewVal.getFloat();
3247 return true;
3248 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003249};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003250} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003251
Richard Smith3229b742013-05-05 21:17:10 +00003252const AccessKinds ModifySubobjectHandler::AccessKind;
3253
Richard Smith3da88fa2013-04-26 14:36:30 +00003254/// Update the designated sub-object of an rvalue to the given value.
3255static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003256 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003257 const SubobjectDesignator &Sub,
3258 APValue &NewVal) {
3259 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003260 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003261}
3262
Richard Smith84f6dcf2012-02-02 01:16:57 +00003263/// Find the position where two subobject designators diverge, or equivalently
3264/// the length of the common initial subsequence.
3265static unsigned FindDesignatorMismatch(QualType ObjType,
3266 const SubobjectDesignator &A,
3267 const SubobjectDesignator &B,
3268 bool &WasArrayIndex) {
3269 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3270 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003271 if (!ObjType.isNull() &&
3272 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003273 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003274 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003275 WasArrayIndex = true;
3276 return I;
3277 }
Richard Smith66c96992012-02-18 22:04:06 +00003278 if (ObjType->isAnyComplexType())
3279 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3280 else
3281 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003282 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003283 if (A.Entries[I].getAsBaseOrMember() !=
3284 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003285 WasArrayIndex = false;
3286 return I;
3287 }
3288 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3289 // Next subobject is a field.
3290 ObjType = FD->getType();
3291 else
3292 // Next subobject is a base class.
3293 ObjType = QualType();
3294 }
3295 }
3296 WasArrayIndex = false;
3297 return I;
3298}
3299
3300/// Determine whether the given subobject designators refer to elements of the
3301/// same array object.
3302static bool AreElementsOfSameArray(QualType ObjType,
3303 const SubobjectDesignator &A,
3304 const SubobjectDesignator &B) {
3305 if (A.Entries.size() != B.Entries.size())
3306 return false;
3307
George Burgess IVa51c4072015-10-16 01:49:01 +00003308 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003309 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3310 // A is a subobject of the array element.
3311 return false;
3312
3313 // If A (and B) designates an array element, the last entry will be the array
3314 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3315 // of length 1' case, and the entire path must match.
3316 bool WasArrayIndex;
3317 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3318 return CommonLength >= A.Entries.size() - IsArray;
3319}
3320
Richard Smith3229b742013-05-05 21:17:10 +00003321/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003322static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3323 AccessKinds AK, const LValue &LVal,
3324 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003325 if (LVal.InvalidBase) {
3326 Info.FFDiag(E);
3327 return CompleteObject();
3328 }
3329
Richard Smith3229b742013-05-05 21:17:10 +00003330 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003331 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003332 return CompleteObject();
3333 }
3334
Craig Topper36250ad2014-05-12 05:36:57 +00003335 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003336 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003337 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003338 std::tie(Frame, Depth) =
3339 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003340 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003341 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003342 << AK << LVal.Base.is<const ValueDecl*>();
3343 NoteLValueLocation(Info, LVal.Base);
3344 return CompleteObject();
3345 }
Richard Smith3229b742013-05-05 21:17:10 +00003346 }
3347
Richard Smith7bd54ab2019-05-15 20:22:21 +00003348 bool IsAccess = isFormalAccess(AK);
3349
Richard Smith3229b742013-05-05 21:17:10 +00003350 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3351 // is not a constant expression (even if the object is non-volatile). We also
3352 // apply this rule to C++98, in order to conform to the expected 'volatile'
3353 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003354 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003355 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003356 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003357 << AK << LValType;
3358 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003359 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003360 return CompleteObject();
3361 }
3362
3363 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003364 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003365 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003366
3367 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3368 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3369 // In C++11, constexpr, non-volatile variables initialized with constant
3370 // expressions are constant expressions too. Inside constexpr functions,
3371 // parameters are constant expressions even if they're non-const.
3372 // In C++1y, objects local to a constant expression (those with a Frame) are
3373 // both readable and writable inside constant expressions.
3374 // In C, such things can also be folded, although they are not ICEs.
3375 const VarDecl *VD = dyn_cast<VarDecl>(D);
3376 if (VD) {
3377 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3378 VD = VDef;
3379 }
3380 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003381 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003382 return CompleteObject();
3383 }
3384
Richard Smith3229b742013-05-05 21:17:10 +00003385 // Unless we're looking at a local variable or argument in a constexpr call,
3386 // the variable we're reading must be const.
3387 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003388 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003389 declaresSameEntity(
3390 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003391 // OK, we can read and modify an object if we're in the process of
3392 // evaluating its initializer, because its lifetime began in this
3393 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003394 } else if (isModification(AK)) {
3395 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003396 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003397 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003398 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003399 // OK, we can read this variable.
3400 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003401 // In OpenCL if a variable is in constant address space it is a const
3402 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003403 if (!(BaseType.isConstQualified() ||
3404 (Info.getLangOpts().OpenCL &&
3405 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003406 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003407 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003408 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003409 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003410 Info.Note(VD->getLocation(), diag::note_declared_at);
3411 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003412 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003413 }
3414 return CompleteObject();
3415 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003416 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003417 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003418 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3419 // We support folding of const floating-point types, in order to make
3420 // static const data members of such types (supported as an extension)
3421 // more useful.
3422 if (Info.getLangOpts().CPlusPlus11) {
3423 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3424 Info.Note(VD->getLocation(), diag::note_declared_at);
3425 } else {
3426 Info.CCEDiag(E);
3427 }
George Burgess IVb5316982016-12-27 05:33:20 +00003428 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3429 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3430 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003431 } else {
3432 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003433 if (Info.checkingPotentialConstantExpression() &&
3434 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3435 // The definition of this variable could be constexpr. We can't
3436 // access it right now, but may be able to in future.
3437 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003438 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003439 Info.Note(VD->getLocation(), diag::note_declared_at);
3440 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003441 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003442 }
3443 return CompleteObject();
3444 }
3445 }
3446
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003447 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003448 return CompleteObject();
3449 } else {
3450 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3451
3452 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003453 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003454 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003455 assert(MTE->getStorageDuration() == SD_Static &&
3456 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003457
Richard Smithe6c01442013-06-05 00:46:14 +00003458 // Per C++1y [expr.const]p2:
3459 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3460 // - a [...] glvalue of integral or enumeration type that refers to
3461 // a non-volatile const object [...]
3462 // [...]
3463 // - a [...] glvalue of literal type that refers to a non-volatile
3464 // object whose lifetime began within the evaluation of e.
3465 //
3466 // C++11 misses the 'began within the evaluation of e' check and
3467 // instead allows all temporaries, including things like:
3468 // int &&r = 1;
3469 // int x = ++r;
3470 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003471 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003472 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3473 const ValueDecl *ED = MTE->getExtendingDecl();
3474 if (!(BaseType.isConstQualified() &&
3475 BaseType->isIntegralOrEnumerationType()) &&
3476 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003477 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003478 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003479 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003480 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3481 return CompleteObject();
3482 }
3483
3484 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3485 assert(BaseVal && "got reference to unevaluated temporary");
3486 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003487 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003488 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003489 APValue Val;
3490 LVal.moveInto(Val);
3491 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3492 << AK
3493 << Val.getAsString(Info.Ctx,
3494 Info.Ctx.getLValueReferenceType(LValType));
3495 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003496 return CompleteObject();
3497 }
3498 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003499 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003500 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003501 }
Richard Smith7525ff62013-05-09 07:14:00 +00003502 }
3503
Richard Smith9defb7d2018-02-21 03:38:30 +00003504 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003505 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003506 //
3507 // FIXME: Not all local state is mutable. Allow local constant subobjects
3508 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003509 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3510 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003511 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003512 return CompleteObject();
3513
Richard Smithdebad642019-05-12 09:39:08 +00003514 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003515}
3516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003517/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003518/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3519/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003520///
3521/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003522/// \param Conv - The expression for which we are performing the conversion.
3523/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003524/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3525/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003526/// \param LVal - The glvalue on which we are attempting to perform this action.
3527/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003528static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003529 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003530 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003531 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003532 return false;
3533
Richard Smith3229b742013-05-05 21:17:10 +00003534 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003535 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003536
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003537 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003538 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3539 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3540 // initializer until now for such expressions. Such an expression can't be
3541 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003542 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003543 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003544 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003545 }
Richard Smith3229b742013-05-05 21:17:10 +00003546 APValue Lit;
3547 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3548 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003549 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003550 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003551 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003552 // Special-case character extraction so we don't have to construct an
3553 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003554 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003555 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003556 if (LVal.Designator.Entries.empty()) {
3557 // Fail for now for LValue to RValue conversion of an array.
3558 // (This shouldn't show up in C/C++, but it could be triggered by a
3559 // weird EvaluateAsRValue call from a tool.)
3560 Info.FFDiag(Conv);
3561 return false;
3562 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003563 if (LVal.Designator.isOnePastTheEnd()) {
3564 if (Info.getLangOpts().CPlusPlus11)
3565 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3566 else
3567 Info.FFDiag(Conv);
3568 return false;
3569 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003570 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003571 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3572 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003573 }
Richard Smith11562c52011-10-28 17:51:58 +00003574 }
3575
Richard Smith3229b742013-05-05 21:17:10 +00003576 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3577 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003578}
3579
3580/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003581static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003582 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003583 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003584 return false;
3585
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003586 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003587 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003588 return false;
3589 }
3590
Richard Smith3229b742013-05-05 21:17:10 +00003591 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003592 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3593}
3594
3595namespace {
3596struct CompoundAssignSubobjectHandler {
3597 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003598 const Expr *E;
3599 QualType PromotedLHSType;
3600 BinaryOperatorKind Opcode;
3601 const APValue &RHS;
3602
3603 static const AccessKinds AccessKind = AK_Assign;
3604
3605 typedef bool result_type;
3606
3607 bool checkConst(QualType QT) {
3608 // Assigning to a const object has undefined behavior.
3609 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003610 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003611 return false;
3612 }
3613 return true;
3614 }
3615
3616 bool failed() { return false; }
3617 bool found(APValue &Subobj, QualType SubobjType) {
3618 switch (Subobj.getKind()) {
3619 case APValue::Int:
3620 return found(Subobj.getInt(), SubobjType);
3621 case APValue::Float:
3622 return found(Subobj.getFloat(), SubobjType);
3623 case APValue::ComplexInt:
3624 case APValue::ComplexFloat:
3625 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003626 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003627 return false;
3628 case APValue::LValue:
3629 return foundPointer(Subobj, SubobjType);
3630 default:
3631 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003632 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003633 return false;
3634 }
3635 }
3636 bool found(APSInt &Value, QualType SubobjType) {
3637 if (!checkConst(SubobjType))
3638 return false;
3639
Tan S. B.9f935e82018-12-18 07:38:06 +00003640 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003641 // We don't support compound assignment on integer-cast-to-pointer
3642 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003643 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003644 return false;
3645 }
3646
Tan S. B.9f935e82018-12-18 07:38:06 +00003647 if (RHS.isInt()) {
3648 APSInt LHS =
3649 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3650 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3651 return false;
3652 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3653 return true;
3654 } else if (RHS.isFloat()) {
3655 APFloat FValue(0.0);
3656 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3657 FValue) &&
3658 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3659 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3660 Value);
3661 }
3662
3663 Info.FFDiag(E);
3664 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003665 }
3666 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003667 return checkConst(SubobjType) &&
3668 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3669 Value) &&
3670 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3671 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003672 }
3673 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3674 if (!checkConst(SubobjType))
3675 return false;
3676
3677 QualType PointeeType;
3678 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3679 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003680
3681 if (PointeeType.isNull() || !RHS.isInt() ||
3682 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003683 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003684 return false;
3685 }
3686
Richard Smithd6cc1982017-01-31 02:23:02 +00003687 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003688 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003689 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003690
3691 LValue LVal;
3692 LVal.setFrom(Info.Ctx, Subobj);
3693 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3694 return false;
3695 LVal.moveInto(Subobj);
3696 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003697 }
Richard Smith43e77732013-05-07 04:50:00 +00003698};
3699} // end anonymous namespace
3700
3701const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3702
3703/// Perform a compound assignment of LVal <op>= RVal.
3704static bool handleCompoundAssignment(
3705 EvalInfo &Info, const Expr *E,
3706 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3707 BinaryOperatorKind Opcode, const APValue &RVal) {
3708 if (LVal.Designator.Invalid)
3709 return false;
3710
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003711 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003712 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003713 return false;
3714 }
3715
3716 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3717 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3718 RVal };
3719 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3720}
3721
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003722namespace {
3723struct IncDecSubobjectHandler {
3724 EvalInfo &Info;
3725 const UnaryOperator *E;
3726 AccessKinds AccessKind;
3727 APValue *Old;
3728
Richard Smith243ef902013-05-05 23:31:59 +00003729 typedef bool result_type;
3730
3731 bool checkConst(QualType QT) {
3732 // Assigning to a const object has undefined behavior.
3733 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003734 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003735 return false;
3736 }
3737 return true;
3738 }
3739
3740 bool failed() { return false; }
3741 bool found(APValue &Subobj, QualType SubobjType) {
3742 // Stash the old value. Also clear Old, so we don't clobber it later
3743 // if we're post-incrementing a complex.
3744 if (Old) {
3745 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003746 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003747 }
3748
3749 switch (Subobj.getKind()) {
3750 case APValue::Int:
3751 return found(Subobj.getInt(), SubobjType);
3752 case APValue::Float:
3753 return found(Subobj.getFloat(), SubobjType);
3754 case APValue::ComplexInt:
3755 return found(Subobj.getComplexIntReal(),
3756 SubobjType->castAs<ComplexType>()->getElementType()
3757 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3758 case APValue::ComplexFloat:
3759 return found(Subobj.getComplexFloatReal(),
3760 SubobjType->castAs<ComplexType>()->getElementType()
3761 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3762 case APValue::LValue:
3763 return foundPointer(Subobj, SubobjType);
3764 default:
3765 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003766 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003767 return false;
3768 }
3769 }
3770 bool found(APSInt &Value, QualType SubobjType) {
3771 if (!checkConst(SubobjType))
3772 return false;
3773
3774 if (!SubobjType->isIntegerType()) {
3775 // We don't support increment / decrement on integer-cast-to-pointer
3776 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003777 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003778 return false;
3779 }
3780
3781 if (Old) *Old = APValue(Value);
3782
3783 // bool arithmetic promotes to int, and the conversion back to bool
3784 // doesn't reduce mod 2^n, so special-case it.
3785 if (SubobjType->isBooleanType()) {
3786 if (AccessKind == AK_Increment)
3787 Value = 1;
3788 else
3789 Value = !Value;
3790 return true;
3791 }
3792
3793 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003794 if (AccessKind == AK_Increment) {
3795 ++Value;
3796
3797 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3798 APSInt ActualValue(Value, /*IsUnsigned*/true);
3799 return HandleOverflow(Info, E, ActualValue, SubobjType);
3800 }
3801 } else {
3802 --Value;
3803
3804 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3805 unsigned BitWidth = Value.getBitWidth();
3806 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3807 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003808 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003809 }
3810 }
3811 return true;
3812 }
3813 bool found(APFloat &Value, QualType SubobjType) {
3814 if (!checkConst(SubobjType))
3815 return false;
3816
3817 if (Old) *Old = APValue(Value);
3818
3819 APFloat One(Value.getSemantics(), 1);
3820 if (AccessKind == AK_Increment)
3821 Value.add(One, APFloat::rmNearestTiesToEven);
3822 else
3823 Value.subtract(One, APFloat::rmNearestTiesToEven);
3824 return true;
3825 }
3826 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3827 if (!checkConst(SubobjType))
3828 return false;
3829
3830 QualType PointeeType;
3831 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3832 PointeeType = PT->getPointeeType();
3833 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003834 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003835 return false;
3836 }
3837
3838 LValue LVal;
3839 LVal.setFrom(Info.Ctx, Subobj);
3840 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3841 AccessKind == AK_Increment ? 1 : -1))
3842 return false;
3843 LVal.moveInto(Subobj);
3844 return true;
3845 }
Richard Smith243ef902013-05-05 23:31:59 +00003846};
3847} // end anonymous namespace
3848
3849/// Perform an increment or decrement on LVal.
3850static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3851 QualType LValType, bool IsIncrement, APValue *Old) {
3852 if (LVal.Designator.Invalid)
3853 return false;
3854
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003855 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003856 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003857 return false;
3858 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003859
3860 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3861 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3862 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3863 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3864}
3865
Richard Smithe97cbd72011-11-11 04:05:33 +00003866/// Build an lvalue for the object argument of a member function call.
3867static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3868 LValue &This) {
3869 if (Object->getType()->isPointerType())
3870 return EvaluatePointer(Object, This, Info);
3871
3872 if (Object->isGLValue())
3873 return EvaluateLValue(Object, This, Info);
3874
Richard Smithd9f663b2013-04-22 15:31:51 +00003875 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003876 return EvaluateTemporary(Object, This, Info);
3877
Faisal Valie690b7a2016-07-02 22:34:24 +00003878 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003879 return false;
3880}
3881
3882/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3883/// lvalue referring to the result.
3884///
3885/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003886/// \param LV - An lvalue referring to the base of the member pointer.
3887/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003888/// \param IncludeMember - Specifies whether the member itself is included in
3889/// the resulting LValue subobject designator. This is not possible when
3890/// creating a bound member function.
3891/// \return The field or method declaration to which the member pointer refers,
3892/// or 0 if evaluation fails.
3893static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003894 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003895 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003896 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003897 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003898 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003899 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003900 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003901
3902 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3903 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003904 if (!MemPtr.getDecl()) {
3905 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003906 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003907 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003908 }
Richard Smith253c2a32012-01-27 01:14:48 +00003909
Richard Smith027bf112011-11-17 22:56:20 +00003910 if (MemPtr.isDerivedMember()) {
3911 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003912 // The end of the derived-to-base path for the base object must match the
3913 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003914 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003915 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003916 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003917 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003918 }
Richard Smith027bf112011-11-17 22:56:20 +00003919 unsigned PathLengthToMember =
3920 LV.Designator.Entries.size() - MemPtr.Path.size();
3921 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3922 const CXXRecordDecl *LVDecl = getAsBaseClass(
3923 LV.Designator.Entries[PathLengthToMember + I]);
3924 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003925 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003926 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003927 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003928 }
Richard Smith027bf112011-11-17 22:56:20 +00003929 }
3930
3931 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003932 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003933 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003934 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003935 } else if (!MemPtr.Path.empty()) {
3936 // Extend the LValue path with the member pointer's path.
3937 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3938 MemPtr.Path.size() + IncludeMember);
3939
3940 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003941 if (const PointerType *PT = LVType->getAs<PointerType>())
3942 LVType = PT->getPointeeType();
3943 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3944 assert(RD && "member pointer access on non-class-type expression");
3945 // The first class in the path is that of the lvalue.
3946 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3947 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003948 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003949 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003950 RD = Base;
3951 }
3952 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003953 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3954 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003955 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003956 }
3957
3958 // Add the member. Note that we cannot build bound member functions here.
3959 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003960 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003961 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003962 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003963 } else if (const IndirectFieldDecl *IFD =
3964 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003965 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003966 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003967 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003968 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003969 }
Richard Smith027bf112011-11-17 22:56:20 +00003970 }
3971
3972 return MemPtr.getDecl();
3973}
3974
Richard Smith84401042013-06-03 05:03:02 +00003975static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3976 const BinaryOperator *BO,
3977 LValue &LV,
3978 bool IncludeMember = true) {
3979 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3980
3981 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003982 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003983 MemberPtr MemPtr;
3984 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3985 }
Craig Topper36250ad2014-05-12 05:36:57 +00003986 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003987 }
3988
3989 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3990 BO->getRHS(), IncludeMember);
3991}
3992
Richard Smith027bf112011-11-17 22:56:20 +00003993/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3994/// the provided lvalue, which currently refers to the base object.
3995static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3996 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003997 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003998 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003999 return false;
4000
Richard Smitha8105bc2012-01-06 16:39:00 +00004001 QualType TargetQT = E->getType();
4002 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4003 TargetQT = PT->getPointeeType();
4004
4005 // Check this cast lands within the final derived-to-base subobject path.
4006 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004007 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004008 << D.MostDerivedType << TargetQT;
4009 return false;
4010 }
4011
Richard Smith027bf112011-11-17 22:56:20 +00004012 // Check the type of the final cast. We don't need to check the path,
4013 // since a cast can only be formed if the path is unique.
4014 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004015 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4016 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004017 if (NewEntriesSize == D.MostDerivedPathLength)
4018 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4019 else
Richard Smith027bf112011-11-17 22:56:20 +00004020 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004021 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004022 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004023 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004024 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004025 }
Richard Smith027bf112011-11-17 22:56:20 +00004026
4027 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004028 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004029}
4030
Mike Stump876387b2009-10-27 22:09:17 +00004031namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004032enum EvalStmtResult {
4033 /// Evaluation failed.
4034 ESR_Failed,
4035 /// Hit a 'return' statement.
4036 ESR_Returned,
4037 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004038 ESR_Succeeded,
4039 /// Hit a 'continue' statement.
4040 ESR_Continue,
4041 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004042 ESR_Break,
4043 /// Still scanning for 'case' or 'default' statement.
4044 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004045};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004046}
Richard Smith254a73d2011-10-28 22:34:42 +00004047
Richard Smith97fcf4b2016-08-14 23:15:52 +00004048static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4049 // We don't need to evaluate the initializer for a static local.
4050 if (!VD->hasLocalStorage())
4051 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004052
Richard Smith97fcf4b2016-08-14 23:15:52 +00004053 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004054 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00004055
Richard Smith97fcf4b2016-08-14 23:15:52 +00004056 const Expr *InitE = VD->getInit();
4057 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004058 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4059 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00004060 Val = APValue();
4061 return false;
4062 }
Richard Smith51f03172013-06-20 03:00:05 +00004063
Richard Smith97fcf4b2016-08-14 23:15:52 +00004064 if (InitE->isValueDependent())
4065 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004066
Richard Smith97fcf4b2016-08-14 23:15:52 +00004067 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4068 // Wipe out any partially-computed value, to allow tracking that this
4069 // evaluation failed.
4070 Val = APValue();
4071 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004072 }
4073
4074 return true;
4075}
4076
Richard Smith97fcf4b2016-08-14 23:15:52 +00004077static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4078 bool OK = true;
4079
4080 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4081 OK &= EvaluateVarDecl(Info, VD);
4082
4083 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4084 for (auto *BD : DD->bindings())
4085 if (auto *VD = BD->getHoldingVar())
4086 OK &= EvaluateDecl(Info, VD);
4087
4088 return OK;
4089}
4090
4091
Richard Smith4e18ca52013-05-06 05:56:11 +00004092/// Evaluate a condition (either a variable declaration or an expression).
4093static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4094 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004095 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004096 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4097 return false;
4098 return EvaluateAsBooleanCondition(Cond, Result, Info);
4099}
4100
Richard Smith89210072016-04-04 23:29:43 +00004101namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004102/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004103/// statement should be stored.
4104struct StmtResult {
4105 /// The APValue that should be filled in with the returned value.
4106 APValue &Value;
4107 /// The location containing the result, if any (used to support RVO).
4108 const LValue *Slot;
4109};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004110
4111struct TempVersionRAII {
4112 CallStackFrame &Frame;
4113
4114 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4115 Frame.pushTempVersion();
4116 }
4117
4118 ~TempVersionRAII() {
4119 Frame.popTempVersion();
4120 }
4121};
4122
Richard Smith89210072016-04-04 23:29:43 +00004123}
Richard Smith52a980a2015-08-28 02:43:42 +00004124
4125static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004126 const Stmt *S,
4127 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004128
4129/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004130static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004131 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004132 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004133 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004134 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004135 case ESR_Break:
4136 return ESR_Succeeded;
4137 case ESR_Succeeded:
4138 case ESR_Continue:
4139 return ESR_Continue;
4140 case ESR_Failed:
4141 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004142 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004143 return ESR;
4144 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004145 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004146}
4147
Richard Smith496ddcf2013-05-12 17:32:42 +00004148/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004149static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004150 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004151 BlockScopeRAII Scope(Info);
4152
Richard Smith496ddcf2013-05-12 17:32:42 +00004153 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004154 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004155 {
4156 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004157 if (const Stmt *Init = SS->getInit()) {
4158 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4159 if (ESR != ESR_Succeeded)
4160 return ESR;
4161 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004162 if (SS->getConditionVariable() &&
4163 !EvaluateDecl(Info, SS->getConditionVariable()))
4164 return ESR_Failed;
4165 if (!EvaluateInteger(SS->getCond(), Value, Info))
4166 return ESR_Failed;
4167 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004168
4169 // Find the switch case corresponding to the value of the condition.
4170 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004171 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004172 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4173 SC = SC->getNextSwitchCase()) {
4174 if (isa<DefaultStmt>(SC)) {
4175 Found = SC;
4176 continue;
4177 }
4178
4179 const CaseStmt *CS = cast<CaseStmt>(SC);
4180 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4181 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4182 : LHS;
4183 if (LHS <= Value && Value <= RHS) {
4184 Found = SC;
4185 break;
4186 }
4187 }
4188
4189 if (!Found)
4190 return ESR_Succeeded;
4191
4192 // Search the switch body for the switch case and evaluate it from there.
4193 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4194 case ESR_Break:
4195 return ESR_Succeeded;
4196 case ESR_Succeeded:
4197 case ESR_Continue:
4198 case ESR_Failed:
4199 case ESR_Returned:
4200 return ESR;
4201 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004202 // This can only happen if the switch case is nested within a statement
4203 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004204 Info.FFDiag(Found->getBeginLoc(),
4205 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004206 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004207 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004208 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004209}
4210
Richard Smith254a73d2011-10-28 22:34:42 +00004211// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004212static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004213 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004214 if (!Info.nextStep(S))
4215 return ESR_Failed;
4216
Richard Smith496ddcf2013-05-12 17:32:42 +00004217 // If we're hunting down a 'case' or 'default' label, recurse through
4218 // substatements until we hit the label.
4219 if (Case) {
4220 // FIXME: We don't start the lifetime of objects whose initialization we
4221 // jump over. However, such objects must be of class type with a trivial
4222 // default constructor that initialize all subobjects, so must be empty,
4223 // so this almost never matters.
4224 switch (S->getStmtClass()) {
4225 case Stmt::CompoundStmtClass:
4226 // FIXME: Precompute which substatement of a compound statement we
4227 // would jump to, and go straight there rather than performing a
4228 // linear scan each time.
4229 case Stmt::LabelStmtClass:
4230 case Stmt::AttributedStmtClass:
4231 case Stmt::DoStmtClass:
4232 break;
4233
4234 case Stmt::CaseStmtClass:
4235 case Stmt::DefaultStmtClass:
4236 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004237 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004238 break;
4239
4240 case Stmt::IfStmtClass: {
4241 // FIXME: Precompute which side of an 'if' we would jump to, and go
4242 // straight there rather than scanning both sides.
4243 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004244
4245 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4246 // preceded by our switch label.
4247 BlockScopeRAII Scope(Info);
4248
Richard Smith496ddcf2013-05-12 17:32:42 +00004249 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4250 if (ESR != ESR_CaseNotFound || !IS->getElse())
4251 return ESR;
4252 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4253 }
4254
4255 case Stmt::WhileStmtClass: {
4256 EvalStmtResult ESR =
4257 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4258 if (ESR != ESR_Continue)
4259 return ESR;
4260 break;
4261 }
4262
4263 case Stmt::ForStmtClass: {
4264 const ForStmt *FS = cast<ForStmt>(S);
4265 EvalStmtResult ESR =
4266 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4267 if (ESR != ESR_Continue)
4268 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004269 if (FS->getInc()) {
4270 FullExpressionRAII IncScope(Info);
4271 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4272 return ESR_Failed;
4273 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004274 break;
4275 }
4276
4277 case Stmt::DeclStmtClass:
4278 // FIXME: If the variable has initialization that can't be jumped over,
4279 // bail out of any immediately-surrounding compound-statement too.
4280 default:
4281 return ESR_CaseNotFound;
4282 }
4283 }
4284
Richard Smith254a73d2011-10-28 22:34:42 +00004285 switch (S->getStmtClass()) {
4286 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004287 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004288 // Don't bother evaluating beyond an expression-statement which couldn't
4289 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004290 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004291 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004292 return ESR_Failed;
4293 return ESR_Succeeded;
4294 }
4295
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004296 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004297 return ESR_Failed;
4298
4299 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004300 return ESR_Succeeded;
4301
Richard Smithd9f663b2013-04-22 15:31:51 +00004302 case Stmt::DeclStmtClass: {
4303 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004304 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004305 // Each declaration initialization is its own full-expression.
4306 // FIXME: This isn't quite right; if we're performing aggregate
4307 // initialization, each braced subexpression is its own full-expression.
4308 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004309 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004310 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004311 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004312 return ESR_Succeeded;
4313 }
4314
Richard Smith357362d2011-12-13 06:39:58 +00004315 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004316 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004317 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004318 if (RetExpr &&
4319 !(Result.Slot
4320 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4321 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004322 return ESR_Failed;
4323 return ESR_Returned;
4324 }
Richard Smith254a73d2011-10-28 22:34:42 +00004325
4326 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004327 BlockScopeRAII Scope(Info);
4328
Richard Smith254a73d2011-10-28 22:34:42 +00004329 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004330 for (const auto *BI : CS->body()) {
4331 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004332 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004333 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004334 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004335 return ESR;
4336 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004337 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004338 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004339
4340 case Stmt::IfStmtClass: {
4341 const IfStmt *IS = cast<IfStmt>(S);
4342
4343 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004344 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004345 if (const Stmt *Init = IS->getInit()) {
4346 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4347 if (ESR != ESR_Succeeded)
4348 return ESR;
4349 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004350 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004351 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004352 return ESR_Failed;
4353
4354 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4355 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4356 if (ESR != ESR_Succeeded)
4357 return ESR;
4358 }
4359 return ESR_Succeeded;
4360 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004361
4362 case Stmt::WhileStmtClass: {
4363 const WhileStmt *WS = cast<WhileStmt>(S);
4364 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004365 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004366 bool Continue;
4367 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4368 Continue))
4369 return ESR_Failed;
4370 if (!Continue)
4371 break;
4372
4373 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4374 if (ESR != ESR_Continue)
4375 return ESR;
4376 }
4377 return ESR_Succeeded;
4378 }
4379
4380 case Stmt::DoStmtClass: {
4381 const DoStmt *DS = cast<DoStmt>(S);
4382 bool Continue;
4383 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004384 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004385 if (ESR != ESR_Continue)
4386 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004387 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004388
Richard Smith08d6a2c2013-07-24 07:11:57 +00004389 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004390 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4391 return ESR_Failed;
4392 } while (Continue);
4393 return ESR_Succeeded;
4394 }
4395
4396 case Stmt::ForStmtClass: {
4397 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004398 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004399 if (FS->getInit()) {
4400 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4401 if (ESR != ESR_Succeeded)
4402 return ESR;
4403 }
4404 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004405 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004406 bool Continue = true;
4407 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4408 FS->getCond(), Continue))
4409 return ESR_Failed;
4410 if (!Continue)
4411 break;
4412
4413 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4414 if (ESR != ESR_Continue)
4415 return ESR;
4416
Richard Smith08d6a2c2013-07-24 07:11:57 +00004417 if (FS->getInc()) {
4418 FullExpressionRAII IncScope(Info);
4419 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4420 return ESR_Failed;
4421 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004422 }
4423 return ESR_Succeeded;
4424 }
4425
Richard Smith896e0d72013-05-06 06:51:17 +00004426 case Stmt::CXXForRangeStmtClass: {
4427 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004428 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004429
Richard Smith8baa5002018-09-28 18:44:09 +00004430 // Evaluate the init-statement if present.
4431 if (FS->getInit()) {
4432 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4433 if (ESR != ESR_Succeeded)
4434 return ESR;
4435 }
4436
Richard Smith896e0d72013-05-06 06:51:17 +00004437 // Initialize the __range variable.
4438 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4439 if (ESR != ESR_Succeeded)
4440 return ESR;
4441
4442 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004443 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4444 if (ESR != ESR_Succeeded)
4445 return ESR;
4446 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004447 if (ESR != ESR_Succeeded)
4448 return ESR;
4449
4450 while (true) {
4451 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004452 {
4453 bool Continue = true;
4454 FullExpressionRAII CondExpr(Info);
4455 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4456 return ESR_Failed;
4457 if (!Continue)
4458 break;
4459 }
Richard Smith896e0d72013-05-06 06:51:17 +00004460
4461 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004462 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004463 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4464 if (ESR != ESR_Succeeded)
4465 return ESR;
4466
4467 // Loop body.
4468 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4469 if (ESR != ESR_Continue)
4470 return ESR;
4471
4472 // Increment: ++__begin
4473 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4474 return ESR_Failed;
4475 }
4476
4477 return ESR_Succeeded;
4478 }
4479
Richard Smith496ddcf2013-05-12 17:32:42 +00004480 case Stmt::SwitchStmtClass:
4481 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4482
Richard Smith4e18ca52013-05-06 05:56:11 +00004483 case Stmt::ContinueStmtClass:
4484 return ESR_Continue;
4485
4486 case Stmt::BreakStmtClass:
4487 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004488
4489 case Stmt::LabelStmtClass:
4490 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4491
4492 case Stmt::AttributedStmtClass:
4493 // As a general principle, C++11 attributes can be ignored without
4494 // any semantic impact.
4495 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4496 Case);
4497
4498 case Stmt::CaseStmtClass:
4499 case Stmt::DefaultStmtClass:
4500 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004501 case Stmt::CXXTryStmtClass:
4502 // Evaluate try blocks by evaluating all sub statements.
4503 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004504 }
4505}
4506
Richard Smithcc36f692011-12-22 02:22:31 +00004507/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4508/// default constructor. If so, we'll fold it whether or not it's marked as
4509/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4510/// so we need special handling.
4511static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004512 const CXXConstructorDecl *CD,
4513 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004514 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4515 return false;
4516
Richard Smith66e05fe2012-01-18 05:21:49 +00004517 // Value-initialization does not call a trivial default constructor, so such a
4518 // call is a core constant expression whether or not the constructor is
4519 // constexpr.
4520 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004521 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004522 // FIXME: If DiagDecl is an implicitly-declared special member function,
4523 // we should be much more explicit about why it's not constexpr.
4524 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4525 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4526 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004527 } else {
4528 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4529 }
4530 }
4531 return true;
4532}
4533
Richard Smith357362d2011-12-13 06:39:58 +00004534/// CheckConstexprFunction - Check that a function can be called in a constant
4535/// expression.
4536static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4537 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004538 const FunctionDecl *Definition,
4539 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004540 // Potential constant expressions can contain calls to declared, but not yet
4541 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004542 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004543 Declaration->isConstexpr())
4544 return false;
4545
James Y Knightc7d3e602018-10-05 17:49:48 +00004546 // Bail out if the function declaration itself is invalid. We will
4547 // have produced a relevant diagnostic while parsing it, so just
4548 // note the problematic sub-expression.
4549 if (Declaration->isInvalidDecl()) {
4550 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004551 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004552 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004553
Richard Smithd9c6b032019-05-09 19:45:49 +00004554 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004555 // constant expression (prior to C++20). We can still constant-fold such a
4556 // call.
4557 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4558 cast<CXXMethodDecl>(Declaration)->isVirtual())
4559 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4560
4561 if (Definition && Definition->isInvalidDecl()) {
4562 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004563 return false;
4564 }
4565
Richard Smith357362d2011-12-13 06:39:58 +00004566 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004567 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004568 return true;
4569
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004570 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004571 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004572
Richard Smith5179eb72016-06-28 19:03:57 +00004573 // If this function is not constexpr because it is an inherited
4574 // non-constexpr constructor, diagnose that directly.
4575 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4576 if (CD && CD->isInheritingConstructor()) {
4577 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004578 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004579 DiagDecl = CD = Inherited;
4580 }
4581
4582 // FIXME: If DiagDecl is an implicitly-declared special member function
4583 // or an inheriting constructor, we should be much more explicit about why
4584 // it's not constexpr.
4585 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004586 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004587 << CD->getInheritedConstructor().getConstructor()->getParent();
4588 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004589 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004590 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004591 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4592 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004593 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004594 }
4595 return false;
4596}
4597
Richard Smithdebad642019-05-12 09:39:08 +00004598namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004599struct CheckDynamicTypeHandler {
4600 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004601 typedef bool result_type;
4602 bool failed() { return false; }
4603 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4604 bool found(APSInt &Value, QualType SubobjType) { return true; }
4605 bool found(APFloat &Value, QualType SubobjType) { return true; }
4606};
4607} // end anonymous namespace
4608
Richard Smith7bd54ab2019-05-15 20:22:21 +00004609/// Check that we can access the notional vptr of an object / determine its
4610/// dynamic type.
4611static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4612 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004613 if (This.Designator.Invalid)
4614 return false;
4615
Richard Smith7bd54ab2019-05-15 20:22:21 +00004616 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004617
4618 if (!Obj)
4619 return false;
4620
4621 if (!Obj.Value) {
4622 // The object is not usable in constant expressions, so we can't inspect
4623 // its value to see if it's in-lifetime or what the active union members
4624 // are. We can still check for a one-past-the-end lvalue.
4625 if (This.Designator.isOnePastTheEnd() ||
4626 This.Designator.isMostDerivedAnUnsizedArray()) {
4627 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4628 ? diag::note_constexpr_access_past_end
4629 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004630 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004631 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004632 } else if (Polymorphic) {
4633 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004634 // not be able to read a notional 'vptr' value.
4635 APValue Val;
4636 This.moveInto(Val);
4637 QualType StarThisType =
4638 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004639 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4640 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004641 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004642 }
4643 return true;
4644 }
4645
Richard Smith7bd54ab2019-05-15 20:22:21 +00004646 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004647 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4648}
4649
Richard Smith7bd54ab2019-05-15 20:22:21 +00004650/// Check that the pointee of the 'this' pointer in a member function call is
4651/// either within its lifetime or in its period of construction or destruction.
4652static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4653 const LValue &This) {
4654 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4655}
4656
Richard Smith921f1322019-05-13 23:35:21 +00004657struct DynamicType {
4658 /// The dynamic class type of the object.
4659 const CXXRecordDecl *Type;
4660 /// The corresponding path length in the lvalue.
4661 unsigned PathLength;
4662};
4663
4664static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4665 unsigned PathLength) {
4666 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4667 Designator.Entries.size() && "invalid path length");
4668 return (PathLength == Designator.MostDerivedPathLength)
4669 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4670 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4671}
4672
4673/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004674static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4675 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004676 // If we don't have an lvalue denoting an object of class type, there is no
4677 // meaningful dynamic type. (We consider objects of non-class type to have no
4678 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004679 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004680 return None;
4681
Richard Smith7bd54ab2019-05-15 20:22:21 +00004682 // Refuse to compute a dynamic type in the presence of virtual bases. This
4683 // shouldn't happen other than in constant-folding situations, since literal
4684 // types can't have virtual bases.
4685 //
4686 // Note that consumers of DynamicType assume that the type has no virtual
4687 // bases, and will need modifications if this restriction is relaxed.
4688 const CXXRecordDecl *Class =
4689 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4690 if (!Class || Class->getNumVBases()) {
4691 Info.FFDiag(E);
4692 return None;
4693 }
4694
Richard Smith921f1322019-05-13 23:35:21 +00004695 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4696 // binary search here instead. But the overwhelmingly common case is that
4697 // we're not in the middle of a constructor, so it probably doesn't matter
4698 // in practice.
4699 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4700 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4701 PathLength <= Path.size(); ++PathLength) {
4702 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4703 Path.slice(0, PathLength))) {
4704 case ConstructionPhase::Bases:
4705 // We're constructing a base class. This is not the dynamic type.
4706 break;
4707
4708 case ConstructionPhase::None:
4709 case ConstructionPhase::AfterBases:
4710 // We've finished constructing the base classes, so this is the dynamic
4711 // type.
4712 return DynamicType{getBaseClassType(This.Designator, PathLength),
4713 PathLength};
4714 }
4715 }
4716
4717 // CWG issue 1517: we're constructing a base class of the object described by
4718 // 'This', so that object has not yet begun its period of construction and
4719 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004720 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004721 return None;
4722}
4723
4724/// Perform virtual dispatch.
4725static const CXXMethodDecl *HandleVirtualDispatch(
4726 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4727 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004728 Optional<DynamicType> DynType =
4729 ComputeDynamicType(Info, E, This, AK_MemberCall);
4730 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004731 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004732
4733 // Find the final overrider. It must be declared in one of the classes on the
4734 // path from the dynamic type to the static type.
4735 // FIXME: If we ever allow literal types to have virtual base classes, that
4736 // won't be true.
4737 const CXXMethodDecl *Callee = Found;
4738 unsigned PathLength = DynType->PathLength;
4739 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4740 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004741 const CXXMethodDecl *Overrider =
4742 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4743 if (Overrider) {
4744 Callee = Overrider;
4745 break;
4746 }
4747 }
4748
4749 // C++2a [class.abstract]p6:
4750 // the effect of making a virtual call to a pure virtual function [...] is
4751 // undefined
4752 if (Callee->isPure()) {
4753 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4754 Info.Note(Callee->getLocation(), diag::note_declared_at);
4755 return nullptr;
4756 }
4757
4758 // If necessary, walk the rest of the path to determine the sequence of
4759 // covariant adjustment steps to apply.
4760 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4761 Found->getReturnType())) {
4762 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4763 for (unsigned CovariantPathLength = PathLength + 1;
4764 CovariantPathLength != This.Designator.Entries.size();
4765 ++CovariantPathLength) {
4766 const CXXRecordDecl *NextClass =
4767 getBaseClassType(This.Designator, CovariantPathLength);
4768 const CXXMethodDecl *Next =
4769 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4770 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4771 Next->getReturnType(), CovariantAdjustmentPath.back()))
4772 CovariantAdjustmentPath.push_back(Next->getReturnType());
4773 }
4774 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4775 CovariantAdjustmentPath.back()))
4776 CovariantAdjustmentPath.push_back(Found->getReturnType());
4777 }
4778
4779 // Perform 'this' adjustment.
4780 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4781 return nullptr;
4782
4783 return Callee;
4784}
4785
4786/// Perform the adjustment from a value returned by a virtual function to
4787/// a value of the statically expected type, which may be a pointer or
4788/// reference to a base class of the returned type.
4789static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4790 APValue &Result,
4791 ArrayRef<QualType> Path) {
4792 assert(Result.isLValue() &&
4793 "unexpected kind of APValue for covariant return");
4794 if (Result.isNullPointer())
4795 return true;
4796
4797 LValue LVal;
4798 LVal.setFrom(Info.Ctx, Result);
4799
4800 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4801 for (unsigned I = 1; I != Path.size(); ++I) {
4802 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4803 assert(OldClass && NewClass && "unexpected kind of covariant return");
4804 if (OldClass != NewClass &&
4805 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4806 return false;
4807 OldClass = NewClass;
4808 }
4809
4810 LVal.moveInto(Result);
4811 return true;
4812}
4813
Richard Smith7bd54ab2019-05-15 20:22:21 +00004814/// Determine whether \p Base, which is known to be a direct base class of
4815/// \p Derived, is a public base class.
4816static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4817 const CXXRecordDecl *Base) {
4818 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4819 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4820 if (BaseClass && declaresSameEntity(BaseClass, Base))
4821 return BaseSpec.getAccessSpecifier() == AS_public;
4822 }
4823 llvm_unreachable("Base is not a direct base of Derived");
4824}
4825
4826/// Apply the given dynamic cast operation on the provided lvalue.
4827///
4828/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4829/// to find a suitable target subobject.
4830static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4831 LValue &Ptr) {
4832 // We can't do anything with a non-symbolic pointer value.
4833 SubobjectDesignator &D = Ptr.Designator;
4834 if (D.Invalid)
4835 return false;
4836
4837 // C++ [expr.dynamic.cast]p6:
4838 // If v is a null pointer value, the result is a null pointer value.
4839 if (Ptr.isNullPointer() && !E->isGLValue())
4840 return true;
4841
4842 // For all the other cases, we need the pointer to point to an object within
4843 // its lifetime / period of construction / destruction, and we need to know
4844 // its dynamic type.
4845 Optional<DynamicType> DynType =
4846 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4847 if (!DynType)
4848 return false;
4849
4850 // C++ [expr.dynamic.cast]p7:
4851 // If T is "pointer to cv void", then the result is a pointer to the most
4852 // derived object
4853 if (E->getType()->isVoidPointerType())
4854 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4855
4856 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4857 assert(C && "dynamic_cast target is not void pointer nor class");
4858 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4859
4860 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4861 // C++ [expr.dynamic.cast]p9:
4862 if (!E->isGLValue()) {
4863 // The value of a failed cast to pointer type is the null pointer value
4864 // of the required result type.
4865 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4866 Ptr.setNull(E->getType(), TargetVal);
4867 return true;
4868 }
4869
4870 // A failed cast to reference type throws [...] std::bad_cast.
4871 unsigned DiagKind;
4872 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4873 DynType->Type->isDerivedFrom(C)))
4874 DiagKind = 0;
4875 else if (!Paths || Paths->begin() == Paths->end())
4876 DiagKind = 1;
4877 else if (Paths->isAmbiguous(CQT))
4878 DiagKind = 2;
4879 else {
4880 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4881 DiagKind = 3;
4882 }
4883 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4884 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4885 << Info.Ctx.getRecordType(DynType->Type)
4886 << E->getType().getUnqualifiedType();
4887 return false;
4888 };
4889
4890 // Runtime check, phase 1:
4891 // Walk from the base subobject towards the derived object looking for the
4892 // target type.
4893 for (int PathLength = Ptr.Designator.Entries.size();
4894 PathLength >= (int)DynType->PathLength; --PathLength) {
4895 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4896 if (declaresSameEntity(Class, C))
4897 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4898 // We can only walk across public inheritance edges.
4899 if (PathLength > (int)DynType->PathLength &&
4900 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4901 Class))
4902 return RuntimeCheckFailed(nullptr);
4903 }
4904
4905 // Runtime check, phase 2:
4906 // Search the dynamic type for an unambiguous public base of type C.
4907 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4908 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4909 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4910 Paths.front().Access == AS_public) {
4911 // Downcast to the dynamic type...
4912 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4913 return false;
4914 // ... then upcast to the chosen base class subobject.
4915 for (CXXBasePathElement &Elem : Paths.front())
4916 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4917 return false;
4918 return true;
4919 }
4920
4921 // Otherwise, the runtime check fails.
4922 return RuntimeCheckFailed(&Paths);
4923}
4924
Richard Smith31c69a32019-05-21 23:15:20 +00004925namespace {
4926struct StartLifetimeOfUnionMemberHandler {
4927 const FieldDecl *Field;
4928
4929 static const AccessKinds AccessKind = AK_Assign;
4930
4931 APValue getDefaultInitValue(QualType SubobjType) {
4932 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4933 if (RD->isUnion())
4934 return APValue((const FieldDecl*)nullptr);
4935
4936 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4937 std::distance(RD->field_begin(), RD->field_end()));
4938
4939 unsigned Index = 0;
4940 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4941 End = RD->bases_end(); I != End; ++I, ++Index)
4942 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4943
4944 for (const auto *I : RD->fields()) {
4945 if (I->isUnnamedBitfield())
4946 continue;
4947 Struct.getStructField(I->getFieldIndex()) =
4948 getDefaultInitValue(I->getType());
4949 }
4950 return Struct;
4951 }
4952
4953 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4954 SubobjType->getAsArrayTypeUnsafe())) {
4955 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4956 if (Array.hasArrayFiller())
4957 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4958 return Array;
4959 }
4960
4961 return APValue::IndeterminateValue();
4962 }
4963
4964 typedef bool result_type;
4965 bool failed() { return false; }
4966 bool found(APValue &Subobj, QualType SubobjType) {
4967 // We are supposed to perform no initialization but begin the lifetime of
4968 // the object. We interpret that as meaning to do what default
4969 // initialization of the object would do if all constructors involved were
4970 // trivial:
4971 // * All base, non-variant member, and array element subobjects' lifetimes
4972 // begin
4973 // * No variant members' lifetimes begin
4974 // * All scalar subobjects whose lifetimes begin have indeterminate values
4975 assert(SubobjType->isUnionType());
4976 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4977 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4978 return true;
4979 }
4980 bool found(APSInt &Value, QualType SubobjType) {
4981 llvm_unreachable("wrong value kind for union object");
4982 }
4983 bool found(APFloat &Value, QualType SubobjType) {
4984 llvm_unreachable("wrong value kind for union object");
4985 }
4986};
4987} // end anonymous namespace
4988
4989const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4990
4991/// Handle a builtin simple-assignment or a call to a trivial assignment
4992/// operator whose left-hand side might involve a union member access. If it
4993/// does, implicitly start the lifetime of any accessed union elements per
4994/// C++20 [class.union]5.
4995static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4996 const LValue &LHS) {
4997 if (LHS.InvalidBase || LHS.Designator.Invalid)
4998 return false;
4999
5000 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5001 // C++ [class.union]p5:
5002 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005003 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005004 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005005 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5006 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5007 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5008 if (!FD)
5009 break;
5010
5011 // ... and also contains A.B if B names a union member
5012 if (FD->getParent()->isUnion())
5013 UnionPathLengths.push_back({PathLength - 1, FD});
5014
5015 E = ME->getBase();
5016 --PathLength;
5017 assert(declaresSameEntity(FD,
5018 LHS.Designator.Entries[PathLength]
5019 .getAsBaseOrMember().getPointer()));
5020
5021 // -- If E is of the form A[B] and is interpreted as a built-in array
5022 // subscripting operator, S(E) is [S(the array operand, if any)].
5023 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5024 // Step over an ArrayToPointerDecay implicit cast.
5025 auto *Base = ASE->getBase()->IgnoreImplicit();
5026 if (!Base->getType()->isArrayType())
5027 break;
5028
5029 E = Base;
5030 --PathLength;
5031
5032 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5033 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005034 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005035 if (ICE->getCastKind() == CK_NoOp)
5036 continue;
5037 if (ICE->getCastKind() != CK_DerivedToBase &&
5038 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5039 break;
Richard Smitha481b012019-05-30 20:45:12 +00005040 // Walk path backwards as we walk up from the base to the derived class.
5041 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005042 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005043 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005044 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5045 LHS.Designator.Entries[PathLength]
5046 .getAsBaseOrMember().getPointer()));
5047 }
Richard Smith31c69a32019-05-21 23:15:20 +00005048
5049 // -- Otherwise, S(E) is empty.
5050 } else {
5051 break;
5052 }
5053 }
5054
5055 // Common case: no unions' lifetimes are started.
5056 if (UnionPathLengths.empty())
5057 return true;
5058
5059 // if modification of X [would access an inactive union member], an object
5060 // of the type of X is implicitly created
5061 CompleteObject Obj =
5062 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5063 if (!Obj)
5064 return false;
5065 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5066 llvm::reverse(UnionPathLengths)) {
5067 // Form a designator for the union object.
5068 SubobjectDesignator D = LHS.Designator;
5069 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5070
5071 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5072 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5073 return false;
5074 }
5075
5076 return true;
5077}
5078
Richard Smithbe6dd812014-11-19 21:27:17 +00005079/// Determine if a class has any fields that might need to be copied by a
5080/// trivial copy or move operation.
5081static bool hasFields(const CXXRecordDecl *RD) {
5082 if (!RD || RD->isEmpty())
5083 return false;
5084 for (auto *FD : RD->fields()) {
5085 if (FD->isUnnamedBitfield())
5086 continue;
5087 return true;
5088 }
5089 for (auto &Base : RD->bases())
5090 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5091 return true;
5092 return false;
5093}
5094
Richard Smithd62306a2011-11-10 06:34:14 +00005095namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005096typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005097}
5098
5099/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005100static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5101 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005102 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005103 llvm::SmallBitVector ForbiddenNullArgs;
5104 if (Callee->hasAttr<NonNullAttr>()) {
5105 ForbiddenNullArgs.resize(Args.size());
5106 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5107 if (!Attr->args_size()) {
5108 ForbiddenNullArgs.set();
5109 break;
5110 } else
5111 for (auto Idx : Attr->args()) {
5112 unsigned ASTIdx = Idx.getASTIndex();
5113 if (ASTIdx >= Args.size())
5114 continue;
5115 ForbiddenNullArgs[ASTIdx] = 1;
5116 }
5117 }
5118 }
Richard Smithd62306a2011-11-10 06:34:14 +00005119 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005120 I != E; ++I) {
5121 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5122 // If we're checking for a potential constant expression, evaluate all
5123 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005124 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005125 return false;
5126 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005127 } else if (!ForbiddenNullArgs.empty() &&
5128 ForbiddenNullArgs[I - Args.begin()] &&
5129 ArgValues[I - Args.begin()].isNullPointer()) {
5130 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5131 if (!Info.noteFailure())
5132 return false;
5133 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005134 }
5135 }
5136 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005137}
5138
Richard Smith254a73d2011-10-28 22:34:42 +00005139/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005140static bool HandleFunctionCall(SourceLocation CallLoc,
5141 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005143 EvalInfo &Info, APValue &Result,
5144 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005145 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005146 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005147 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005148
Richard Smith253c2a32012-01-27 01:14:48 +00005149 if (!Info.CheckCallLimit(CallLoc))
5150 return false;
5151
5152 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005153
5154 // For a trivial copy or move assignment, perform an APValue copy. This is
5155 // essential for unions, where the operations performed by the assignment
5156 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005157 //
5158 // Skip this for non-union classes with no fields; in that case, the defaulted
5159 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005160 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005161 if (MD && MD->isDefaulted() &&
5162 (MD->getParent()->isUnion() ||
5163 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005164 assert(This &&
5165 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5166 LValue RHS;
5167 RHS.setFrom(Info.Ctx, ArgValues[0]);
5168 APValue RHSValue;
5169 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5170 RHS, RHSValue))
5171 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005172 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5173 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5174 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005175 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005176 RHSValue))
5177 return false;
5178 This->moveInto(Result);
5179 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005180 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005181 // We're in a lambda; determine the lambda capture field maps unless we're
5182 // just constexpr checking a lambda's call operator. constexpr checking is
5183 // done before the captures have been added to the closure object (unless
5184 // we're inferring constexpr-ness), so we don't have access to them in this
5185 // case. But since we don't need the captures to constexpr check, we can
5186 // just ignore them.
5187 if (!Info.checkingPotentialConstantExpression())
5188 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5189 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005190 }
5191
Richard Smith52a980a2015-08-28 02:43:42 +00005192 StmtResult Ret = {Result, ResultSlot};
5193 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005194 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005195 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005196 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005197 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005198 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005199 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005200}
5201
Richard Smithd62306a2011-11-10 06:34:14 +00005202/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005203static bool HandleConstructorCall(const Expr *E, const LValue &This,
5204 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005205 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005206 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005207 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005208 if (!Info.CheckCallLimit(CallLoc))
5209 return false;
5210
Richard Smith3607ffe2012-02-13 03:54:03 +00005211 const CXXRecordDecl *RD = Definition->getParent();
5212 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005213 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005214 return false;
5215 }
5216
Erik Pilkington42925492017-10-04 00:18:55 +00005217 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005218 Info,
5219 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5220 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005221 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005222
Richard Smith52a980a2015-08-28 02:43:42 +00005223 // FIXME: Creating an APValue just to hold a nonexistent return value is
5224 // wasteful.
5225 APValue RetVal;
5226 StmtResult Ret = {RetVal, nullptr};
5227
Richard Smith5179eb72016-06-28 19:03:57 +00005228 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005229 if (Definition->isDelegatingConstructor()) {
5230 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005231 {
5232 FullExpressionRAII InitScope(Info);
5233 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5234 return false;
5235 }
Richard Smith52a980a2015-08-28 02:43:42 +00005236 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005237 }
5238
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005239 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005240 // essential for unions (or classes with anonymous union members), where the
5241 // operations performed by the constructor cannot be represented by
5242 // ctor-initializers.
5243 //
5244 // Skip this for empty non-union classes; we should not perform an
5245 // lvalue-to-rvalue conversion on them because their copy constructor does not
5246 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005247 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005248 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005249 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005250 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005251 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005252 return handleLValueToRValueConversion(
5253 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5254 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005255 }
5256
5257 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005258 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005259 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005260 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005261
John McCalld7bca762012-05-01 00:38:49 +00005262 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005263 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5264
Richard Smith08d6a2c2013-07-24 07:11:57 +00005265 // A scope for temporaries lifetime-extended by reference members.
5266 BlockScopeRAII LifetimeExtendedScope(Info);
5267
Richard Smith253c2a32012-01-27 01:14:48 +00005268 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005269 unsigned BasesSeen = 0;
5270#ifndef NDEBUG
5271 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5272#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005273 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005274 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005275 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005276 APValue *Value = &Result;
5277
5278 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005279 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005280 if (I->isBaseInitializer()) {
5281 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005282#ifndef NDEBUG
5283 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005284 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005285 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5286 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5287 "base class initializers not in expected order");
5288 ++BaseIt;
5289#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005290 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005291 BaseType->getAsCXXRecordDecl(), &Layout))
5292 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005293 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005294 } else if ((FD = I->getMember())) {
5295 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005296 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005297 if (RD->isUnion()) {
5298 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005299 Value = &Result.getUnionValue();
5300 } else {
5301 Value = &Result.getStructField(FD->getFieldIndex());
5302 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005303 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005304 // Walk the indirect field decl's chain to find the object to initialize,
5305 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005306 auto IndirectFieldChain = IFD->chain();
5307 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005308 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005309 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5310 // Switch the union field if it differs. This happens if we had
5311 // preceding zero-initialization, and we're now initializing a union
5312 // subobject other than the first.
5313 // FIXME: In this case, the values of the other subobjects are
5314 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005315 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005316 (Value->isUnion() && Value->getUnionField() != FD)) {
5317 if (CD->isUnion())
5318 *Value = APValue(FD);
5319 else
5320 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005321 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005322 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005323 // Store Subobject as its parent before updating it for the last element
5324 // in the chain.
5325 if (C == IndirectFieldChain.back())
5326 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005327 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005328 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005329 if (CD->isUnion())
5330 Value = &Value->getUnionValue();
5331 else
5332 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00005333 }
Richard Smithd62306a2011-11-10 06:34:14 +00005334 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005335 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005336 }
Richard Smith253c2a32012-01-27 01:14:48 +00005337
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005338 // Need to override This for implicit field initializers as in this case
5339 // This refers to innermost anonymous struct/union containing initializer,
5340 // not to currently constructed class.
5341 const Expr *Init = I->getInit();
5342 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5343 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005344 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005345 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5346 (FD && FD->isBitField() &&
5347 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005348 // If we're checking for a potential constant expression, evaluate all
5349 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005350 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005351 return false;
5352 Success = false;
5353 }
Richard Smith921f1322019-05-13 23:35:21 +00005354
5355 // This is the point at which the dynamic type of the object becomes this
5356 // class type.
5357 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5358 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005359 }
5360
Richard Smithd9f663b2013-04-22 15:31:51 +00005361 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005362 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005363}
5364
Richard Smith5179eb72016-06-28 19:03:57 +00005365static bool HandleConstructorCall(const Expr *E, const LValue &This,
5366 ArrayRef<const Expr*> Args,
5367 const CXXConstructorDecl *Definition,
5368 EvalInfo &Info, APValue &Result) {
5369 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005370 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005371 return false;
5372
5373 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5374 Info, Result);
5375}
5376
Eli Friedman9a156e52008-11-12 09:44:48 +00005377//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005378// Generic Evaluation
5379//===----------------------------------------------------------------------===//
5380namespace {
5381
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005382class BitCastBuffer {
5383 // FIXME: We're going to need bit-level granularity when we support
5384 // bit-fields.
5385 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5386 // we don't support a host or target where that is the case. Still, we should
5387 // use a more generic type in case we ever do.
5388 SmallVector<Optional<unsigned char>, 32> Bytes;
5389
5390 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5391 "Need at least 8 bit unsigned char");
5392
5393 bool TargetIsLittleEndian;
5394
5395public:
5396 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5397 : Bytes(Width.getQuantity()),
5398 TargetIsLittleEndian(TargetIsLittleEndian) {}
5399
5400 LLVM_NODISCARD
5401 bool readObject(CharUnits Offset, CharUnits Width,
5402 SmallVectorImpl<unsigned char> &Output) const {
5403 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5404 // If a byte of an integer is uninitialized, then the whole integer is
5405 // uninitalized.
5406 if (!Bytes[I.getQuantity()])
5407 return false;
5408 Output.push_back(*Bytes[I.getQuantity()]);
5409 }
5410 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5411 std::reverse(Output.begin(), Output.end());
5412 return true;
5413 }
5414
5415 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5416 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5417 std::reverse(Input.begin(), Input.end());
5418
5419 size_t Index = 0;
5420 for (unsigned char Byte : Input) {
5421 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5422 Bytes[Offset.getQuantity() + Index] = Byte;
5423 ++Index;
5424 }
5425 }
5426
5427 size_t size() { return Bytes.size(); }
5428};
5429
5430/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5431/// target would represent the value at runtime.
5432class APValueToBufferConverter {
5433 EvalInfo &Info;
5434 BitCastBuffer Buffer;
5435 const CastExpr *BCE;
5436
5437 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5438 const CastExpr *BCE)
5439 : Info(Info),
5440 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5441 BCE(BCE) {}
5442
5443 bool visit(const APValue &Val, QualType Ty) {
5444 return visit(Val, Ty, CharUnits::fromQuantity(0));
5445 }
5446
5447 // Write out Val with type Ty into Buffer starting at Offset.
5448 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5449 assert((size_t)Offset.getQuantity() <= Buffer.size());
5450
5451 // As a special case, nullptr_t has an indeterminate value.
5452 if (Ty->isNullPtrType())
5453 return true;
5454
5455 // Dig through Src to find the byte at SrcOffset.
5456 switch (Val.getKind()) {
5457 case APValue::Indeterminate:
5458 case APValue::None:
5459 return true;
5460
5461 case APValue::Int:
5462 return visitInt(Val.getInt(), Ty, Offset);
5463 case APValue::Float:
5464 return visitFloat(Val.getFloat(), Ty, Offset);
5465 case APValue::Array:
5466 return visitArray(Val, Ty, Offset);
5467 case APValue::Struct:
5468 return visitRecord(Val, Ty, Offset);
5469
5470 case APValue::ComplexInt:
5471 case APValue::ComplexFloat:
5472 case APValue::Vector:
5473 case APValue::FixedPoint:
5474 // FIXME: We should support these.
5475
5476 case APValue::Union:
5477 case APValue::MemberPointer:
5478 case APValue::AddrLabelDiff: {
5479 Info.FFDiag(BCE->getBeginLoc(),
5480 diag::note_constexpr_bit_cast_unsupported_type)
5481 << Ty;
5482 return false;
5483 }
5484
5485 case APValue::LValue:
5486 llvm_unreachable("LValue subobject in bit_cast?");
5487 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005488 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005489 }
5490
5491 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5492 const RecordDecl *RD = Ty->getAsRecordDecl();
5493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5494
5495 // Visit the base classes.
5496 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5497 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5498 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5499 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5500
5501 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5502 Layout.getBaseClassOffset(BaseDecl) + Offset))
5503 return false;
5504 }
5505 }
5506
5507 // Visit the fields.
5508 unsigned FieldIdx = 0;
5509 for (FieldDecl *FD : RD->fields()) {
5510 if (FD->isBitField()) {
5511 Info.FFDiag(BCE->getBeginLoc(),
5512 diag::note_constexpr_bit_cast_unsupported_bitfield);
5513 return false;
5514 }
5515
5516 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5517
5518 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5519 "only bit-fields can have sub-char alignment");
5520 CharUnits FieldOffset =
5521 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5522 QualType FieldTy = FD->getType();
5523 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5524 return false;
5525 ++FieldIdx;
5526 }
5527
5528 return true;
5529 }
5530
5531 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5532 const auto *CAT =
5533 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5534 if (!CAT)
5535 return false;
5536
5537 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5538 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5539 unsigned ArraySize = Val.getArraySize();
5540 // First, initialize the initialized elements.
5541 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5542 const APValue &SubObj = Val.getArrayInitializedElt(I);
5543 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5544 return false;
5545 }
5546
5547 // Next, initialize the rest of the array using the filler.
5548 if (Val.hasArrayFiller()) {
5549 const APValue &Filler = Val.getArrayFiller();
5550 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5551 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5552 return false;
5553 }
5554 }
5555
5556 return true;
5557 }
5558
5559 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5560 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5561 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5562 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5563 Buffer.writeObject(Offset, Bytes);
5564 return true;
5565 }
5566
5567 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5568 APSInt AsInt(Val.bitcastToAPInt());
5569 return visitInt(AsInt, Ty, Offset);
5570 }
5571
5572public:
5573 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5574 const CastExpr *BCE) {
5575 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5576 APValueToBufferConverter Converter(Info, DstSize, BCE);
5577 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5578 return None;
5579 return Converter.Buffer;
5580 }
5581};
5582
5583/// Write an BitCastBuffer into an APValue.
5584class BufferToAPValueConverter {
5585 EvalInfo &Info;
5586 const BitCastBuffer &Buffer;
5587 const CastExpr *BCE;
5588
5589 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5590 const CastExpr *BCE)
5591 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5592
5593 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5594 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5595 // Ideally this will be unreachable.
5596 llvm::NoneType unsupportedType(QualType Ty) {
5597 Info.FFDiag(BCE->getBeginLoc(),
5598 diag::note_constexpr_bit_cast_unsupported_type)
5599 << Ty;
5600 return None;
5601 }
5602
5603 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5604 const EnumType *EnumSugar = nullptr) {
5605 if (T->isNullPtrType()) {
5606 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5607 return APValue((Expr *)nullptr,
5608 /*Offset=*/CharUnits::fromQuantity(NullValue),
5609 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5610 }
5611
5612 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5613 SmallVector<uint8_t, 8> Bytes;
5614 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5615 // If this is std::byte or unsigned char, then its okay to store an
5616 // indeterminate value.
5617 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5618 bool IsUChar =
5619 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5620 T->isSpecificBuiltinType(BuiltinType::Char_U));
5621 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00005622 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005623 Info.FFDiag(BCE->getExprLoc(),
5624 diag::note_constexpr_bit_cast_indet_dest)
5625 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5626 return None;
5627 }
5628
5629 return APValue::IndeterminateValue();
5630 }
5631
5632 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5633 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5634
5635 if (T->isIntegralOrEnumerationType()) {
5636 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5637 return APValue(Val);
5638 }
5639
5640 if (T->isRealFloatingType()) {
5641 const llvm::fltSemantics &Semantics =
5642 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5643 return APValue(APFloat(Semantics, Val));
5644 }
5645
5646 return unsupportedType(QualType(T, 0));
5647 }
5648
5649 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5650 const RecordDecl *RD = RTy->getAsRecordDecl();
5651 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5652
5653 unsigned NumBases = 0;
5654 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5655 NumBases = CXXRD->getNumBases();
5656
5657 APValue ResultVal(APValue::UninitStruct(), NumBases,
5658 std::distance(RD->field_begin(), RD->field_end()));
5659
5660 // Visit the base classes.
5661 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5662 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5663 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5664 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5665 if (BaseDecl->isEmpty() ||
5666 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5667 continue;
5668
5669 Optional<APValue> SubObj = visitType(
5670 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5671 if (!SubObj)
5672 return None;
5673 ResultVal.getStructBase(I) = *SubObj;
5674 }
5675 }
5676
5677 // Visit the fields.
5678 unsigned FieldIdx = 0;
5679 for (FieldDecl *FD : RD->fields()) {
5680 // FIXME: We don't currently support bit-fields. A lot of the logic for
5681 // this is in CodeGen, so we need to factor it around.
5682 if (FD->isBitField()) {
5683 Info.FFDiag(BCE->getBeginLoc(),
5684 diag::note_constexpr_bit_cast_unsupported_bitfield);
5685 return None;
5686 }
5687
5688 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5689 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5690
5691 CharUnits FieldOffset =
5692 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5693 Offset;
5694 QualType FieldTy = FD->getType();
5695 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5696 if (!SubObj)
5697 return None;
5698 ResultVal.getStructField(FieldIdx) = *SubObj;
5699 ++FieldIdx;
5700 }
5701
5702 return ResultVal;
5703 }
5704
5705 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5706 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5707 assert(!RepresentationType.isNull() &&
5708 "enum forward decl should be caught by Sema");
5709 const BuiltinType *AsBuiltin =
5710 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5711 assert(AsBuiltin && "non-integral enum underlying type?");
5712 // Recurse into the underlying type. Treat std::byte transparently as
5713 // unsigned char.
5714 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5715 }
5716
5717 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5718 size_t Size = Ty->getSize().getLimitedValue();
5719 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5720
5721 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5722 for (size_t I = 0; I != Size; ++I) {
5723 Optional<APValue> ElementValue =
5724 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5725 if (!ElementValue)
5726 return None;
5727 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5728 }
5729
5730 return ArrayValue;
5731 }
5732
5733 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5734 return unsupportedType(QualType(Ty, 0));
5735 }
5736
5737 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5738 QualType Can = Ty.getCanonicalType();
5739
5740 switch (Can->getTypeClass()) {
5741#define TYPE(Class, Base) \
5742 case Type::Class: \
5743 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5744#define ABSTRACT_TYPE(Class, Base)
5745#define NON_CANONICAL_TYPE(Class, Base) \
5746 case Type::Class: \
5747 llvm_unreachable("non-canonical type should be impossible!");
5748#define DEPENDENT_TYPE(Class, Base) \
5749 case Type::Class: \
5750 llvm_unreachable( \
5751 "dependent types aren't supported in the constant evaluator!");
5752#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5753 case Type::Class: \
5754 llvm_unreachable("either dependent or not canonical!");
5755#include "clang/AST/TypeNodes.def"
5756 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005757 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005758 }
5759
5760public:
5761 // Pull out a full value of type DstType.
5762 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5763 const CastExpr *BCE) {
5764 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5765 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5766 }
5767};
5768
5769static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5770 QualType Ty, EvalInfo *Info,
5771 const ASTContext &Ctx,
5772 bool CheckingDest) {
5773 Ty = Ty.getCanonicalType();
5774
5775 auto diag = [&](int Reason) {
5776 if (Info)
5777 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5778 << CheckingDest << (Reason == 4) << Reason;
5779 return false;
5780 };
5781 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5782 if (Info)
5783 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5784 << NoteTy << Construct << Ty;
5785 return false;
5786 };
5787
5788 if (Ty->isUnionType())
5789 return diag(0);
5790 if (Ty->isPointerType())
5791 return diag(1);
5792 if (Ty->isMemberPointerType())
5793 return diag(2);
5794 if (Ty.isVolatileQualified())
5795 return diag(3);
5796
5797 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5798 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5799 for (CXXBaseSpecifier &BS : CXXRD->bases())
5800 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5801 CheckingDest))
5802 return note(1, BS.getType(), BS.getBeginLoc());
5803 }
5804 for (FieldDecl *FD : Record->fields()) {
5805 if (FD->getType()->isReferenceType())
5806 return diag(4);
5807 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5808 CheckingDest))
5809 return note(0, FD->getType(), FD->getBeginLoc());
5810 }
5811 }
5812
5813 if (Ty->isArrayType() &&
5814 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5815 Info, Ctx, CheckingDest))
5816 return false;
5817
5818 return true;
5819}
5820
5821static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5822 const ASTContext &Ctx,
5823 const CastExpr *BCE) {
5824 bool DestOK = checkBitCastConstexprEligibilityType(
5825 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5826 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5827 BCE->getBeginLoc(),
5828 BCE->getSubExpr()->getType(), Info, Ctx, false);
5829 return SourceOK;
5830}
5831
5832static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5833 APValue &SourceValue,
5834 const CastExpr *BCE) {
5835 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5836 "no host or target supports non 8-bit chars");
5837 assert(SourceValue.isLValue() &&
5838 "LValueToRValueBitcast requires an lvalue operand!");
5839
5840 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5841 return false;
5842
5843 LValue SourceLValue;
5844 APValue SourceRValue;
5845 SourceLValue.setFrom(Info.Ctx, SourceValue);
5846 if (!handleLValueToRValueConversion(Info, BCE,
5847 BCE->getSubExpr()->getType().withConst(),
5848 SourceLValue, SourceRValue))
5849 return false;
5850
5851 // Read out SourceValue into a char buffer.
5852 Optional<BitCastBuffer> Buffer =
5853 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5854 if (!Buffer)
5855 return false;
5856
5857 // Write out the buffer into a new APValue.
5858 Optional<APValue> MaybeDestValue =
5859 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5860 if (!MaybeDestValue)
5861 return false;
5862
5863 DestValue = std::move(*MaybeDestValue);
5864 return true;
5865}
5866
Aaron Ballman68af21c2014-01-03 19:26:43 +00005867template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005868class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005869 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005870private:
Richard Smith52a980a2015-08-28 02:43:42 +00005871 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005872 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005873 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005874 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005875 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005876 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005877 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005878
Richard Smith17100ba2012-02-16 02:46:34 +00005879 // Check whether a conditional operator with a non-constant condition is a
5880 // potential constant expression. If neither arm is a potential constant
5881 // expression, then the conditional operator is not either.
5882 template<typename ConditionalOperator>
5883 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005884 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005885
5886 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005887 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005888 {
Richard Smith17100ba2012-02-16 02:46:34 +00005889 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005890 StmtVisitorTy::Visit(E->getFalseExpr());
5891 if (Diag.empty())
5892 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005893 }
Richard Smith17100ba2012-02-16 02:46:34 +00005894
George Burgess IV8c892b52016-05-25 22:31:54 +00005895 {
5896 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005897 Diag.clear();
5898 StmtVisitorTy::Visit(E->getTrueExpr());
5899 if (Diag.empty())
5900 return;
5901 }
5902
5903 Error(E, diag::note_constexpr_conditional_never_const);
5904 }
5905
5906
5907 template<typename ConditionalOperator>
5908 bool HandleConditionalOperator(const ConditionalOperator *E) {
5909 bool BoolResult;
5910 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005911 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005912 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005913 return false;
5914 }
5915 if (Info.noteFailure()) {
5916 StmtVisitorTy::Visit(E->getTrueExpr());
5917 StmtVisitorTy::Visit(E->getFalseExpr());
5918 }
Richard Smith17100ba2012-02-16 02:46:34 +00005919 return false;
5920 }
5921
5922 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5923 return StmtVisitorTy::Visit(EvalExpr);
5924 }
5925
Peter Collingbournee9200682011-05-13 03:29:01 +00005926protected:
5927 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005928 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005929 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5930
Richard Smith92b1ce02011-12-12 09:28:41 +00005931 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005932 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005933 }
5934
Aaron Ballman68af21c2014-01-03 19:26:43 +00005935 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005936
5937public:
5938 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5939
5940 EvalInfo &getEvalInfo() { return Info; }
5941
Richard Smithf57d8cb2011-12-09 22:58:01 +00005942 /// Report an evaluation error. This should only be called when an error is
5943 /// first discovered. When propagating an error, just return false.
5944 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005945 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005946 return false;
5947 }
5948 bool Error(const Expr *E) {
5949 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5950 }
5951
Aaron Ballman68af21c2014-01-03 19:26:43 +00005952 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005953 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005954 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005955 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005956 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005957 }
5958
Bill Wendling8003edc2018-11-09 00:41:36 +00005959 bool VisitConstantExpr(const ConstantExpr *E)
5960 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005961 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005962 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005963 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005964 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005965 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005966 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005967 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005968 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005969 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005970 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005971 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005972 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005973 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5974 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005975 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005976 return StmtVisitorTy::Visit(E->getExpr());
5977 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005978 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005979 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005980 // The initializer may not have been parsed yet, or might be erroneous.
5981 if (!E->getExpr())
5982 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005983 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005984 return StmtVisitorTy::Visit(E->getExpr());
5985 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005986
Richard Smith5894a912011-12-19 22:12:41 +00005987 // We cannot create any objects for which cleanups are required, so there is
5988 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005989 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005990 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005991
Aaron Ballman68af21c2014-01-03 19:26:43 +00005992 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005993 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5994 return static_cast<Derived*>(this)->VisitCastExpr(E);
5995 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005996 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005997 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5998 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005999 return static_cast<Derived*>(this)->VisitCastExpr(E);
6000 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006001 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6002 return static_cast<Derived*>(this)->VisitCastExpr(E);
6003 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006004
Aaron Ballman68af21c2014-01-03 19:26:43 +00006005 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006006 switch (E->getOpcode()) {
6007 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006008 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006009
6010 case BO_Comma:
6011 VisitIgnoredValue(E->getLHS());
6012 return StmtVisitorTy::Visit(E->getRHS());
6013
6014 case BO_PtrMemD:
6015 case BO_PtrMemI: {
6016 LValue Obj;
6017 if (!HandleMemberPointerAccess(Info, E, Obj))
6018 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006019 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006020 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006021 return false;
6022 return DerivedSuccess(Result, E);
6023 }
6024 }
6025 }
6026
Aaron Ballman68af21c2014-01-03 19:26:43 +00006027 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006028 // Evaluate and cache the common expression. We treat it as a temporary,
6029 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00006030 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00006031 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006032 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006033
Richard Smith17100ba2012-02-16 02:46:34 +00006034 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006035 }
6036
Aaron Ballman68af21c2014-01-03 19:26:43 +00006037 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006038 bool IsBcpCall = false;
6039 // If the condition (ignoring parens) is a __builtin_constant_p call,
6040 // the result is a constant expression if it can be folded without
6041 // side-effects. This is an important GNU extension. See GCC PR38377
6042 // for discussion.
6043 if (const CallExpr *CallCE =
6044 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006045 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006046 IsBcpCall = true;
6047
6048 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6049 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00006050 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006051 return false;
6052
Richard Smith6d4c6582013-11-05 22:18:15 +00006053 FoldConstant Fold(Info, IsBcpCall);
6054 if (!HandleConditionalOperator(E)) {
6055 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006056 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006057 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006058
6059 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006060 }
6061
Aaron Ballman68af21c2014-01-03 19:26:43 +00006062 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006063 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006064 return DerivedSuccess(*Value, E);
6065
6066 const Expr *Source = E->getSourceExpr();
6067 if (!Source)
6068 return Error(E);
6069 if (Source == E) { // sanity checking.
6070 assert(0 && "OpaqueValueExpr recursively refers to itself");
6071 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006072 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006073 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006074 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006075
Aaron Ballman68af21c2014-01-03 19:26:43 +00006076 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006077 APValue Result;
6078 if (!handleCallExpr(E, Result, nullptr))
6079 return false;
6080 return DerivedSuccess(Result, E);
6081 }
6082
6083 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006084 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006085 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006086 QualType CalleeType = Callee->getType();
6087
Craig Topper36250ad2014-05-12 05:36:57 +00006088 const FunctionDecl *FD = nullptr;
6089 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006090 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006091 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006092
Richard Smithe97cbd72011-11-11 04:05:33 +00006093 // Extract function decl and 'this' pointer from the callee.
6094 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006095 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006096 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6097 // Explicit bound member calls, such as x.f() or p->g();
6098 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006099 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006100 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6101 if (!Member)
6102 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006103 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006104 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006105 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6106 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006107 Member = dyn_cast_or_null<CXXMethodDecl>(
6108 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6109 if (!Member)
6110 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006111 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00006112 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006113 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006114 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006115 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006116 LValue Call;
6117 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006118 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006119
Richard Smitha8105bc2012-01-06 16:39:00 +00006120 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006121 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006122 FD = dyn_cast_or_null<FunctionDecl>(
6123 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006124 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006125 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006126 // Don't call function pointers which have been cast to some other type.
6127 // Per DR (no number yet), the caller and callee can differ in noexcept.
6128 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6129 CalleeType->getPointeeType(), FD->getType())) {
6130 return Error(E);
6131 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006132
6133 // Overloaded operator calls to member functions are represented as normal
6134 // calls with '*this' as the first argument.
6135 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6136 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006137 // FIXME: When selecting an implicit conversion for an overloaded
6138 // operator delete, we sometimes try to evaluate calls to conversion
6139 // operators without a 'this' parameter!
6140 if (Args.empty())
6141 return Error(E);
6142
Nick Lewycky13073a62017-06-12 21:15:44 +00006143 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006144 return false;
6145 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006146 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006147 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006148 // Map the static invoker for the lambda back to the call operator.
6149 // Conveniently, we don't have to slice out the 'this' argument (as is
6150 // being done for the non-static case), since a static member function
6151 // doesn't have an implicit argument passed in.
6152 const CXXRecordDecl *ClosureClass = MD->getParent();
6153 assert(
6154 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6155 "Number of captures must be zero for conversion to function-ptr");
6156
6157 const CXXMethodDecl *LambdaCallOp =
6158 ClosureClass->getLambdaCallOperator();
6159
6160 // Set 'FD', the function that will be called below, to the call
6161 // operator. If the closure object represents a generic lambda, find
6162 // the corresponding specialization of the call operator.
6163
6164 if (ClosureClass->isGenericLambda()) {
6165 assert(MD->isFunctionTemplateSpecialization() &&
6166 "A generic lambda's static-invoker function must be a "
6167 "template specialization");
6168 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6169 FunctionTemplateDecl *CallOpTemplate =
6170 LambdaCallOp->getDescribedFunctionTemplate();
6171 void *InsertPos = nullptr;
6172 FunctionDecl *CorrespondingCallOpSpecialization =
6173 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6174 assert(CorrespondingCallOpSpecialization &&
6175 "We must always have a function call operator specialization "
6176 "that corresponds to our static invoker specialization");
6177 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6178 } else
6179 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006180 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006181 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006182 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006183
Richard Smith921f1322019-05-13 23:35:21 +00006184 SmallVector<QualType, 4> CovariantAdjustmentPath;
6185 if (This) {
6186 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006187 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6188 // Perform virtual dispatch, if necessary.
6189 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6190 CovariantAdjustmentPath);
6191 if (!FD)
6192 return false;
6193 } else {
6194 // Check that the 'this' pointer points to an object of the right type.
6195 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6196 return false;
6197 }
Richard Smith921f1322019-05-13 23:35:21 +00006198 }
Richard Smith47b34932012-02-01 02:39:43 +00006199
Craig Topper36250ad2014-05-12 05:36:57 +00006200 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006201 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006202
Nick Lewycky13073a62017-06-12 21:15:44 +00006203 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6204 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006205 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006206 return false;
6207
Richard Smith921f1322019-05-13 23:35:21 +00006208 if (!CovariantAdjustmentPath.empty() &&
6209 !HandleCovariantReturnAdjustment(Info, E, Result,
6210 CovariantAdjustmentPath))
6211 return false;
6212
Richard Smith52a980a2015-08-28 02:43:42 +00006213 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006214 }
6215
Aaron Ballman68af21c2014-01-03 19:26:43 +00006216 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006217 return StmtVisitorTy::Visit(E->getInitializer());
6218 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006219 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006220 if (E->getNumInits() == 0)
6221 return DerivedZeroInitialization(E);
6222 if (E->getNumInits() == 1)
6223 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006224 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006225 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006226 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006227 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006228 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006229 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006230 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006231 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006232 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006233 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006234 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006235
Richard Smithd62306a2011-11-10 06:34:14 +00006236 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006237 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006238 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6239 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006240 assert(!E->isArrow() && "missing call to bound member function?");
6241
Richard Smith2e312c82012-03-03 22:46:17 +00006242 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006243 if (!Evaluate(Val, Info, E->getBase()))
6244 return false;
6245
6246 QualType BaseTy = E->getBase()->getType();
6247
6248 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006249 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006250 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006251 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006252 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6253
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006254 // Note: there is no lvalue base here. But this case should only ever
6255 // happen in C or in C++98, where we cannot be evaluating a constexpr
6256 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006257 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006258 SubobjectDesignator Designator(BaseTy);
6259 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006260
Richard Smith3229b742013-05-05 21:17:10 +00006261 APValue Result;
6262 return extractSubobject(Info, E, Obj, Designator, Result) &&
6263 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006264 }
6265
Aaron Ballman68af21c2014-01-03 19:26:43 +00006266 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006267 switch (E->getCastKind()) {
6268 default:
6269 break;
6270
Richard Smitha23ab512013-05-23 00:30:41 +00006271 case CK_AtomicToNonAtomic: {
6272 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006273 // This does not need to be done in place even for class/array types:
6274 // atomic-to-non-atomic conversion implies copying the object
6275 // representation.
6276 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006277 return false;
6278 return DerivedSuccess(AtomicVal, E);
6279 }
6280
Richard Smith11562c52011-10-28 17:51:58 +00006281 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006282 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006283 return StmtVisitorTy::Visit(E->getSubExpr());
6284
6285 case CK_LValueToRValue: {
6286 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006287 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6288 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006289 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006290 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006291 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006292 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006293 return false;
6294 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006295 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006296 case CK_LValueToRValueBitCast: {
6297 APValue DestValue, SourceValue;
6298 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6299 return false;
6300 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6301 return false;
6302 return DerivedSuccess(DestValue, E);
6303 }
Richard Smith11562c52011-10-28 17:51:58 +00006304 }
6305
Richard Smithf57d8cb2011-12-09 22:58:01 +00006306 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006307 }
6308
Aaron Ballman68af21c2014-01-03 19:26:43 +00006309 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006310 return VisitUnaryPostIncDec(UO);
6311 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006312 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006313 return VisitUnaryPostIncDec(UO);
6314 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006315 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006316 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006317 return Error(UO);
6318
6319 LValue LVal;
6320 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6321 return false;
6322 APValue RVal;
6323 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6324 UO->isIncrementOp(), &RVal))
6325 return false;
6326 return DerivedSuccess(RVal, UO);
6327 }
6328
Aaron Ballman68af21c2014-01-03 19:26:43 +00006329 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006330 // We will have checked the full-expressions inside the statement expression
6331 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00006332 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00006333 return Error(E);
6334
Richard Smith08d6a2c2013-07-24 07:11:57 +00006335 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006336 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006337 if (CS->body_empty())
6338 return true;
6339
Richard Smith51f03172013-06-20 03:00:05 +00006340 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6341 BE = CS->body_end();
6342 /**/; ++BI) {
6343 if (BI + 1 == BE) {
6344 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6345 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006346 Info.FFDiag((*BI)->getBeginLoc(),
6347 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006348 return false;
6349 }
6350 return this->Visit(FinalExpr);
6351 }
6352
6353 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006354 StmtResult Result = { ReturnValue, nullptr };
6355 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006356 if (ESR != ESR_Succeeded) {
6357 // FIXME: If the statement-expression terminated due to 'return',
6358 // 'break', or 'continue', it would be nice to propagate that to
6359 // the outer statement evaluation rather than bailing out.
6360 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006361 Info.FFDiag((*BI)->getBeginLoc(),
6362 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006363 return false;
6364 }
6365 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006366
6367 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006368 }
6369
Richard Smith4a678122011-10-24 18:44:57 +00006370 /// Visit a value which is evaluated, but whose value is ignored.
6371 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006372 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006373 }
David Majnemere9807b22016-02-26 04:23:19 +00006374
6375 /// Potentially visit a MemberExpr's base expression.
6376 void VisitIgnoredBaseExpression(const Expr *E) {
6377 // While MSVC doesn't evaluate the base expression, it does diagnose the
6378 // presence of side-effecting behavior.
6379 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6380 return;
6381 VisitIgnoredValue(E);
6382 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006383};
6384
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006385} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006386
6387//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006388// Common base class for lvalue and temporary evaluation.
6389//===----------------------------------------------------------------------===//
6390namespace {
6391template<class Derived>
6392class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006393 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006394protected:
6395 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006396 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006397 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006398 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006399
6400 bool Success(APValue::LValueBase B) {
6401 Result.set(B);
6402 return true;
6403 }
6404
George Burgess IVf9013bf2017-02-10 22:52:29 +00006405 bool evaluatePointer(const Expr *E, LValue &Result) {
6406 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6407 }
6408
Richard Smith027bf112011-11-17 22:56:20 +00006409public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006410 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6411 : ExprEvaluatorBaseTy(Info), Result(Result),
6412 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006413
Richard Smith2e312c82012-03-03 22:46:17 +00006414 bool Success(const APValue &V, const Expr *E) {
6415 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006416 return true;
6417 }
Richard Smith027bf112011-11-17 22:56:20 +00006418
Richard Smith027bf112011-11-17 22:56:20 +00006419 bool VisitMemberExpr(const MemberExpr *E) {
6420 // Handle non-static data members.
6421 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006422 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006423 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006424 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006425 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006426 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006427 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006428 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006429 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006430 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006431 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006432 BaseTy = E->getBase()->getType();
6433 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006434 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006435 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006436 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006437 Result.setInvalid(E);
6438 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006439 }
Richard Smith027bf112011-11-17 22:56:20 +00006440
Richard Smith1b78b3d2012-01-25 22:15:11 +00006441 const ValueDecl *MD = E->getMemberDecl();
6442 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6443 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6444 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6445 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006446 if (!HandleLValueMember(this->Info, E, Result, FD))
6447 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006448 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006449 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6450 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006451 } else
6452 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006453
Richard Smith1b78b3d2012-01-25 22:15:11 +00006454 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006455 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006456 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006457 RefValue))
6458 return false;
6459 return Success(RefValue, E);
6460 }
6461 return true;
6462 }
6463
6464 bool VisitBinaryOperator(const BinaryOperator *E) {
6465 switch (E->getOpcode()) {
6466 default:
6467 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6468
6469 case BO_PtrMemD:
6470 case BO_PtrMemI:
6471 return HandleMemberPointerAccess(this->Info, E, Result);
6472 }
6473 }
6474
6475 bool VisitCastExpr(const CastExpr *E) {
6476 switch (E->getCastKind()) {
6477 default:
6478 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6479
6480 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006481 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006482 if (!this->Visit(E->getSubExpr()))
6483 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006484
6485 // Now figure out the necessary offset to add to the base LV to get from
6486 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006487 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6488 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006489 }
6490 }
6491};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006492}
Richard Smith027bf112011-11-17 22:56:20 +00006493
6494//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006495// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006496//
6497// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6498// function designators (in C), decl references to void objects (in C), and
6499// temporaries (if building with -Wno-address-of-temporary).
6500//
6501// LValue evaluation produces values comprising a base expression of one of the
6502// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006503// - Declarations
6504// * VarDecl
6505// * FunctionDecl
6506// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006507// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006508// * StringLiteral
6509// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006510// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006511// * ObjCEncodeExpr
6512// * AddrLabelExpr
6513// * BlockExpr
6514// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006515// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006516// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006517// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006518// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006519// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6520// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006521// * A MaterializeTemporaryExpr that has static storage duration, with no
6522// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006523// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006524//===----------------------------------------------------------------------===//
6525namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006526class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006527 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006528public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006529 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6530 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006531
Richard Smith11562c52011-10-28 17:51:58 +00006532 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006533 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006534
Peter Collingbournee9200682011-05-13 03:29:01 +00006535 bool VisitDeclRefExpr(const DeclRefExpr *E);
6536 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006537 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006538 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6539 bool VisitMemberExpr(const MemberExpr *E);
6540 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6541 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006542 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006543 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006544 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6545 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006546 bool VisitUnaryReal(const UnaryOperator *E);
6547 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006548 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6549 return VisitUnaryPreIncDec(UO);
6550 }
6551 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6552 return VisitUnaryPreIncDec(UO);
6553 }
Richard Smith3229b742013-05-05 21:17:10 +00006554 bool VisitBinAssign(const BinaryOperator *BO);
6555 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006556
Peter Collingbournee9200682011-05-13 03:29:01 +00006557 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006558 switch (E->getCastKind()) {
6559 default:
Richard Smith027bf112011-11-17 22:56:20 +00006560 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006561
Eli Friedmance3e02a2011-10-11 00:13:24 +00006562 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006563 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006564 if (!Visit(E->getSubExpr()))
6565 return false;
6566 Result.Designator.setInvalid();
6567 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006568
Richard Smith027bf112011-11-17 22:56:20 +00006569 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006570 if (!Visit(E->getSubExpr()))
6571 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006572 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006573
6574 case CK_Dynamic:
6575 if (!Visit(E->getSubExpr()))
6576 return false;
6577 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006578 }
6579 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006580};
6581} // end anonymous namespace
6582
Richard Smith11562c52011-10-28 17:51:58 +00006583/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006584/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006585/// * function designators in C, and
6586/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006587/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006588static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6589 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006590 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006591 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006592 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006593}
6594
Peter Collingbournee9200682011-05-13 03:29:01 +00006595bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006596 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006597 return Success(FD);
6598 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006599 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006600 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006601 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006602 return Error(E);
6603}
Richard Smith733237d2011-10-24 23:14:33 +00006604
Faisal Vali0528a312016-11-13 06:09:16 +00006605
Richard Smith11562c52011-10-28 17:51:58 +00006606bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006607
6608 // If we are within a lambda's call operator, check whether the 'VD' referred
6609 // to within 'E' actually represents a lambda-capture that maps to a
6610 // data-member/field within the closure object, and if so, evaluate to the
6611 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006612 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6613 isa<DeclRefExpr>(E) &&
6614 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6615 // We don't always have a complete capture-map when checking or inferring if
6616 // the function call operator meets the requirements of a constexpr function
6617 // - but we don't need to evaluate the captures to determine constexprness
6618 // (dcl.constexpr C++17).
6619 if (Info.checkingPotentialConstantExpression())
6620 return false;
6621
Faisal Vali051e3a22017-02-16 04:12:21 +00006622 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006623 // Start with 'Result' referring to the complete closure object...
6624 Result = *Info.CurrentCall->This;
6625 // ... then update it to refer to the field of the closure object
6626 // that represents the capture.
6627 if (!HandleLValueMember(Info, E, Result, FD))
6628 return false;
6629 // And if the field is of reference type, update 'Result' to refer to what
6630 // the field refers to.
6631 if (FD->getType()->isReferenceType()) {
6632 APValue RVal;
6633 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6634 RVal))
6635 return false;
6636 Result.setFrom(Info.Ctx, RVal);
6637 }
6638 return true;
6639 }
6640 }
Craig Topper36250ad2014-05-12 05:36:57 +00006641 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006642 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6643 // Only if a local variable was declared in the function currently being
6644 // evaluated, do we expect to be able to find its value in the current
6645 // frame. (Otherwise it was likely declared in an enclosing context and
6646 // could either have a valid evaluatable value (for e.g. a constexpr
6647 // variable) or be ill-formed (and trigger an appropriate evaluation
6648 // diagnostic)).
6649 if (Info.CurrentCall->Callee &&
6650 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6651 Frame = Info.CurrentCall;
6652 }
6653 }
Richard Smith3229b742013-05-05 21:17:10 +00006654
Richard Smithfec09922011-11-01 16:57:24 +00006655 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006656 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006657 Result.set({VD, Frame->Index,
6658 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006659 return true;
6660 }
Richard Smithce40ad62011-11-12 22:28:03 +00006661 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006662 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006663
Richard Smith3229b742013-05-05 21:17:10 +00006664 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006665 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006666 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006667 if (!V->hasValue()) {
6668 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6669 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006670 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006671 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006672 return false;
6673 }
Richard Smith3229b742013-05-05 21:17:10 +00006674 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006675}
6676
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006677bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6678 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006679 // Walk through the expression to find the materialized temporary itself.
6680 SmallVector<const Expr *, 2> CommaLHSs;
6681 SmallVector<SubobjectAdjustment, 2> Adjustments;
6682 const Expr *Inner = E->GetTemporaryExpr()->
6683 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006684
Richard Smith84401042013-06-03 05:03:02 +00006685 // If we passed any comma operators, evaluate their LHSs.
6686 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6687 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6688 return false;
6689
Richard Smithe6c01442013-06-05 00:46:14 +00006690 // A materialized temporary with static storage duration can appear within the
6691 // result of a constant expression evaluation, so we need to preserve its
6692 // value for use outside this evaluation.
6693 APValue *Value;
6694 if (E->getStorageDuration() == SD_Static) {
6695 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006696 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006697 Result.set(E);
6698 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006699 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6700 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006701 }
6702
Richard Smithea4ad5d2013-06-06 08:19:16 +00006703 QualType Type = Inner->getType();
6704
Richard Smith84401042013-06-03 05:03:02 +00006705 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006706 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6707 (E->getStorageDuration() == SD_Static &&
6708 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6709 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006710 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006711 }
Richard Smith84401042013-06-03 05:03:02 +00006712
6713 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006714 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6715 --I;
6716 switch (Adjustments[I].Kind) {
6717 case SubobjectAdjustment::DerivedToBaseAdjustment:
6718 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6719 Type, Result))
6720 return false;
6721 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6722 break;
6723
6724 case SubobjectAdjustment::FieldAdjustment:
6725 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6726 return false;
6727 Type = Adjustments[I].Field->getType();
6728 break;
6729
6730 case SubobjectAdjustment::MemberPointerAdjustment:
6731 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6732 Adjustments[I].Ptr.RHS))
6733 return false;
6734 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6735 break;
6736 }
6737 }
6738
6739 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006740}
6741
Peter Collingbournee9200682011-05-13 03:29:01 +00006742bool
6743LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006744 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6745 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006746 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6747 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006748 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006749}
6750
Richard Smith6e525142011-12-27 12:18:28 +00006751bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006752 TypeInfoLValue TypeInfo;
6753
Richard Smithee0ce3022019-05-17 07:06:46 +00006754 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006755 if (E->isTypeOperand())
6756 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6757 else
6758 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006759 } else {
6760 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6761 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6762 << E->getExprOperand()->getType()
6763 << E->getExprOperand()->getSourceRange();
6764 }
6765
6766 if (!Visit(E->getExprOperand()))
6767 return false;
6768
6769 Optional<DynamicType> DynType =
6770 ComputeDynamicType(Info, E, Result, AK_TypeId);
6771 if (!DynType)
6772 return false;
6773
6774 TypeInfo =
6775 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006776 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006777
Richard Smitha9330302019-05-17 19:19:28 +00006778 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006779}
6780
Francois Pichet0066db92012-04-16 04:08:35 +00006781bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6782 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006783}
Francois Pichet0066db92012-04-16 04:08:35 +00006784
Peter Collingbournee9200682011-05-13 03:29:01 +00006785bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006786 // Handle static data members.
6787 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006788 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006789 return VisitVarDecl(E, VD);
6790 }
6791
Richard Smith254a73d2011-10-28 22:34:42 +00006792 // Handle static member functions.
6793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6794 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006795 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006796 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006797 }
6798 }
6799
Richard Smithd62306a2011-11-10 06:34:14 +00006800 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006801 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006802}
6803
Peter Collingbournee9200682011-05-13 03:29:01 +00006804bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006805 // FIXME: Deal with vectors as array subscript bases.
6806 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006807 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006808
Nick Lewyckyad888682017-04-27 07:27:36 +00006809 bool Success = true;
6810 if (!evaluatePointer(E->getBase(), Result)) {
6811 if (!Info.noteFailure())
6812 return false;
6813 Success = false;
6814 }
Mike Stump11289f42009-09-09 15:08:12 +00006815
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006816 APSInt Index;
6817 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006818 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006819
Nick Lewyckyad888682017-04-27 07:27:36 +00006820 return Success &&
6821 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006822}
Eli Friedman9a156e52008-11-12 09:44:48 +00006823
Peter Collingbournee9200682011-05-13 03:29:01 +00006824bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006825 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006826}
6827
Richard Smith66c96992012-02-18 22:04:06 +00006828bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6829 if (!Visit(E->getSubExpr()))
6830 return false;
6831 // __real is a no-op on scalar lvalues.
6832 if (E->getSubExpr()->getType()->isAnyComplexType())
6833 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6834 return true;
6835}
6836
6837bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6838 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6839 "lvalue __imag__ on scalar?");
6840 if (!Visit(E->getSubExpr()))
6841 return false;
6842 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6843 return true;
6844}
6845
Richard Smith243ef902013-05-05 23:31:59 +00006846bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006847 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006848 return Error(UO);
6849
6850 if (!this->Visit(UO->getSubExpr()))
6851 return false;
6852
Richard Smith243ef902013-05-05 23:31:59 +00006853 return handleIncDec(
6854 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006855 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006856}
6857
6858bool LValueExprEvaluator::VisitCompoundAssignOperator(
6859 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006860 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006861 return Error(CAO);
6862
Richard Smith3229b742013-05-05 21:17:10 +00006863 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006864
6865 // The overall lvalue result is the result of evaluating the LHS.
6866 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006867 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006868 Evaluate(RHS, this->Info, CAO->getRHS());
6869 return false;
6870 }
6871
Richard Smith3229b742013-05-05 21:17:10 +00006872 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6873 return false;
6874
Richard Smith43e77732013-05-07 04:50:00 +00006875 return handleCompoundAssignment(
6876 this->Info, CAO,
6877 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6878 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006879}
6880
6881bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006883 return Error(E);
6884
Richard Smith3229b742013-05-05 21:17:10 +00006885 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006886
6887 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006888 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006889 Evaluate(NewVal, this->Info, E->getRHS());
6890 return false;
6891 }
6892
Richard Smith3229b742013-05-05 21:17:10 +00006893 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6894 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006895
Richard Smith31c69a32019-05-21 23:15:20 +00006896 if (Info.getLangOpts().CPlusPlus2a &&
6897 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6898 return false;
6899
Richard Smith243ef902013-05-05 23:31:59 +00006900 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006901 NewVal);
6902}
6903
Eli Friedman9a156e52008-11-12 09:44:48 +00006904//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006905// Pointer Evaluation
6906//===----------------------------------------------------------------------===//
6907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006908/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006909/// returned by a function with the alloc_size attribute. Returns true if we
6910/// were successful. Places an unsigned number into `Result`.
6911///
6912/// This expects the given CallExpr to be a call to a function with an
6913/// alloc_size attribute.
6914static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6915 const CallExpr *Call,
6916 llvm::APInt &Result) {
6917 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6918
Joel E. Denny81508102018-03-13 14:51:22 +00006919 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6920 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006921 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6922 if (Call->getNumArgs() <= SizeArgNo)
6923 return false;
6924
6925 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006926 Expr::EvalResult ExprResult;
6927 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006928 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006929 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006930 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6931 return false;
6932 Into = Into.zextOrSelf(BitsInSizeT);
6933 return true;
6934 };
6935
6936 APSInt SizeOfElem;
6937 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6938 return false;
6939
Joel E. Denny81508102018-03-13 14:51:22 +00006940 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006941 Result = std::move(SizeOfElem);
6942 return true;
6943 }
6944
6945 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006946 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006947 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6948 return false;
6949
6950 bool Overflow;
6951 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6952 if (Overflow)
6953 return false;
6954
6955 Result = std::move(BytesAvailable);
6956 return true;
6957}
6958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006959/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006960/// function.
6961static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6962 const LValue &LVal,
6963 llvm::APInt &Result) {
6964 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6965 "Can't get the size of a non alloc_size function");
6966 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6967 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6968 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6969}
6970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006971/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006972/// a function with the alloc_size attribute. If it was possible to do so, this
6973/// function will return true, make Result's Base point to said function call,
6974/// and mark Result's Base as invalid.
6975static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6976 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006977 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006978 return false;
6979
6980 // Because we do no form of static analysis, we only support const variables.
6981 //
6982 // Additionally, we can't support parameters, nor can we support static
6983 // variables (in the latter case, use-before-assign isn't UB; in the former,
6984 // we have no clue what they'll be assigned to).
6985 const auto *VD =
6986 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6987 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6988 return false;
6989
6990 const Expr *Init = VD->getAnyInitializer();
6991 if (!Init)
6992 return false;
6993
6994 const Expr *E = Init->IgnoreParens();
6995 if (!tryUnwrapAllocSizeCall(E))
6996 return false;
6997
6998 // Store E instead of E unwrapped so that the type of the LValue's base is
6999 // what the user wanted.
7000 Result.setInvalid(E);
7001
7002 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007003 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007004 return true;
7005}
7006
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007007namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007008class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007009 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007010 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007011 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007012
Peter Collingbournee9200682011-05-13 03:29:01 +00007013 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007014 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007015 return true;
7016 }
George Burgess IVe3763372016-12-22 02:50:20 +00007017
George Burgess IVf9013bf2017-02-10 22:52:29 +00007018 bool evaluateLValue(const Expr *E, LValue &Result) {
7019 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7020 }
7021
7022 bool evaluatePointer(const Expr *E, LValue &Result) {
7023 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7024 }
7025
George Burgess IVe3763372016-12-22 02:50:20 +00007026 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007027public:
Mike Stump11289f42009-09-09 15:08:12 +00007028
George Burgess IVf9013bf2017-02-10 22:52:29 +00007029 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7030 : ExprEvaluatorBaseTy(info), Result(Result),
7031 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007032
Richard Smith2e312c82012-03-03 22:46:17 +00007033 bool Success(const APValue &V, const Expr *E) {
7034 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007035 return true;
7036 }
Richard Smithfddd3842011-12-30 21:15:51 +00007037 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00007038 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7039 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00007040 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007041 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007042
John McCall45d55e42010-05-07 21:00:08 +00007043 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007044 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007045 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007046 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007047 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007048 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007049 if (E->isExpressibleAsConstantInitializer())
7050 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007051 if (Info.noteFailure())
7052 EvaluateIgnoredValue(Info, E->getSubExpr());
7053 return Error(E);
7054 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007055 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007056 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007057 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007058 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007059 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007060 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007061 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007062 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007063 }
Richard Smithd62306a2011-11-10 06:34:14 +00007064 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007065 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007066 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007067 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007068 if (!Info.CurrentCall->This) {
7069 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007070 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007071 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007072 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007073 return false;
7074 }
Richard Smithd62306a2011-11-10 06:34:14 +00007075 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007076 // If we are inside a lambda's call operator, the 'this' expression refers
7077 // to the enclosing '*this' object (either by value or reference) which is
7078 // either copied into the closure object's field that represents the '*this'
7079 // or refers to '*this'.
7080 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7081 // Update 'Result' to refer to the data member/field of the closure object
7082 // that represents the '*this' capture.
7083 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007084 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007085 return false;
7086 // If we captured '*this' by reference, replace the field with its referent.
7087 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7088 ->isPointerType()) {
7089 APValue RVal;
7090 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7091 RVal))
7092 return false;
7093
7094 Result.setFrom(Info.Ctx, RVal);
7095 }
7096 }
Richard Smithd62306a2011-11-10 06:34:14 +00007097 return true;
7098 }
John McCallc07a0c72011-02-17 10:25:35 +00007099
Eric Fiselier708afb52019-05-16 21:04:15 +00007100 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7101 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7102 APValue LValResult = E->EvaluateInContext(
7103 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7104 Result.setFrom(Info.Ctx, LValResult);
7105 return true;
7106 }
7107
Eli Friedman449fe542009-03-23 04:56:01 +00007108 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007109};
Chris Lattner05706e882008-07-11 18:11:29 +00007110} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007111
George Burgess IVf9013bf2017-02-10 22:52:29 +00007112static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7113 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007114 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007115 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007116}
7117
John McCall45d55e42010-05-07 21:00:08 +00007118bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007119 if (E->getOpcode() != BO_Add &&
7120 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007121 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007122
Chris Lattner05706e882008-07-11 18:11:29 +00007123 const Expr *PExp = E->getLHS();
7124 const Expr *IExp = E->getRHS();
7125 if (IExp->getType()->isPointerType())
7126 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007127
George Burgess IVf9013bf2017-02-10 22:52:29 +00007128 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007129 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007130 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007131
John McCall45d55e42010-05-07 21:00:08 +00007132 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007133 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007134 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007135
Richard Smith96e0c102011-11-04 02:25:55 +00007136 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007137 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007138
Ted Kremenek28831752012-08-23 20:46:57 +00007139 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007140 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007141}
Eli Friedman9a156e52008-11-12 09:44:48 +00007142
John McCall45d55e42010-05-07 21:00:08 +00007143bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007144 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007145}
Mike Stump11289f42009-09-09 15:08:12 +00007146
Richard Smith81dfef92018-07-11 00:29:05 +00007147bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7148 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007149
Eli Friedman847a2bc2009-12-27 05:43:15 +00007150 switch (E->getCastKind()) {
7151 default:
7152 break;
John McCalle3027922010-08-25 11:45:40 +00007153 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007154 case CK_CPointerToObjCPointerCast:
7155 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007156 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007157 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007158 if (!Visit(SubExpr))
7159 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007160 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7161 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7162 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007163 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007164 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007165 if (SubExpr->getType()->isVoidPointerType())
7166 CCEDiag(E, diag::note_constexpr_invalid_cast)
7167 << 3 << SubExpr->getType();
7168 else
7169 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7170 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007171 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7172 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007173 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007174
Anders Carlsson18275092010-10-31 20:41:46 +00007175 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007176 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007177 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007178 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007179 if (!Result.Base && Result.Offset.isZero())
7180 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007181
Richard Smithd62306a2011-11-10 06:34:14 +00007182 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007183 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007184 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7185 castAs<PointerType>()->getPointeeType(),
7186 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007187
Richard Smith027bf112011-11-17 22:56:20 +00007188 case CK_BaseToDerived:
7189 if (!Visit(E->getSubExpr()))
7190 return false;
7191 if (!Result.Base && Result.Offset.isZero())
7192 return true;
7193 return HandleBaseToDerivedCast(Info, E, Result);
7194
Richard Smith7bd54ab2019-05-15 20:22:21 +00007195 case CK_Dynamic:
7196 if (!Visit(E->getSubExpr()))
7197 return false;
7198 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7199
Richard Smith0b0a0b62011-10-29 20:57:55 +00007200 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007201 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007202 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007203
John McCalle3027922010-08-25 11:45:40 +00007204 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007205 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7206
Richard Smith2e312c82012-03-03 22:46:17 +00007207 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007208 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007209 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007210
John McCall45d55e42010-05-07 21:00:08 +00007211 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007212 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7213 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007214 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007215 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007216 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007217 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007218 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007219 return true;
7220 } else {
7221 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007222 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007223 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007224 }
7225 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007226
7227 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007228 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007229 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007230 return false;
7231 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007232 APValue &Value = createTemporary(SubExpr, false, Result,
7233 *Info.CurrentCall);
7234 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007235 return false;
7236 }
Richard Smith96e0c102011-11-04 02:25:55 +00007237 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007238 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7239 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007240 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007241 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007242 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007243 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007244 }
Richard Smithdd785442011-10-31 20:57:44 +00007245
John McCalle3027922010-08-25 11:45:40 +00007246 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007247 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007248
7249 case CK_LValueToRValue: {
7250 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007251 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007252 return false;
7253
7254 APValue RVal;
7255 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7256 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7257 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007258 return InvalidBaseOK &&
7259 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007260 return Success(RVal, E);
7261 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007262 }
7263
Richard Smith11562c52011-10-28 17:51:58 +00007264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007265}
Chris Lattner05706e882008-07-11 18:11:29 +00007266
Richard Smith6822bd72018-10-26 19:26:45 +00007267static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7268 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007269 // C++ [expr.alignof]p3:
7270 // When alignof is applied to a reference type, the result is the
7271 // alignment of the referenced type.
7272 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7273 T = Ref->getPointeeType();
7274
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007275 if (T.getQualifiers().hasUnaligned())
7276 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007277
7278 const bool AlignOfReturnsPreferred =
7279 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7280
7281 // __alignof is defined to return the preferred alignment.
7282 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7283 // as well.
7284 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7285 return Info.Ctx.toCharUnitsFromBits(
7286 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7287 // alignof and _Alignof are defined to return the ABI alignment.
7288 else if (ExprKind == UETT_AlignOf)
7289 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7290 else
7291 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007292}
7293
Richard Smith6822bd72018-10-26 19:26:45 +00007294static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7295 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007296 E = E->IgnoreParens();
7297
7298 // The kinds of expressions that we have special-case logic here for
7299 // should be kept up to date with the special checks for those
7300 // expressions in Sema.
7301
7302 // alignof decl is always accepted, even if it doesn't make sense: we default
7303 // to 1 in those cases.
7304 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7305 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7306 /*RefAsPointee*/true);
7307
7308 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7309 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7310 /*RefAsPointee*/true);
7311
Richard Smith6822bd72018-10-26 19:26:45 +00007312 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007313}
7314
George Burgess IVe3763372016-12-22 02:50:20 +00007315// To be clear: this happily visits unsupported builtins. Better name welcomed.
7316bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7317 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7318 return true;
7319
George Burgess IVf9013bf2017-02-10 22:52:29 +00007320 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007321 return false;
7322
7323 Result.setInvalid(E);
7324 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007325 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007326 return true;
7327}
7328
Peter Collingbournee9200682011-05-13 03:29:01 +00007329bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007330 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007331 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007332
Richard Smith6328cbd2016-11-16 00:57:23 +00007333 if (unsigned BuiltinOp = E->getBuiltinCallee())
7334 return VisitBuiltinCallExpr(E, BuiltinOp);
7335
George Burgess IVe3763372016-12-22 02:50:20 +00007336 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007337}
7338
7339bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7340 unsigned BuiltinOp) {
7341 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007342 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007343 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007344 case Builtin::BI__builtin_assume_aligned: {
7345 // We need to be very careful here because: if the pointer does not have the
7346 // asserted alignment, then the behavior is undefined, and undefined
7347 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007348 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007349 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007350
Hal Finkel0dd05d42014-10-03 17:18:37 +00007351 LValue OffsetResult(Result);
7352 APSInt Alignment;
7353 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7354 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007355 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007356
7357 if (E->getNumArgs() > 2) {
7358 APSInt Offset;
7359 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7360 return false;
7361
Richard Smith642a2362017-01-30 23:30:26 +00007362 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007363 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7364 }
7365
7366 // If there is a base object, then it must have the correct alignment.
7367 if (OffsetResult.Base) {
7368 CharUnits BaseAlignment;
7369 if (const ValueDecl *VD =
7370 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7371 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007372 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7373 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007374 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007375 BaseAlignment = GetAlignOfType(
7376 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007377 }
7378
7379 if (BaseAlignment < Align) {
7380 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007381 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007382 CCEDiag(E->getArg(0),
7383 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007384 << (unsigned)BaseAlignment.getQuantity()
7385 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007386 return false;
7387 }
7388 }
7389
7390 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007391 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007392 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007393
Richard Smith642a2362017-01-30 23:30:26 +00007394 (OffsetResult.Base
7395 ? CCEDiag(E->getArg(0),
7396 diag::note_constexpr_baa_insufficient_alignment) << 1
7397 : CCEDiag(E->getArg(0),
7398 diag::note_constexpr_baa_value_insufficient_alignment))
7399 << (int)OffsetResult.Offset.getQuantity()
7400 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007401 return false;
7402 }
7403
7404 return true;
7405 }
Eric Fiselier26187502018-12-14 21:11:28 +00007406 case Builtin::BI__builtin_launder:
7407 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007408 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007409 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007410 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007411 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007412 if (Info.getLangOpts().CPlusPlus11)
7413 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7414 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007415 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007416 else
7417 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007418 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007419 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007420 case Builtin::BI__builtin_wcschr:
7421 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007422 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007423 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007424 if (!Visit(E->getArg(0)))
7425 return false;
7426 APSInt Desired;
7427 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7428 return false;
7429 uint64_t MaxLength = uint64_t(-1);
7430 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007431 BuiltinOp != Builtin::BIwcschr &&
7432 BuiltinOp != Builtin::BI__builtin_strchr &&
7433 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007434 APSInt N;
7435 if (!EvaluateInteger(E->getArg(2), N, Info))
7436 return false;
7437 MaxLength = N.getExtValue();
7438 }
Hubert Tong147b7432018-12-12 16:53:43 +00007439 // We cannot find the value if there are no candidates to match against.
7440 if (MaxLength == 0u)
7441 return ZeroInitialization(E);
7442 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7443 Result.Designator.Invalid)
7444 return false;
7445 QualType CharTy = Result.Designator.getType(Info.Ctx);
7446 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7447 BuiltinOp == Builtin::BI__builtin_memchr;
7448 assert(IsRawByte ||
7449 Info.Ctx.hasSameUnqualifiedType(
7450 CharTy, E->getArg(0)->getType()->getPointeeType()));
7451 // Pointers to const void may point to objects of incomplete type.
7452 if (IsRawByte && CharTy->isIncompleteType()) {
7453 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7454 return false;
7455 }
7456 // Give up on byte-oriented matching against multibyte elements.
7457 // FIXME: We can compare the bytes in the correct order.
7458 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7459 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007460 // Figure out what value we're actually looking for (after converting to
7461 // the corresponding unsigned type if necessary).
7462 uint64_t DesiredVal;
7463 bool StopAtNull = false;
7464 switch (BuiltinOp) {
7465 case Builtin::BIstrchr:
7466 case Builtin::BI__builtin_strchr:
7467 // strchr compares directly to the passed integer, and therefore
7468 // always fails if given an int that is not a char.
7469 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7470 E->getArg(1)->getType(),
7471 Desired),
7472 Desired))
7473 return ZeroInitialization(E);
7474 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007475 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007476 case Builtin::BImemchr:
7477 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007478 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007479 // memchr compares by converting both sides to unsigned char. That's also
7480 // correct for strchr if we get this far (to cope with plain char being
7481 // unsigned in the strchr case).
7482 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7483 break;
Richard Smithe9507952016-11-12 01:39:56 +00007484
Richard Smith8110c9d2016-11-29 19:45:17 +00007485 case Builtin::BIwcschr:
7486 case Builtin::BI__builtin_wcschr:
7487 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007488 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007489 case Builtin::BIwmemchr:
7490 case Builtin::BI__builtin_wmemchr:
7491 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7492 DesiredVal = Desired.getZExtValue();
7493 break;
7494 }
Richard Smithe9507952016-11-12 01:39:56 +00007495
7496 for (; MaxLength; --MaxLength) {
7497 APValue Char;
7498 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7499 !Char.isInt())
7500 return false;
7501 if (Char.getInt().getZExtValue() == DesiredVal)
7502 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007503 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007504 break;
7505 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7506 return false;
7507 }
7508 // Not found: return nullptr.
7509 return ZeroInitialization(E);
7510 }
7511
Richard Smith06f71b52018-08-04 00:57:17 +00007512 case Builtin::BImemcpy:
7513 case Builtin::BImemmove:
7514 case Builtin::BIwmemcpy:
7515 case Builtin::BIwmemmove:
7516 if (Info.getLangOpts().CPlusPlus11)
7517 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7518 << /*isConstexpr*/0 << /*isConstructor*/0
7519 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7520 else
7521 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7522 LLVM_FALLTHROUGH;
7523 case Builtin::BI__builtin_memcpy:
7524 case Builtin::BI__builtin_memmove:
7525 case Builtin::BI__builtin_wmemcpy:
7526 case Builtin::BI__builtin_wmemmove: {
7527 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7528 BuiltinOp == Builtin::BIwmemmove ||
7529 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7530 BuiltinOp == Builtin::BI__builtin_wmemmove;
7531 bool Move = BuiltinOp == Builtin::BImemmove ||
7532 BuiltinOp == Builtin::BIwmemmove ||
7533 BuiltinOp == Builtin::BI__builtin_memmove ||
7534 BuiltinOp == Builtin::BI__builtin_wmemmove;
7535
7536 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007537 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007538 return false;
7539 LValue Dest = Result;
7540
7541 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007542 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007543 return false;
7544
7545 APSInt N;
7546 if (!EvaluateInteger(E->getArg(2), N, Info))
7547 return false;
7548 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7549
7550 // If the size is zero, we treat this as always being a valid no-op.
7551 // (Even if one of the src and dest pointers is null.)
7552 if (!N)
7553 return true;
7554
Richard Smith128719c2018-09-13 22:47:33 +00007555 // Otherwise, if either of the operands is null, we can't proceed. Don't
7556 // try to determine the type of the copied objects, because there aren't
7557 // any.
7558 if (!Src.Base || !Dest.Base) {
7559 APValue Val;
7560 (!Src.Base ? Src : Dest).moveInto(Val);
7561 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7562 << Move << WChar << !!Src.Base
7563 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7564 return false;
7565 }
7566 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7567 return false;
7568
Richard Smith06f71b52018-08-04 00:57:17 +00007569 // We require that Src and Dest are both pointers to arrays of
7570 // trivially-copyable type. (For the wide version, the designator will be
7571 // invalid if the designated object is not a wchar_t.)
7572 QualType T = Dest.Designator.getType(Info.Ctx);
7573 QualType SrcT = Src.Designator.getType(Info.Ctx);
7574 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7575 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7576 return false;
7577 }
Petr Pavlued083f22018-10-04 09:25:44 +00007578 if (T->isIncompleteType()) {
7579 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7580 return false;
7581 }
Richard Smith06f71b52018-08-04 00:57:17 +00007582 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7583 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7584 return false;
7585 }
7586
7587 // Figure out how many T's we're copying.
7588 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7589 if (!WChar) {
7590 uint64_t Remainder;
7591 llvm::APInt OrigN = N;
7592 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7593 if (Remainder) {
7594 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7595 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7596 << (unsigned)TSize;
7597 return false;
7598 }
7599 }
7600
7601 // Check that the copying will remain within the arrays, just so that we
7602 // can give a more meaningful diagnostic. This implicitly also checks that
7603 // N fits into 64 bits.
7604 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7605 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7606 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7607 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7608 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7609 << N.toString(10, /*Signed*/false);
7610 return false;
7611 }
7612 uint64_t NElems = N.getZExtValue();
7613 uint64_t NBytes = NElems * TSize;
7614
7615 // Check for overlap.
7616 int Direction = 1;
7617 if (HasSameBase(Src, Dest)) {
7618 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7619 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7620 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7621 // Dest is inside the source region.
7622 if (!Move) {
7623 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7624 return false;
7625 }
7626 // For memmove and friends, copy backwards.
7627 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7628 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7629 return false;
7630 Direction = -1;
7631 } else if (!Move && SrcOffset >= DestOffset &&
7632 SrcOffset - DestOffset < NBytes) {
7633 // Src is inside the destination region for memcpy: invalid.
7634 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7635 return false;
7636 }
7637 }
7638
7639 while (true) {
7640 APValue Val;
7641 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7642 !handleAssignment(Info, E, Dest, T, Val))
7643 return false;
7644 // Do not iterate past the last element; if we're copying backwards, that
7645 // might take us off the start of the array.
7646 if (--NElems == 0)
7647 return true;
7648 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7649 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7650 return false;
7651 }
7652 }
7653
Richard Smith6cbd65d2013-07-11 02:27:57 +00007654 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007655 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007656 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007657}
Chris Lattner05706e882008-07-11 18:11:29 +00007658
7659//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007660// Member Pointer Evaluation
7661//===----------------------------------------------------------------------===//
7662
7663namespace {
7664class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007665 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007666 MemberPtr &Result;
7667
7668 bool Success(const ValueDecl *D) {
7669 Result = MemberPtr(D);
7670 return true;
7671 }
7672public:
7673
7674 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7675 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7676
Richard Smith2e312c82012-03-03 22:46:17 +00007677 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007678 Result.setFrom(V);
7679 return true;
7680 }
Richard Smithfddd3842011-12-30 21:15:51 +00007681 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007682 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007683 }
7684
7685 bool VisitCastExpr(const CastExpr *E);
7686 bool VisitUnaryAddrOf(const UnaryOperator *E);
7687};
7688} // end anonymous namespace
7689
7690static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7691 EvalInfo &Info) {
7692 assert(E->isRValue() && E->getType()->isMemberPointerType());
7693 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7694}
7695
7696bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7697 switch (E->getCastKind()) {
7698 default:
7699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7700
7701 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007702 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007703 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007704
7705 case CK_BaseToDerivedMemberPointer: {
7706 if (!Visit(E->getSubExpr()))
7707 return false;
7708 if (E->path_empty())
7709 return true;
7710 // Base-to-derived member pointer casts store the path in derived-to-base
7711 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7712 // the wrong end of the derived->base arc, so stagger the path by one class.
7713 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7714 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7715 PathI != PathE; ++PathI) {
7716 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7717 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7718 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007719 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007720 }
7721 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7722 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007723 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007724 return true;
7725 }
7726
7727 case CK_DerivedToBaseMemberPointer:
7728 if (!Visit(E->getSubExpr()))
7729 return false;
7730 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7731 PathE = E->path_end(); PathI != PathE; ++PathI) {
7732 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7733 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7734 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007735 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007736 }
7737 return true;
7738 }
7739}
7740
7741bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7742 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7743 // member can be formed.
7744 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7745}
7746
7747//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007748// Record Evaluation
7749//===----------------------------------------------------------------------===//
7750
7751namespace {
7752 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007753 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007754 const LValue &This;
7755 APValue &Result;
7756 public:
7757
7758 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7759 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7760
Richard Smith2e312c82012-03-03 22:46:17 +00007761 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007762 Result = V;
7763 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007764 }
Richard Smithb8348f52016-05-12 22:16:28 +00007765 bool ZeroInitialization(const Expr *E) {
7766 return ZeroInitialization(E, E->getType());
7767 }
7768 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007769
Richard Smith52a980a2015-08-28 02:43:42 +00007770 bool VisitCallExpr(const CallExpr *E) {
7771 return handleCallExpr(E, Result, &This);
7772 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007773 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007774 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007775 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7776 return VisitCXXConstructExpr(E, E->getType());
7777 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007778 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007779 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007780 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007781 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007782
7783 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007784 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007785}
Richard Smithd62306a2011-11-10 06:34:14 +00007786
Richard Smithfddd3842011-12-30 21:15:51 +00007787/// Perform zero-initialization on an object of non-union class type.
7788/// C++11 [dcl.init]p5:
7789/// To zero-initialize an object or reference of type T means:
7790/// [...]
7791/// -- if T is a (possibly cv-qualified) non-union class type,
7792/// each non-static data member and each base-class subobject is
7793/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007794static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7795 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007796 const LValue &This, APValue &Result) {
7797 assert(!RD->isUnion() && "Expected non-union class type");
7798 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7799 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007800 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007801
John McCalld7bca762012-05-01 00:38:49 +00007802 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007803 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7804
7805 if (CD) {
7806 unsigned Index = 0;
7807 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007808 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007809 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7810 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007811 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7812 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007813 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007814 Result.getStructBase(Index)))
7815 return false;
7816 }
7817 }
7818
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007819 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007820 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007821 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007822 continue;
7823
7824 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007825 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007826 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007827
David Blaikie2d7c57e2012-04-30 02:36:29 +00007828 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007829 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007830 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007831 return false;
7832 }
7833
7834 return true;
7835}
7836
Richard Smithb8348f52016-05-12 22:16:28 +00007837bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7838 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007839 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007840 if (RD->isUnion()) {
7841 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7842 // object's first non-static named data member is zero-initialized
7843 RecordDecl::field_iterator I = RD->field_begin();
7844 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007845 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007846 return true;
7847 }
7848
7849 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007850 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007851 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007852 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007853 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007854 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007855 }
7856
Richard Smith5d108602012-02-17 00:44:16 +00007857 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007858 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007859 return false;
7860 }
7861
Richard Smitha8105bc2012-01-06 16:39:00 +00007862 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007863}
7864
Richard Smithe97cbd72011-11-11 04:05:33 +00007865bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7866 switch (E->getCastKind()) {
7867 default:
7868 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7869
7870 case CK_ConstructorConversion:
7871 return Visit(E->getSubExpr());
7872
7873 case CK_DerivedToBase:
7874 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007875 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007876 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007877 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007878 if (!DerivedObject.isStruct())
7879 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007880
7881 // Derived-to-base rvalue conversion: just slice off the derived part.
7882 APValue *Value = &DerivedObject;
7883 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7884 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7885 PathE = E->path_end(); PathI != PathE; ++PathI) {
7886 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7887 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7888 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7889 RD = Base;
7890 }
7891 Result = *Value;
7892 return true;
7893 }
7894 }
7895}
7896
Richard Smithd62306a2011-11-10 06:34:14 +00007897bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007898 if (E->isTransparent())
7899 return Visit(E->getInit(0));
7900
Richard Smithd62306a2011-11-10 06:34:14 +00007901 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007902 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007903 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007904 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7905
7906 EvalInfo::EvaluatingConstructorRAII EvalObj(
7907 Info,
7908 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7909 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007910
7911 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007912 const FieldDecl *Field = E->getInitializedFieldInUnion();
7913 Result = APValue(Field);
7914 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007915 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007916
7917 // If the initializer list for a union does not contain any elements, the
7918 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007919 // FIXME: The element should be initialized from an initializer list.
7920 // Is this difference ever observable for initializer lists which
7921 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007922 ImplicitValueInitExpr VIE(Field->getType());
7923 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7924
Richard Smithd62306a2011-11-10 06:34:14 +00007925 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007926 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7927 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007928
7929 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7930 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7931 isa<CXXDefaultInitExpr>(InitExpr));
7932
Richard Smithb228a862012-02-15 02:18:13 +00007933 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007934 }
7935
Richard Smithe637cbe2019-05-21 23:15:18 +00007936 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007937 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7938 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007939 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007940 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007941
7942 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007943 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007944 for (const auto &Base : CXXRD->bases()) {
7945 assert(ElementNo < E->getNumInits() && "missing init for base class");
7946 const Expr *Init = E->getInit(ElementNo);
7947
7948 LValue Subobject = This;
7949 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7950 return false;
7951
7952 APValue &FieldVal = Result.getStructBase(ElementNo);
7953 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007954 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007955 return false;
7956 Success = false;
7957 }
7958 ++ElementNo;
7959 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007960
7961 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007962 }
7963
7964 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007965 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007966 // Anonymous bit-fields are not considered members of the class for
7967 // purposes of aggregate initialization.
7968 if (Field->isUnnamedBitfield())
7969 continue;
7970
7971 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007972
Richard Smith253c2a32012-01-27 01:14:48 +00007973 bool HaveInit = ElementNo < E->getNumInits();
7974
7975 // FIXME: Diagnostics here should point to the end of the initializer
7976 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007977 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007978 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007979 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007980
7981 // Perform an implicit value-initialization for members beyond the end of
7982 // the initializer list.
7983 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007984 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007985
Richard Smith852c9db2013-04-20 22:23:05 +00007986 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7987 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7988 isa<CXXDefaultInitExpr>(Init));
7989
Richard Smith49ca8aa2013-08-06 07:09:20 +00007990 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7991 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7992 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007993 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007994 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007995 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007996 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007997 }
7998 }
7999
Richard Smith253c2a32012-01-27 01:14:48 +00008000 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008001}
8002
Richard Smithb8348f52016-05-12 22:16:28 +00008003bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8004 QualType T) {
8005 // Note that E's type is not necessarily the type of our class here; we might
8006 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008007 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008008 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8009
Richard Smithfddd3842011-12-30 21:15:51 +00008010 bool ZeroInit = E->requiresZeroInitialization();
8011 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008012 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008013 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008014 return true;
8015
Richard Smithda3f4fd2014-03-05 23:32:50 +00008016 // We can get here in two different ways:
8017 // 1) We're performing value-initialization, and should zero-initialize
8018 // the object, or
8019 // 2) We're performing default-initialization of an object with a trivial
8020 // constexpr default constructor, in which case we should start the
8021 // lifetimes of all the base subobjects (there can be no data member
8022 // subobjects in this case) per [basic.life]p1.
8023 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00008024 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00008025 }
8026
Craig Topper36250ad2014-05-12 05:36:57 +00008027 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008028 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00008029
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008030 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00008031 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008032
Richard Smith1bc5c2c2012-01-10 04:32:03 +00008033 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00008034 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00008035 if (const MaterializeTemporaryExpr *ME
8036 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8037 return Visit(ME->GetTemporaryExpr());
8038
Richard Smithb8348f52016-05-12 22:16:28 +00008039 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00008040 return false;
8041
Craig Topper5fc8fc22014-08-27 06:28:36 +00008042 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00008043 return HandleConstructorCall(E, This, Args,
8044 cast<CXXConstructorDecl>(Definition), Info,
8045 Result);
8046}
8047
8048bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8049 const CXXInheritedCtorInitExpr *E) {
8050 if (!Info.CurrentCall) {
8051 assert(Info.checkingPotentialConstantExpression());
8052 return false;
8053 }
8054
8055 const CXXConstructorDecl *FD = E->getConstructor();
8056 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8057 return false;
8058
8059 const FunctionDecl *Definition = nullptr;
8060 auto Body = FD->getBody(Definition);
8061
8062 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8063 return false;
8064
8065 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008066 cast<CXXConstructorDecl>(Definition), Info,
8067 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00008068}
8069
Richard Smithcc1b96d2013-06-12 22:31:48 +00008070bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8071 const CXXStdInitializerListExpr *E) {
8072 const ConstantArrayType *ArrayType =
8073 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8074
8075 LValue Array;
8076 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8077 return false;
8078
8079 // Get a pointer to the first element of the array.
8080 Array.addArray(Info, E, ArrayType);
8081
8082 // FIXME: Perform the checks on the field types in SemaInit.
8083 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8084 RecordDecl::field_iterator Field = Record->field_begin();
8085 if (Field == Record->field_end())
8086 return Error(E);
8087
8088 // Start pointer.
8089 if (!Field->getType()->isPointerType() ||
8090 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8091 ArrayType->getElementType()))
8092 return Error(E);
8093
8094 // FIXME: What if the initializer_list type has base classes, etc?
8095 Result = APValue(APValue::UninitStruct(), 0, 2);
8096 Array.moveInto(Result.getStructField(0));
8097
8098 if (++Field == Record->field_end())
8099 return Error(E);
8100
8101 if (Field->getType()->isPointerType() &&
8102 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8103 ArrayType->getElementType())) {
8104 // End pointer.
8105 if (!HandleLValueArrayAdjustment(Info, E, Array,
8106 ArrayType->getElementType(),
8107 ArrayType->getSize().getZExtValue()))
8108 return false;
8109 Array.moveInto(Result.getStructField(1));
8110 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8111 // Length.
8112 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8113 else
8114 return Error(E);
8115
8116 if (++Field != Record->field_end())
8117 return Error(E);
8118
8119 return true;
8120}
8121
Faisal Valic72a08c2017-01-09 03:02:53 +00008122bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8123 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8124 if (ClosureClass->isInvalidDecl()) return false;
8125
8126 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008127
Faisal Vali051e3a22017-02-16 04:12:21 +00008128 const size_t NumFields =
8129 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008130
8131 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8132 E->capture_init_end()) &&
8133 "The number of lambda capture initializers should equal the number of "
8134 "fields within the closure type");
8135
Faisal Vali051e3a22017-02-16 04:12:21 +00008136 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8137 // Iterate through all the lambda's closure object's fields and initialize
8138 // them.
8139 auto *CaptureInitIt = E->capture_init_begin();
8140 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8141 bool Success = true;
8142 for (const auto *Field : ClosureClass->fields()) {
8143 assert(CaptureInitIt != E->capture_init_end());
8144 // Get the initializer for this field
8145 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008146
Faisal Vali051e3a22017-02-16 04:12:21 +00008147 // If there is no initializer, either this is a VLA or an error has
8148 // occurred.
8149 if (!CurFieldInit)
8150 return Error(E);
8151
8152 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8153 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8154 if (!Info.keepEvaluatingAfterFailure())
8155 return false;
8156 Success = false;
8157 }
8158 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008159 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008160 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008161}
8162
Richard Smithd62306a2011-11-10 06:34:14 +00008163static bool EvaluateRecord(const Expr *E, const LValue &This,
8164 APValue &Result, EvalInfo &Info) {
8165 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008166 "can't evaluate expression as a record rvalue");
8167 return RecordExprEvaluator(Info, This, Result).Visit(E);
8168}
8169
8170//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008171// Temporary Evaluation
8172//
8173// Temporaries are represented in the AST as rvalues, but generally behave like
8174// lvalues. The full-object of which the temporary is a subobject is implicitly
8175// materialized so that a reference can bind to it.
8176//===----------------------------------------------------------------------===//
8177namespace {
8178class TemporaryExprEvaluator
8179 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8180public:
8181 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008182 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008183
8184 /// Visit an expression which constructs the value of this temporary.
8185 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008186 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8187 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008188 }
8189
8190 bool VisitCastExpr(const CastExpr *E) {
8191 switch (E->getCastKind()) {
8192 default:
8193 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8194
8195 case CK_ConstructorConversion:
8196 return VisitConstructExpr(E->getSubExpr());
8197 }
8198 }
8199 bool VisitInitListExpr(const InitListExpr *E) {
8200 return VisitConstructExpr(E);
8201 }
8202 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8203 return VisitConstructExpr(E);
8204 }
8205 bool VisitCallExpr(const CallExpr *E) {
8206 return VisitConstructExpr(E);
8207 }
Richard Smith513955c2014-12-17 19:24:30 +00008208 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8209 return VisitConstructExpr(E);
8210 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008211 bool VisitLambdaExpr(const LambdaExpr *E) {
8212 return VisitConstructExpr(E);
8213 }
Richard Smith027bf112011-11-17 22:56:20 +00008214};
8215} // end anonymous namespace
8216
8217/// Evaluate an expression of record type as a temporary.
8218static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008219 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008220 return TemporaryExprEvaluator(Info, Result).Visit(E);
8221}
8222
8223//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008224// Vector Evaluation
8225//===----------------------------------------------------------------------===//
8226
8227namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008228 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008229 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008230 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008231 public:
Mike Stump11289f42009-09-09 15:08:12 +00008232
Richard Smith2d406342011-10-22 21:10:00 +00008233 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8234 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008235
Craig Topper9798b932015-09-29 04:30:05 +00008236 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8238 // FIXME: remove this APValue copy.
8239 Result = APValue(V.data(), V.size());
8240 return true;
8241 }
Richard Smith2e312c82012-03-03 22:46:17 +00008242 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008243 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008244 Result = V;
8245 return true;
8246 }
Richard Smithfddd3842011-12-30 21:15:51 +00008247 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008248
Richard Smith2d406342011-10-22 21:10:00 +00008249 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008250 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008251 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008252 bool VisitInitListExpr(const InitListExpr *E);
8253 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008254 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008255 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008256 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008257 };
8258} // end anonymous namespace
8259
8260static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008261 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008262 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008263}
8264
George Burgess IV533ff002015-12-11 00:23:35 +00008265bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008266 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008267 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008268
Richard Smith161f09a2011-12-06 22:44:34 +00008269 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008270 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008271
Eli Friedmanc757de22011-03-25 00:43:55 +00008272 switch (E->getCastKind()) {
8273 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008274 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008275 if (SETy->isIntegerType()) {
8276 APSInt IntResult;
8277 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008278 return false;
8279 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008280 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008281 APFloat FloatResult(0.0);
8282 if (!EvaluateFloat(SE, FloatResult, Info))
8283 return false;
8284 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008285 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008286 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008287 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008288
8289 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008290 SmallVector<APValue, 4> Elts(NElts, Val);
8291 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008292 }
Eli Friedman803acb32011-12-22 03:51:45 +00008293 case CK_BitCast: {
8294 // Evaluate the operand into an APInt we can extract from.
8295 llvm::APInt SValInt;
8296 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8297 return false;
8298 // Extract the elements
8299 QualType EltTy = VTy->getElementType();
8300 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8301 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8302 SmallVector<APValue, 4> Elts;
8303 if (EltTy->isRealFloatingType()) {
8304 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008305 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008306 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008307 FloatEltSize = 80;
8308 for (unsigned i = 0; i < NElts; i++) {
8309 llvm::APInt Elt;
8310 if (BigEndian)
8311 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8312 else
8313 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008314 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008315 }
8316 } else if (EltTy->isIntegerType()) {
8317 for (unsigned i = 0; i < NElts; i++) {
8318 llvm::APInt Elt;
8319 if (BigEndian)
8320 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8321 else
8322 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8323 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8324 }
8325 } else {
8326 return Error(E);
8327 }
8328 return Success(Elts, E);
8329 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008330 default:
Richard Smith11562c52011-10-28 17:51:58 +00008331 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008332 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008333}
8334
Richard Smith2d406342011-10-22 21:10:00 +00008335bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008336VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008337 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008338 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008339 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008340
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008341 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008342 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008343
Eli Friedmanb9c71292012-01-03 23:24:20 +00008344 // The number of initializers can be less than the number of
8345 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008346 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008347 // should be initialized with zeroes.
8348 unsigned CountInits = 0, CountElts = 0;
8349 while (CountElts < NumElements) {
8350 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008351 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008352 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008353 APValue v;
8354 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8355 return Error(E);
8356 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008357 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008358 Elements.push_back(v.getVectorElt(j));
8359 CountElts += vlen;
8360 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008361 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008362 if (CountInits < NumInits) {
8363 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008364 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008365 } else // trailing integer zero.
8366 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8367 Elements.push_back(APValue(sInt));
8368 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008369 } else {
8370 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008371 if (CountInits < NumInits) {
8372 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008373 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008374 } else // trailing float zero.
8375 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8376 Elements.push_back(APValue(f));
8377 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00008378 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00008379 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008380 }
Richard Smith2d406342011-10-22 21:10:00 +00008381 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008382}
8383
Richard Smith2d406342011-10-22 21:10:00 +00008384bool
Richard Smithfddd3842011-12-30 21:15:51 +00008385VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008386 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00008387 QualType EltTy = VT->getElementType();
8388 APValue ZeroElement;
8389 if (EltTy->isIntegerType())
8390 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8391 else
8392 ZeroElement =
8393 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8394
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008395 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00008396 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008397}
8398
Richard Smith2d406342011-10-22 21:10:00 +00008399bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00008400 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008401 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008402}
8403
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008404//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00008405// Array Evaluation
8406//===----------------------------------------------------------------------===//
8407
8408namespace {
8409 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008410 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008411 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00008412 APValue &Result;
8413 public:
8414
Richard Smithd62306a2011-11-10 06:34:14 +00008415 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8416 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00008417
8418 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00008419 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00008420 Result = V;
8421 return true;
8422 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008423
Richard Smithfddd3842011-12-30 21:15:51 +00008424 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008425 const ConstantArrayType *CAT =
8426 Info.Ctx.getAsConstantArrayType(E->getType());
8427 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008428 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008429
8430 Result = APValue(APValue::UninitArray(), 0,
8431 CAT->getSize().getZExtValue());
8432 if (!Result.hasArrayFiller()) return true;
8433
Richard Smithfddd3842011-12-30 21:15:51 +00008434 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00008435 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008436 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00008437 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00008438 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00008439 }
8440
Richard Smith52a980a2015-08-28 02:43:42 +00008441 bool VisitCallExpr(const CallExpr *E) {
8442 return handleCallExpr(E, Result, &This);
8443 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008444 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00008445 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00008446 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00008447 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8448 const LValue &Subobject,
8449 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00008450 bool VisitStringLiteral(const StringLiteral *E) {
8451 expandStringLiteral(Info, E, Result);
8452 return true;
8453 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008454 };
8455} // end anonymous namespace
8456
Richard Smithd62306a2011-11-10 06:34:14 +00008457static bool EvaluateArray(const Expr *E, const LValue &This,
8458 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00008459 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00008460 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008461}
8462
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008463// Return true iff the given array filler may depend on the element index.
8464static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8465 // For now, just whitelist non-class value-initialization and initialization
8466 // lists comprised of them.
8467 if (isa<ImplicitValueInitExpr>(FillerExpr))
8468 return false;
8469 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8470 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8471 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8472 return true;
8473 }
8474 return false;
8475 }
8476 return true;
8477}
8478
Richard Smithf3e9e432011-11-07 09:22:26 +00008479bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8480 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8481 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008482 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008483
Richard Smithca2cfbf2011-12-22 01:07:19 +00008484 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8485 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00008486 if (E->isStringLiteralInit())
8487 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00008488
Richard Smith253c2a32012-01-27 01:14:48 +00008489 bool Success = true;
8490
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008491 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8492 "zero-initialized array shouldn't have any initialized elts");
8493 APValue Filler;
8494 if (Result.isArray() && Result.hasArrayFiller())
8495 Filler = Result.getArrayFiller();
8496
Richard Smith9543c5e2013-04-22 14:44:29 +00008497 unsigned NumEltsToInit = E->getNumInits();
8498 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008499 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008500
8501 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008502 // array element.
8503 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008504 NumEltsToInit = NumElts;
8505
Nicola Zaghen3538b392018-05-15 13:30:56 +00008506 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8507 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008508
Richard Smith9543c5e2013-04-22 14:44:29 +00008509 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008510
8511 // If the array was previously zero-initialized, preserve the
8512 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008513 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008514 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8515 Result.getArrayInitializedElt(I) = Filler;
8516 if (Result.hasArrayFiller())
8517 Result.getArrayFiller() = Filler;
8518 }
8519
Richard Smithd62306a2011-11-10 06:34:14 +00008520 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008521 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008522 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8523 const Expr *Init =
8524 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008525 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008526 Info, Subobject, Init) ||
8527 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008528 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008529 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008530 return false;
8531 Success = false;
8532 }
Richard Smithd62306a2011-11-10 06:34:14 +00008533 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008534
Richard Smith9543c5e2013-04-22 14:44:29 +00008535 if (!Result.hasArrayFiller())
8536 return Success;
8537
8538 // If we get here, we have a trivial filler, which we can just evaluate
8539 // once and splat over the rest of the array elements.
8540 assert(FillerExpr && "no array filler for incomplete init list");
8541 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8542 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008543}
8544
Richard Smith410306b2016-12-12 02:53:20 +00008545bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8546 if (E->getCommonExpr() &&
8547 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8548 Info, E->getCommonExpr()->getSourceExpr()))
8549 return false;
8550
8551 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8552
8553 uint64_t Elements = CAT->getSize().getZExtValue();
8554 Result = APValue(APValue::UninitArray(), Elements, Elements);
8555
8556 LValue Subobject = This;
8557 Subobject.addArray(Info, E, CAT);
8558
8559 bool Success = true;
8560 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8561 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8562 Info, Subobject, E->getSubExpr()) ||
8563 !HandleLValueArrayAdjustment(Info, E, Subobject,
8564 CAT->getElementType(), 1)) {
8565 if (!Info.noteFailure())
8566 return false;
8567 Success = false;
8568 }
8569 }
8570
8571 return Success;
8572}
8573
Richard Smith027bf112011-11-17 22:56:20 +00008574bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008575 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8576}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008577
Richard Smith9543c5e2013-04-22 14:44:29 +00008578bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8579 const LValue &Subobject,
8580 APValue *Value,
8581 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008582 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008583
8584 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8585 unsigned N = CAT->getSize().getZExtValue();
8586
8587 // Preserve the array filler if we had prior zero-initialization.
8588 APValue Filler =
8589 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8590 : APValue();
8591
8592 *Value = APValue(APValue::UninitArray(), N, N);
8593
8594 if (HadZeroInit)
8595 for (unsigned I = 0; I != N; ++I)
8596 Value->getArrayInitializedElt(I) = Filler;
8597
8598 // Initialize the elements.
8599 LValue ArrayElt = Subobject;
8600 ArrayElt.addArray(Info, E, CAT);
8601 for (unsigned I = 0; I != N; ++I)
8602 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8603 CAT->getElementType()) ||
8604 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8605 CAT->getElementType(), 1))
8606 return false;
8607
8608 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008609 }
Richard Smith027bf112011-11-17 22:56:20 +00008610
Richard Smith9543c5e2013-04-22 14:44:29 +00008611 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008612 return Error(E);
8613
Richard Smithb8348f52016-05-12 22:16:28 +00008614 return RecordExprEvaluator(Info, Subobject, *Value)
8615 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008616}
8617
Richard Smithf3e9e432011-11-07 09:22:26 +00008618//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008619// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008620//
8621// As a GNU extension, we support casting pointers to sufficiently-wide integer
8622// types and back in constant folding. Integer values are thus represented
8623// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008624//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008625
8626namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008627class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008628 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008629 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008630public:
Richard Smith2e312c82012-03-03 22:46:17 +00008631 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008632 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008633
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008634 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008635 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008636 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008637 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008638 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008639 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008640 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008641 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008642 return true;
8643 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008644 bool Success(const llvm::APSInt &SI, const Expr *E) {
8645 return Success(SI, E, Result);
8646 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008647
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008648 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008649 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008650 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008651 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008652 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008653 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008654 Result.getInt().setIsUnsigned(
8655 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008656 return true;
8657 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008658 bool Success(const llvm::APInt &I, const Expr *E) {
8659 return Success(I, E, Result);
8660 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008661
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008662 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008663 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008664 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008665 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008666 return true;
8667 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008668 bool Success(uint64_t Value, const Expr *E) {
8669 return Success(Value, E, Result);
8670 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008671
Ken Dyckdbc01912011-03-11 02:13:43 +00008672 bool Success(CharUnits Size, const Expr *E) {
8673 return Success(Size.getQuantity(), E);
8674 }
8675
Richard Smith2e312c82012-03-03 22:46:17 +00008676 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00008677 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008678 Result = V;
8679 return true;
8680 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008681 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008682 }
Mike Stump11289f42009-09-09 15:08:12 +00008683
Richard Smithfddd3842011-12-30 21:15:51 +00008684 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008685
Peter Collingbournee9200682011-05-13 03:29:01 +00008686 //===--------------------------------------------------------------------===//
8687 // Visitor Methods
8688 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008689
Fangrui Song407659a2018-11-30 23:41:18 +00008690 bool VisitConstantExpr(const ConstantExpr *E);
8691
Chris Lattner7174bf32008-07-12 00:38:25 +00008692 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008693 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008694 }
8695 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008696 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008697 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008698
8699 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8700 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008701 if (CheckReferencedDecl(E, E->getDecl()))
8702 return true;
8703
8704 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008705 }
8706 bool VisitMemberExpr(const MemberExpr *E) {
8707 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008708 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008709 return true;
8710 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008711
8712 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008713 }
8714
Peter Collingbournee9200682011-05-13 03:29:01 +00008715 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008716 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008717 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008718 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008719 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008720
Peter Collingbournee9200682011-05-13 03:29:01 +00008721 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008722 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008723
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008724 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008725 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008726 }
Mike Stump11289f42009-09-09 15:08:12 +00008727
Ted Kremeneke65b0862012-03-06 20:05:56 +00008728 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8729 return Success(E->getValue(), E);
8730 }
Richard Smith410306b2016-12-12 02:53:20 +00008731
8732 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8733 if (Info.ArrayInitIndex == uint64_t(-1)) {
8734 // We were asked to evaluate this subexpression independent of the
8735 // enclosing ArrayInitLoopExpr. We can't do that.
8736 Info.FFDiag(E);
8737 return false;
8738 }
8739 return Success(Info.ArrayInitIndex, E);
8740 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008741
Richard Smith4ce706a2011-10-11 21:43:33 +00008742 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008743 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008744 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008745 }
8746
Douglas Gregor29c42f22012-02-24 07:38:34 +00008747 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8748 return Success(E->getValue(), E);
8749 }
8750
John Wiegley6242b6a2011-04-28 00:16:57 +00008751 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8752 return Success(E->getValue(), E);
8753 }
8754
John Wiegleyf9f65842011-04-25 06:54:41 +00008755 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8756 return Success(E->getValue(), E);
8757 }
8758
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008759 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008760 bool VisitUnaryImag(const UnaryOperator *E);
8761
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008762 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008763 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008764 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008765 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008766};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008767
8768class FixedPointExprEvaluator
8769 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8770 APValue &Result;
8771
8772 public:
8773 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8774 : ExprEvaluatorBaseTy(info), Result(result) {}
8775
Leonard Chandb01c3a2018-06-20 17:19:40 +00008776 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008777 return Success(
8778 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008779 }
8780
Leonard Chandb01c3a2018-06-20 17:19:40 +00008781 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008782 return Success(
8783 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008784 }
8785
8786 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008787 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008788 }
8789
Leonard Chand3f3e162019-01-18 21:04:25 +00008790 bool Success(const APFixedPoint &V, const Expr *E) {
8791 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8792 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8793 "Invalid evaluation result.");
8794 Result = APValue(V);
8795 return true;
8796 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008797
8798 //===--------------------------------------------------------------------===//
8799 // Visitor Methods
8800 //===--------------------------------------------------------------------===//
8801
8802 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8803 return Success(E->getValue(), E);
8804 }
8805
Leonard Chand3f3e162019-01-18 21:04:25 +00008806 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008807 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008808 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008809};
Chris Lattner05706e882008-07-11 18:11:29 +00008810} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008811
Richard Smith11562c52011-10-28 17:51:58 +00008812/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8813/// produce either the integer value or a pointer.
8814///
8815/// GCC has a heinous extension which folds casts between pointer types and
8816/// pointer-sized integral types. We support this by allowing the evaluation of
8817/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8818/// Some simple arithmetic on such values is supported (they are treated much
8819/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008820static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008821 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008822 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008823 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008824}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008825
Richard Smithf57d8cb2011-12-09 22:58:01 +00008826static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008827 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008828 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008829 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008830 if (!Val.isInt()) {
8831 // FIXME: It would be better to produce the diagnostic for casting
8832 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008833 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008834 return false;
8835 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008836 Result = Val.getInt();
8837 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008838}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008839
Eric Fiselier708afb52019-05-16 21:04:15 +00008840bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8841 APValue Evaluated = E->EvaluateInContext(
8842 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8843 return Success(Evaluated, E);
8844}
8845
Leonard Chand3f3e162019-01-18 21:04:25 +00008846static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8847 EvalInfo &Info) {
8848 if (E->getType()->isFixedPointType()) {
8849 APValue Val;
8850 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8851 return false;
8852 if (!Val.isFixedPoint())
8853 return false;
8854
8855 Result = Val.getFixedPoint();
8856 return true;
8857 }
8858 return false;
8859}
8860
8861static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8862 EvalInfo &Info) {
8863 if (E->getType()->isIntegerType()) {
8864 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8865 APSInt Val;
8866 if (!EvaluateInteger(E, Val, Info))
8867 return false;
8868 Result = APFixedPoint(Val, FXSema);
8869 return true;
8870 } else if (E->getType()->isFixedPointType()) {
8871 return EvaluateFixedPoint(E, Result, Info);
8872 }
8873 return false;
8874}
8875
Richard Smithf57d8cb2011-12-09 22:58:01 +00008876/// Check whether the given declaration can be directly converted to an integral
8877/// rvalue. If not, no diagnostic is produced; there are other things we can
8878/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008879bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008880 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008881 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008882 // Check for signedness/width mismatches between E type and ECD value.
8883 bool SameSign = (ECD->getInitVal().isSigned()
8884 == E->getType()->isSignedIntegerOrEnumerationType());
8885 bool SameWidth = (ECD->getInitVal().getBitWidth()
8886 == Info.Ctx.getIntWidth(E->getType()));
8887 if (SameSign && SameWidth)
8888 return Success(ECD->getInitVal(), E);
8889 else {
8890 // Get rid of mismatch (otherwise Success assertions will fail)
8891 // by computing a new value matching the type of E.
8892 llvm::APSInt Val = ECD->getInitVal();
8893 if (!SameSign)
8894 Val.setIsSigned(!ECD->getInitVal().isSigned());
8895 if (!SameWidth)
8896 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8897 return Success(Val, E);
8898 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008899 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008900 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008901}
8902
Richard Smith08b682b2018-05-23 21:18:00 +00008903/// Values returned by __builtin_classify_type, chosen to match the values
8904/// produced by GCC's builtin.
8905enum class GCCTypeClass {
8906 None = -1,
8907 Void = 0,
8908 Integer = 1,
8909 // GCC reserves 2 for character types, but instead classifies them as
8910 // integers.
8911 Enum = 3,
8912 Bool = 4,
8913 Pointer = 5,
8914 // GCC reserves 6 for references, but appears to never use it (because
8915 // expressions never have reference type, presumably).
8916 PointerToDataMember = 7,
8917 RealFloat = 8,
8918 Complex = 9,
8919 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8920 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8921 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8922 // uses 12 for that purpose, same as for a class or struct. Maybe it
8923 // internally implements a pointer to member as a struct? Who knows.
8924 PointerToMemberFunction = 12, // Not a bug, see above.
8925 ClassOrStruct = 12,
8926 Union = 13,
8927 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8928 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8929 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8930 // literals.
8931};
8932
Chris Lattner86ee2862008-10-06 06:40:35 +00008933/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8934/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008935static GCCTypeClass
8936EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8937 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008938
Richard Smith08b682b2018-05-23 21:18:00 +00008939 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008940 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8941
8942 switch (CanTy->getTypeClass()) {
8943#define TYPE(ID, BASE)
8944#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8945#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8946#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8947#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008948 case Type::Auto:
8949 case Type::DeducedTemplateSpecialization:
8950 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008951
8952 case Type::Builtin:
8953 switch (BT->getKind()) {
8954#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008955#define SIGNED_TYPE(ID, SINGLETON_ID) \
8956 case BuiltinType::ID: return GCCTypeClass::Integer;
8957#define FLOATING_TYPE(ID, SINGLETON_ID) \
8958 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8959#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8960 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008961#include "clang/AST/BuiltinTypes.def"
8962 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008963 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008964
8965 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008966 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008967
Richard Smith08b682b2018-05-23 21:18:00 +00008968 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008969 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008970 case BuiltinType::WChar_U:
8971 case BuiltinType::Char8:
8972 case BuiltinType::Char16:
8973 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008974 case BuiltinType::UShort:
8975 case BuiltinType::UInt:
8976 case BuiltinType::ULong:
8977 case BuiltinType::ULongLong:
8978 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008979 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008980
Leonard Chanf921d852018-06-04 16:07:52 +00008981 case BuiltinType::UShortAccum:
8982 case BuiltinType::UAccum:
8983 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008984 case BuiltinType::UShortFract:
8985 case BuiltinType::UFract:
8986 case BuiltinType::ULongFract:
8987 case BuiltinType::SatUShortAccum:
8988 case BuiltinType::SatUAccum:
8989 case BuiltinType::SatULongAccum:
8990 case BuiltinType::SatUShortFract:
8991 case BuiltinType::SatUFract:
8992 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008993 return GCCTypeClass::None;
8994
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008995 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008996
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008997 case BuiltinType::ObjCId:
8998 case BuiltinType::ObjCClass:
8999 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00009000#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9001 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00009002#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00009003#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9004 case BuiltinType::Id:
9005#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009006 case BuiltinType::OCLSampler:
9007 case BuiltinType::OCLEvent:
9008 case BuiltinType::OCLClkEvent:
9009 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009010 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00009011#define SVE_TYPE(Name, Id, SingletonId) \
9012 case BuiltinType::Id:
9013#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00009014 return GCCTypeClass::None;
9015
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009016 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00009017 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009018 };
Richard Smith08b682b2018-05-23 21:18:00 +00009019 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009020
9021 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00009022 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009023
9024 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009025 case Type::ConstantArray:
9026 case Type::VariableArray:
9027 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00009028 case Type::FunctionNoProto:
9029 case Type::FunctionProto:
9030 return GCCTypeClass::Pointer;
9031
9032 case Type::MemberPointer:
9033 return CanTy->isMemberDataPointerType()
9034 ? GCCTypeClass::PointerToDataMember
9035 : GCCTypeClass::PointerToMemberFunction;
9036
9037 case Type::Complex:
9038 return GCCTypeClass::Complex;
9039
9040 case Type::Record:
9041 return CanTy->isUnionType() ? GCCTypeClass::Union
9042 : GCCTypeClass::ClassOrStruct;
9043
9044 case Type::Atomic:
9045 // GCC classifies _Atomic T the same as T.
9046 return EvaluateBuiltinClassifyType(
9047 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009048
9049 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009050 case Type::Vector:
9051 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009052 case Type::ObjCObject:
9053 case Type::ObjCInterface:
9054 case Type::ObjCObjectPointer:
9055 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00009056 // GCC classifies vectors as None. We follow its lead and classify all
9057 // other types that don't fit into the regular classification the same way.
9058 return GCCTypeClass::None;
9059
9060 case Type::LValueReference:
9061 case Type::RValueReference:
9062 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009063 }
9064
Richard Smith08b682b2018-05-23 21:18:00 +00009065 llvm_unreachable("unexpected type class");
9066}
9067
9068/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9069/// as GCC.
9070static GCCTypeClass
9071EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9072 // If no argument was supplied, default to None. This isn't
9073 // ideal, however it is what gcc does.
9074 if (E->getNumArgs() == 0)
9075 return GCCTypeClass::None;
9076
9077 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9078 // being an ICE, but still folds it to a constant using the type of the first
9079 // argument.
9080 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00009081}
9082
Richard Smith5fab0c92011-12-28 19:48:30 +00009083/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00009084/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00009085///
Richard Smith31cfb312019-04-27 02:58:17 +00009086/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9087/// or it points to the first character of a string literal.
9088static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9089 APValue::LValueBase Base = LV.getLValueBase();
9090 if (Base.isNull()) {
9091 // A null base is acceptable.
9092 return true;
9093 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9094 if (!isa<StringLiteral>(E))
9095 return false;
9096 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00009097 } else if (Base.is<TypeInfoLValue>()) {
9098 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9099 // evaluate to true.
9100 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00009101 } else {
9102 // Any other base is not constant enough for GCC.
9103 return false;
9104 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009105}
9106
9107/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9108/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009109static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009110 // This evaluation is not permitted to have side-effects, so evaluate it in
9111 // a speculative evaluation context.
9112 SpeculativeEvaluationRAII SpeculativeEval(Info);
9113
Richard Smith31cfb312019-04-27 02:58:17 +00009114 // Constant-folding is always enabled for the operand of __builtin_constant_p
9115 // (even when the enclosing evaluation context otherwise requires a strict
9116 // language-specific constant expression).
9117 FoldConstant Fold(Info, true);
9118
Richard Smith5fab0c92011-12-28 19:48:30 +00009119 QualType ArgType = Arg->getType();
9120
9121 // __builtin_constant_p always has one operand. The rules which gcc follows
9122 // are not precisely documented, but are as follows:
9123 //
9124 // - If the operand is of integral, floating, complex or enumeration type,
9125 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009126 // - If the operand can be folded to a pointer to the first character
9127 // of a string literal (or such a pointer cast to an integral type)
9128 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009129 //
9130 // Otherwise, it returns 0.
9131 //
9132 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009133 // its support for this did not work prior to GCC 9 and is not yet well
9134 // understood.
9135 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9136 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9137 ArgType->isNullPtrType()) {
9138 APValue V;
9139 if (!::EvaluateAsRValue(Info, Arg, V)) {
9140 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009141 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009142 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009143
Richard Smith31cfb312019-04-27 02:58:17 +00009144 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009145 if (V.getKind() == APValue::LValue)
9146 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009147
9148 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009149 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009150 }
9151
9152 // Anything else isn't considered to be sufficiently constant.
9153 return false;
9154}
9155
John McCall95007602010-05-10 23:27:23 +00009156/// Retrieves the "underlying object type" of the given expression,
9157/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009158static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009159 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9160 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009161 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009162 } else if (const Expr *E = B.get<const Expr*>()) {
9163 if (isa<CompoundLiteralExpr>(E))
9164 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009165 } else if (B.is<TypeInfoLValue>()) {
9166 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00009167 }
9168
9169 return QualType();
9170}
9171
George Burgess IV3a03fab2015-09-04 21:28:13 +00009172/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009173/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009174/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009175/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9176///
9177/// Always returns an RValue with a pointer representation.
9178static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9179 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9180
9181 auto *NoParens = E->IgnoreParens();
9182 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009183 if (Cast == nullptr)
9184 return NoParens;
9185
9186 // We only conservatively allow a few kinds of casts, because this code is
9187 // inherently a simple solution that seeks to support the common case.
9188 auto CastKind = Cast->getCastKind();
9189 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9190 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009191 return NoParens;
9192
9193 auto *SubExpr = Cast->getSubExpr();
9194 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9195 return NoParens;
9196 return ignorePointerCastsAndParens(SubExpr);
9197}
9198
George Burgess IVa51c4072015-10-16 01:49:01 +00009199/// Checks to see if the given LValue's Designator is at the end of the LValue's
9200/// record layout. e.g.
9201/// struct { struct { int a, b; } fst, snd; } obj;
9202/// obj.fst // no
9203/// obj.snd // yes
9204/// obj.fst.a // no
9205/// obj.fst.b // no
9206/// obj.snd.a // no
9207/// obj.snd.b // yes
9208///
9209/// Please note: this function is specialized for how __builtin_object_size
9210/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009211///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009212/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9213/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009214static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9215 assert(!LVal.Designator.Invalid);
9216
George Burgess IV4168d752016-06-27 19:40:41 +00009217 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9218 const RecordDecl *Parent = FD->getParent();
9219 Invalid = Parent->isInvalidDecl();
9220 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009221 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009222 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009223 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9224 };
9225
9226 auto &Base = LVal.getLValueBase();
9227 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9228 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009229 bool Invalid;
9230 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9231 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009232 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009233 for (auto *FD : IFD->chain()) {
9234 bool Invalid;
9235 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9236 return Invalid;
9237 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009238 }
9239 }
9240
George Burgess IVe3763372016-12-22 02:50:20 +00009241 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009242 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009243 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009244 // If we don't know the array bound, conservatively assume we're looking at
9245 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009246 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009247 if (BaseType->isIncompleteArrayType())
9248 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9249 else
9250 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009251 }
9252
9253 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9254 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009255 if (BaseType->isArrayType()) {
9256 // Because __builtin_object_size treats arrays as objects, we can ignore
9257 // the index iff this is the last array in the Designator.
9258 if (I + 1 == E)
9259 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009260 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009261 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009262 if (Index + 1 != CAT->getSize())
9263 return false;
9264 BaseType = CAT->getElementType();
9265 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009266 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009267 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009268 if (Index != 1)
9269 return false;
9270 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009271 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009272 bool Invalid;
9273 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9274 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009275 BaseType = FD->getType();
9276 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009277 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009278 return false;
9279 }
9280 }
9281 return true;
9282}
9283
George Burgess IVe3763372016-12-22 02:50:20 +00009284/// Tests to see if the LValue has a user-specified designator (that isn't
9285/// necessarily valid). Note that this always returns 'true' if the LValue has
9286/// an unsized array as its first designator entry, because there's currently no
9287/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009288static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009289 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009290 return false;
9291
George Burgess IVe3763372016-12-22 02:50:20 +00009292 if (!LVal.Designator.Entries.empty())
9293 return LVal.Designator.isMostDerivedAnUnsizedArray();
9294
George Burgess IVa51c4072015-10-16 01:49:01 +00009295 if (!LVal.InvalidBase)
9296 return true;
9297
George Burgess IVe3763372016-12-22 02:50:20 +00009298 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9299 // the LValueBase.
9300 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9301 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009302}
9303
George Burgess IVe3763372016-12-22 02:50:20 +00009304/// Attempts to detect a user writing into a piece of memory that's impossible
9305/// to figure out the size of by just using types.
9306static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9307 const SubobjectDesignator &Designator = LVal.Designator;
9308 // Notes:
9309 // - Users can only write off of the end when we have an invalid base. Invalid
9310 // bases imply we don't know where the memory came from.
9311 // - We used to be a bit more aggressive here; we'd only be conservative if
9312 // the array at the end was flexible, or if it had 0 or 1 elements. This
9313 // broke some common standard library extensions (PR30346), but was
9314 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9315 // with some sort of whitelist. OTOH, it seems that GCC is always
9316 // conservative with the last element in structs (if it's an array), so our
9317 // current behavior is more compatible than a whitelisting approach would
9318 // be.
9319 return LVal.InvalidBase &&
9320 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9321 Designator.MostDerivedIsArrayElement &&
9322 isDesignatorAtObjectEnd(Ctx, LVal);
9323}
9324
9325/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9326/// Fails if the conversion would cause loss of precision.
9327static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9328 CharUnits &Result) {
9329 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9330 if (Int.ugt(CharUnitsMax))
9331 return false;
9332 Result = CharUnits::fromQuantity(Int.getZExtValue());
9333 return true;
9334}
9335
9336/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9337/// determine how many bytes exist from the beginning of the object to either
9338/// the end of the current subobject, or the end of the object itself, depending
9339/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009340///
George Burgess IVe3763372016-12-22 02:50:20 +00009341/// If this returns false, the value of Result is undefined.
9342static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9343 unsigned Type, const LValue &LVal,
9344 CharUnits &EndOffset) {
9345 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009346
George Burgess IV7fb7e362017-01-03 23:35:19 +00009347 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9348 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9349 return false;
9350 return HandleSizeof(Info, ExprLoc, Ty, Result);
9351 };
9352
George Burgess IVe3763372016-12-22 02:50:20 +00009353 // We want to evaluate the size of the entire object. This is a valid fallback
9354 // for when Type=1 and the designator is invalid, because we're asked for an
9355 // upper-bound.
9356 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9357 // Type=3 wants a lower bound, so we can't fall back to this.
9358 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00009359 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00009360
9361 llvm::APInt APEndOffset;
9362 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9363 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9364 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9365
9366 if (LVal.InvalidBase)
9367 return false;
9368
9369 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00009370 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00009371 }
9372
George Burgess IVe3763372016-12-22 02:50:20 +00009373 // We want to evaluate the size of a subobject.
9374 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009375
9376 // The following is a moderately common idiom in C:
9377 //
9378 // struct Foo { int a; char c[1]; };
9379 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9380 // strcpy(&F->c[0], Bar);
9381 //
George Burgess IVe3763372016-12-22 02:50:20 +00009382 // In order to not break too much legacy code, we need to support it.
9383 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9384 // If we can resolve this to an alloc_size call, we can hand that back,
9385 // because we know for certain how many bytes there are to write to.
9386 llvm::APInt APEndOffset;
9387 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9388 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9389 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9390
9391 // If we cannot determine the size of the initial allocation, then we can't
9392 // given an accurate upper-bound. However, we are still able to give
9393 // conservative lower-bounds for Type=3.
9394 if (Type == 1)
9395 return false;
9396 }
9397
9398 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00009399 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009400 return false;
9401
George Burgess IVe3763372016-12-22 02:50:20 +00009402 // According to the GCC documentation, we want the size of the subobject
9403 // denoted by the pointer. But that's not quite right -- what we actually
9404 // want is the size of the immediately-enclosing array, if there is one.
9405 int64_t ElemsRemaining;
9406 if (Designator.MostDerivedIsArrayElement &&
9407 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9408 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009409 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00009410 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9411 } else {
9412 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9413 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009414
George Burgess IVe3763372016-12-22 02:50:20 +00009415 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9416 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009417}
9418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009419/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00009420/// returns true and stores the result in @p Size.
9421///
9422/// If @p WasError is non-null, this will report whether the failure to evaluate
9423/// is to be treated as an Error in IntExprEvaluator.
9424static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9425 EvalInfo &Info, uint64_t &Size) {
9426 // Determine the denoted object.
9427 LValue LVal;
9428 {
9429 // The operand of __builtin_object_size is never evaluated for side-effects.
9430 // If there are any, but we can determine the pointed-to object anyway, then
9431 // ignore the side-effects.
9432 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00009433 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00009434
9435 if (E->isGLValue()) {
9436 // It's possible for us to be given GLValues if we're called via
9437 // Expr::tryEvaluateObjectSize.
9438 APValue RVal;
9439 if (!EvaluateAsRValue(Info, E, RVal))
9440 return false;
9441 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00009442 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9443 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00009444 return false;
9445 }
9446
9447 // If we point to before the start of the object, there are no accessible
9448 // bytes.
9449 if (LVal.getLValueOffset().isNegative()) {
9450 Size = 0;
9451 return true;
9452 }
9453
9454 CharUnits EndOffset;
9455 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9456 return false;
9457
9458 // If we've fallen outside of the end offset, just pretend there's nothing to
9459 // write to/read from.
9460 if (EndOffset <= LVal.getLValueOffset())
9461 Size = 0;
9462 else
9463 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9464 return true;
John McCall95007602010-05-10 23:27:23 +00009465}
9466
Fangrui Song407659a2018-11-30 23:41:18 +00009467bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9468 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00009469 if (E->getResultAPValueKind() != APValue::None)
9470 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00009471 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9472}
9473
Peter Collingbournee9200682011-05-13 03:29:01 +00009474bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00009475 if (unsigned BuiltinOp = E->getBuiltinCallee())
9476 return VisitBuiltinCallExpr(E, BuiltinOp);
9477
9478 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9479}
9480
9481bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9482 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00009483 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009484 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00009485 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00009486
Erik Pilkington9c3b5882019-01-30 20:34:53 +00009487 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00009488 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00009489 // The type was checked when we built the expression.
9490 unsigned Type =
9491 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9492 assert(Type <= 3 && "unexpected type");
9493
George Burgess IVe3763372016-12-22 02:50:20 +00009494 uint64_t Size;
9495 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9496 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00009497
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009498 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00009499 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00009500
Richard Smith01ade172012-05-23 04:13:20 +00009501 // Expression had no side effects, but we couldn't statically determine the
9502 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009503 switch (Info.EvalMode) {
9504 case EvalInfo::EM_ConstantExpression:
9505 case EvalInfo::EM_PotentialConstantExpression:
9506 case EvalInfo::EM_ConstantFold:
9507 case EvalInfo::EM_EvaluateForOverflow:
9508 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009509 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009510 return Error(E);
9511 case EvalInfo::EM_ConstantExpressionUnevaluated:
9512 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009513 // Reduce it to a constant now.
9514 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009515 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009516
9517 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009518 }
9519
Tim Northover314fbfa2018-11-02 13:14:11 +00009520 case Builtin::BI__builtin_os_log_format_buffer_size: {
9521 analyze_os_log::OSLogBufferLayout Layout;
9522 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9523 return Success(Layout.size().getQuantity(), E);
9524 }
9525
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009526 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009527 case Builtin::BI__builtin_bswap32:
9528 case Builtin::BI__builtin_bswap64: {
9529 APSInt Val;
9530 if (!EvaluateInteger(E->getArg(0), Val, Info))
9531 return false;
9532
9533 return Success(Val.byteSwap(), E);
9534 }
9535
Richard Smith8889a3d2013-06-13 06:26:32 +00009536 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009537 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009538
Craig Topperf95a6d92018-08-08 22:31:12 +00009539 case Builtin::BI__builtin_clrsb:
9540 case Builtin::BI__builtin_clrsbl:
9541 case Builtin::BI__builtin_clrsbll: {
9542 APSInt Val;
9543 if (!EvaluateInteger(E->getArg(0), Val, Info))
9544 return false;
9545
9546 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9547 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009548
Richard Smith80b3c8e2013-06-13 05:04:16 +00009549 case Builtin::BI__builtin_clz:
9550 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009551 case Builtin::BI__builtin_clzll:
9552 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009553 APSInt Val;
9554 if (!EvaluateInteger(E->getArg(0), Val, Info))
9555 return false;
9556 if (!Val)
9557 return Error(E);
9558
9559 return Success(Val.countLeadingZeros(), E);
9560 }
9561
Fangrui Song407659a2018-11-30 23:41:18 +00009562 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009563 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009564 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009565 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009566 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009567 // Outside a constant context, eagerly evaluate to false in the presence
9568 // of side-effects in order to avoid -Wunsequenced false-positives in
9569 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009570 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009571 }
David Blaikie639b3d12019-05-03 18:11:31 +00009572 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9573 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009574 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009575
Eric Fiselieradd16a82019-04-24 02:23:30 +00009576 case Builtin::BI__builtin_is_constant_evaluated:
9577 return Success(Info.InConstantContext, E);
9578
Richard Smith80b3c8e2013-06-13 05:04:16 +00009579 case Builtin::BI__builtin_ctz:
9580 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009581 case Builtin::BI__builtin_ctzll:
9582 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009583 APSInt Val;
9584 if (!EvaluateInteger(E->getArg(0), Val, Info))
9585 return false;
9586 if (!Val)
9587 return Error(E);
9588
9589 return Success(Val.countTrailingZeros(), E);
9590 }
9591
Richard Smith8889a3d2013-06-13 06:26:32 +00009592 case Builtin::BI__builtin_eh_return_data_regno: {
9593 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9594 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9595 return Success(Operand, E);
9596 }
9597
9598 case Builtin::BI__builtin_expect:
9599 return Visit(E->getArg(0));
9600
9601 case Builtin::BI__builtin_ffs:
9602 case Builtin::BI__builtin_ffsl:
9603 case Builtin::BI__builtin_ffsll: {
9604 APSInt Val;
9605 if (!EvaluateInteger(E->getArg(0), Val, Info))
9606 return false;
9607
9608 unsigned N = Val.countTrailingZeros();
9609 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9610 }
9611
9612 case Builtin::BI__builtin_fpclassify: {
9613 APFloat Val(0.0);
9614 if (!EvaluateFloat(E->getArg(5), Val, Info))
9615 return false;
9616 unsigned Arg;
9617 switch (Val.getCategory()) {
9618 case APFloat::fcNaN: Arg = 0; break;
9619 case APFloat::fcInfinity: Arg = 1; break;
9620 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9621 case APFloat::fcZero: Arg = 4; break;
9622 }
9623 return Visit(E->getArg(Arg));
9624 }
9625
9626 case Builtin::BI__builtin_isinf_sign: {
9627 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009628 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009629 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9630 }
9631
Richard Smithea3019d2013-10-15 19:07:14 +00009632 case Builtin::BI__builtin_isinf: {
9633 APFloat Val(0.0);
9634 return EvaluateFloat(E->getArg(0), Val, Info) &&
9635 Success(Val.isInfinity() ? 1 : 0, E);
9636 }
9637
9638 case Builtin::BI__builtin_isfinite: {
9639 APFloat Val(0.0);
9640 return EvaluateFloat(E->getArg(0), Val, Info) &&
9641 Success(Val.isFinite() ? 1 : 0, E);
9642 }
9643
9644 case Builtin::BI__builtin_isnan: {
9645 APFloat Val(0.0);
9646 return EvaluateFloat(E->getArg(0), Val, Info) &&
9647 Success(Val.isNaN() ? 1 : 0, E);
9648 }
9649
9650 case Builtin::BI__builtin_isnormal: {
9651 APFloat Val(0.0);
9652 return EvaluateFloat(E->getArg(0), Val, Info) &&
9653 Success(Val.isNormal() ? 1 : 0, E);
9654 }
9655
Richard Smith8889a3d2013-06-13 06:26:32 +00009656 case Builtin::BI__builtin_parity:
9657 case Builtin::BI__builtin_parityl:
9658 case Builtin::BI__builtin_parityll: {
9659 APSInt Val;
9660 if (!EvaluateInteger(E->getArg(0), Val, Info))
9661 return false;
9662
9663 return Success(Val.countPopulation() % 2, E);
9664 }
9665
Richard Smith80b3c8e2013-06-13 05:04:16 +00009666 case Builtin::BI__builtin_popcount:
9667 case Builtin::BI__builtin_popcountl:
9668 case Builtin::BI__builtin_popcountll: {
9669 APSInt Val;
9670 if (!EvaluateInteger(E->getArg(0), Val, Info))
9671 return false;
9672
9673 return Success(Val.countPopulation(), E);
9674 }
9675
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009676 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009677 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009678 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009679 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009680 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009681 << /*isConstexpr*/0 << /*isConstructor*/0
9682 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009683 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009684 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009685 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009686 case Builtin::BI__builtin_strlen:
9687 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009688 // As an extension, we support __builtin_strlen() as a constant expression,
9689 // and support folding strlen() to a constant.
9690 LValue String;
9691 if (!EvaluatePointer(E->getArg(0), String, Info))
9692 return false;
9693
Richard Smith8110c9d2016-11-29 19:45:17 +00009694 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9695
Richard Smithe6c19f22013-11-15 02:10:04 +00009696 // Fast path: if it's a string literal, search the string value.
9697 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9698 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009699 // The string literal may have embedded null characters. Find the first
9700 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009701 StringRef Str = S->getBytes();
9702 int64_t Off = String.Offset.getQuantity();
9703 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009704 S->getCharByteWidth() == 1 &&
9705 // FIXME: Add fast-path for wchar_t too.
9706 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009707 Str = Str.substr(Off);
9708
9709 StringRef::size_type Pos = Str.find(0);
9710 if (Pos != StringRef::npos)
9711 Str = Str.substr(0, Pos);
9712
9713 return Success(Str.size(), E);
9714 }
9715
9716 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009717 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009718
9719 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009720 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9721 APValue Char;
9722 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9723 !Char.isInt())
9724 return false;
9725 if (!Char.getInt())
9726 return Success(Strlen, E);
9727 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9728 return false;
9729 }
9730 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009731
Richard Smithe151bab2016-11-11 23:43:35 +00009732 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009733 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009734 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009735 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009736 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009737 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009738 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009739 // A call to strlen is not a constant expression.
9740 if (Info.getLangOpts().CPlusPlus11)
9741 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9742 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009743 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009744 else
9745 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009746 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009747 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009748 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009749 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009750 case Builtin::BI__builtin_wcsncmp:
9751 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009752 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009753 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009754 LValue String1, String2;
9755 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9756 !EvaluatePointer(E->getArg(1), String2, Info))
9757 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009758
Richard Smithe151bab2016-11-11 23:43:35 +00009759 uint64_t MaxLength = uint64_t(-1);
9760 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009761 BuiltinOp != Builtin::BIwcscmp &&
9762 BuiltinOp != Builtin::BI__builtin_strcmp &&
9763 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009764 APSInt N;
9765 if (!EvaluateInteger(E->getArg(2), N, Info))
9766 return false;
9767 MaxLength = N.getExtValue();
9768 }
Hubert Tong147b7432018-12-12 16:53:43 +00009769
9770 // Empty substrings compare equal by definition.
9771 if (MaxLength == 0u)
9772 return Success(0, E);
9773
9774 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9775 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9776 String1.Designator.Invalid || String2.Designator.Invalid)
9777 return false;
9778
9779 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9780 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9781
9782 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009783 BuiltinOp == Builtin::BIbcmp ||
9784 BuiltinOp == Builtin::BI__builtin_memcmp ||
9785 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009786
9787 assert(IsRawByte ||
9788 (Info.Ctx.hasSameUnqualifiedType(
9789 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9790 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9791
9792 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9793 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9794 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9795 Char1.isInt() && Char2.isInt();
9796 };
9797 const auto &AdvanceElems = [&] {
9798 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9799 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9800 };
9801
9802 if (IsRawByte) {
9803 uint64_t BytesRemaining = MaxLength;
9804 // Pointers to const void may point to objects of incomplete type.
9805 if (CharTy1->isIncompleteType()) {
9806 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9807 return false;
9808 }
9809 if (CharTy2->isIncompleteType()) {
9810 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9811 return false;
9812 }
9813 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9814 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9815 // Give up on comparing between elements with disparate widths.
9816 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9817 return false;
9818 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9819 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9820 "following loop considers at least one element");
9821 while (true) {
9822 APValue Char1, Char2;
9823 if (!ReadCurElems(Char1, Char2))
9824 return false;
9825 // We have compatible in-memory widths, but a possible type and
9826 // (for `bool`) internal representation mismatch.
9827 // Assuming two's complement representation, including 0 for `false` and
9828 // 1 for `true`, we can check an appropriate number of elements for
9829 // equality even if they are not byte-sized.
9830 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9831 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9832 if (Char1InMem.ne(Char2InMem)) {
9833 // If the elements are byte-sized, then we can produce a three-way
9834 // comparison result in a straightforward manner.
9835 if (BytesPerElement == 1u) {
9836 // memcmp always compares unsigned chars.
9837 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9838 }
9839 // The result is byte-order sensitive, and we have multibyte elements.
9840 // FIXME: We can compare the remaining bytes in the correct order.
9841 return false;
9842 }
9843 if (!AdvanceElems())
9844 return false;
9845 if (BytesRemaining <= BytesPerElement)
9846 break;
9847 BytesRemaining -= BytesPerElement;
9848 }
9849 // Enough elements are equal to account for the memcmp limit.
9850 return Success(0, E);
9851 }
9852
Clement Courbet8c3343d2019-02-14 12:00:34 +00009853 bool StopAtNull =
9854 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9855 BuiltinOp != Builtin::BIwmemcmp &&
9856 BuiltinOp != Builtin::BI__builtin_memcmp &&
9857 BuiltinOp != Builtin::BI__builtin_bcmp &&
9858 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009859 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9860 BuiltinOp == Builtin::BIwcsncmp ||
9861 BuiltinOp == Builtin::BIwmemcmp ||
9862 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9863 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9864 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009865
Richard Smithe151bab2016-11-11 23:43:35 +00009866 for (; MaxLength; --MaxLength) {
9867 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009868 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009869 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009870 if (Char1.getInt() != Char2.getInt()) {
9871 if (IsWide) // wmemcmp compares with wchar_t signedness.
9872 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9873 // memcmp always compares unsigned chars.
9874 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9875 }
Richard Smithe151bab2016-11-11 23:43:35 +00009876 if (StopAtNull && !Char1.getInt())
9877 return Success(0, E);
9878 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009879 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009880 return false;
9881 }
9882 // We hit the strncmp / memcmp limit.
9883 return Success(0, E);
9884 }
9885
Richard Smith01ba47d2012-04-13 00:45:38 +00009886 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009887 case Builtin::BI__atomic_is_lock_free:
9888 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009889 APSInt SizeVal;
9890 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9891 return false;
9892
9893 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9894 // of two less than the maximum inline atomic width, we know it is
9895 // lock-free. If the size isn't a power of two, or greater than the
9896 // maximum alignment where we promote atomics, we know it is not lock-free
9897 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9898 // the answer can only be determined at runtime; for example, 16-byte
9899 // atomics have lock-free implementations on some, but not all,
9900 // x86-64 processors.
9901
9902 // Check power-of-two.
9903 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009904 if (Size.isPowerOfTwo()) {
9905 // Check against inlining width.
9906 unsigned InlineWidthBits =
9907 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9908 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9909 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9910 Size == CharUnits::One() ||
9911 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9912 Expr::NPC_NeverValueDependent))
9913 // OK, we will inline appropriately-aligned operations of this size,
9914 // and _Atomic(T) is appropriately-aligned.
9915 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009916
Richard Smith01ba47d2012-04-13 00:45:38 +00009917 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9918 castAs<PointerType>()->getPointeeType();
9919 if (!PointeeType->isIncompleteType() &&
9920 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9921 // OK, we will inline operations on this object.
9922 return Success(1, E);
9923 }
9924 }
9925 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009926
Richard Smith01ba47d2012-04-13 00:45:38 +00009927 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9928 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009929 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009930 case Builtin::BIomp_is_initial_device:
9931 // We can decide statically which value the runtime would return if called.
9932 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009933 case Builtin::BI__builtin_add_overflow:
9934 case Builtin::BI__builtin_sub_overflow:
9935 case Builtin::BI__builtin_mul_overflow:
9936 case Builtin::BI__builtin_sadd_overflow:
9937 case Builtin::BI__builtin_uadd_overflow:
9938 case Builtin::BI__builtin_uaddl_overflow:
9939 case Builtin::BI__builtin_uaddll_overflow:
9940 case Builtin::BI__builtin_usub_overflow:
9941 case Builtin::BI__builtin_usubl_overflow:
9942 case Builtin::BI__builtin_usubll_overflow:
9943 case Builtin::BI__builtin_umul_overflow:
9944 case Builtin::BI__builtin_umull_overflow:
9945 case Builtin::BI__builtin_umulll_overflow:
9946 case Builtin::BI__builtin_saddl_overflow:
9947 case Builtin::BI__builtin_saddll_overflow:
9948 case Builtin::BI__builtin_ssub_overflow:
9949 case Builtin::BI__builtin_ssubl_overflow:
9950 case Builtin::BI__builtin_ssubll_overflow:
9951 case Builtin::BI__builtin_smul_overflow:
9952 case Builtin::BI__builtin_smull_overflow:
9953 case Builtin::BI__builtin_smulll_overflow: {
9954 LValue ResultLValue;
9955 APSInt LHS, RHS;
9956
9957 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9958 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9959 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9960 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9961 return false;
9962
9963 APSInt Result;
9964 bool DidOverflow = false;
9965
9966 // If the types don't have to match, enlarge all 3 to the largest of them.
9967 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9968 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9969 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9970 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9971 ResultType->isSignedIntegerOrEnumerationType();
9972 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9973 ResultType->isSignedIntegerOrEnumerationType();
9974 uint64_t LHSSize = LHS.getBitWidth();
9975 uint64_t RHSSize = RHS.getBitWidth();
9976 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9977 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9978
9979 // Add an additional bit if the signedness isn't uniformly agreed to. We
9980 // could do this ONLY if there is a signed and an unsigned that both have
9981 // MaxBits, but the code to check that is pretty nasty. The issue will be
9982 // caught in the shrink-to-result later anyway.
9983 if (IsSigned && !AllSigned)
9984 ++MaxBits;
9985
Erich Keanefc3dfd32019-05-30 21:35:32 +00009986 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9987 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009988 Result = APSInt(MaxBits, !IsSigned);
9989 }
9990
9991 // Find largest int.
9992 switch (BuiltinOp) {
9993 default:
9994 llvm_unreachable("Invalid value for BuiltinOp");
9995 case Builtin::BI__builtin_add_overflow:
9996 case Builtin::BI__builtin_sadd_overflow:
9997 case Builtin::BI__builtin_saddl_overflow:
9998 case Builtin::BI__builtin_saddll_overflow:
9999 case Builtin::BI__builtin_uadd_overflow:
10000 case Builtin::BI__builtin_uaddl_overflow:
10001 case Builtin::BI__builtin_uaddll_overflow:
10002 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10003 : LHS.uadd_ov(RHS, DidOverflow);
10004 break;
10005 case Builtin::BI__builtin_sub_overflow:
10006 case Builtin::BI__builtin_ssub_overflow:
10007 case Builtin::BI__builtin_ssubl_overflow:
10008 case Builtin::BI__builtin_ssubll_overflow:
10009 case Builtin::BI__builtin_usub_overflow:
10010 case Builtin::BI__builtin_usubl_overflow:
10011 case Builtin::BI__builtin_usubll_overflow:
10012 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10013 : LHS.usub_ov(RHS, DidOverflow);
10014 break;
10015 case Builtin::BI__builtin_mul_overflow:
10016 case Builtin::BI__builtin_smul_overflow:
10017 case Builtin::BI__builtin_smull_overflow:
10018 case Builtin::BI__builtin_smulll_overflow:
10019 case Builtin::BI__builtin_umul_overflow:
10020 case Builtin::BI__builtin_umull_overflow:
10021 case Builtin::BI__builtin_umulll_overflow:
10022 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10023 : LHS.umul_ov(RHS, DidOverflow);
10024 break;
10025 }
10026
10027 // In the case where multiple sizes are allowed, truncate and see if
10028 // the values are the same.
10029 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10030 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10031 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10032 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10033 // since it will give us the behavior of a TruncOrSelf in the case where
10034 // its parameter <= its size. We previously set Result to be at least the
10035 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10036 // will work exactly like TruncOrSelf.
10037 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10038 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10039
10040 if (!APSInt::isSameValue(Temp, Result))
10041 DidOverflow = true;
10042 Result = Temp;
10043 }
10044
10045 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000010046 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10047 return false;
Erich Keane00958272018-06-13 20:43:27 +000010048 return Success(DidOverflow, E);
10049 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010050 }
Chris Lattner7174bf32008-07-12 00:38:25 +000010051}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000010052
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010053/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000010054/// object referred to by the lvalue.
10055static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10056 const LValue &LV) {
10057 // A null pointer can be viewed as being "past the end" but we don't
10058 // choose to look at it that way here.
10059 if (!LV.getLValueBase())
10060 return false;
10061
10062 // If the designator is valid and refers to a subobject, we're not pointing
10063 // past the end.
10064 if (!LV.getLValueDesignator().Invalid &&
10065 !LV.getLValueDesignator().isOnePastTheEnd())
10066 return false;
10067
David Majnemerc378ca52015-08-29 08:32:55 +000010068 // A pointer to an incomplete type might be past-the-end if the type's size is
10069 // zero. We cannot tell because the type is incomplete.
10070 QualType Ty = getType(LV.getLValueBase());
10071 if (Ty->isIncompleteType())
10072 return true;
10073
Richard Smithd20f1e62014-10-21 23:01:04 +000010074 // We're a past-the-end pointer if we point to the byte after the object,
10075 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000010076 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000010077 return LV.getLValueOffset() == Size;
10078}
10079
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010080namespace {
Richard Smith11562c52011-10-28 17:51:58 +000010081
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010082/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010083///
10084/// We use a data recursive algorithm for binary operators so that we are able
10085/// to handle extreme cases of chained binary operators without causing stack
10086/// overflow.
10087class DataRecursiveIntBinOpEvaluator {
10088 struct EvalResult {
10089 APValue Val;
10090 bool Failed;
10091
10092 EvalResult() : Failed(false) { }
10093
10094 void swap(EvalResult &RHS) {
10095 Val.swap(RHS.Val);
10096 Failed = RHS.Failed;
10097 RHS.Failed = false;
10098 }
10099 };
10100
10101 struct Job {
10102 const Expr *E;
10103 EvalResult LHSResult; // meaningful only for binary operator expression.
10104 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010105
David Blaikie73726062015-08-12 23:09:24 +000010106 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010107 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010109 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010110 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010111 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010113 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010114 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010115 };
10116
10117 SmallVector<Job, 16> Queue;
10118
10119 IntExprEvaluator &IntEval;
10120 EvalInfo &Info;
10121 APValue &FinalResult;
10122
10123public:
10124 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10125 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010127 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010128 /// data recursively.
10129 /// We handle binary operators that are comma, logical, or that have operands
10130 /// with integral or enumeration type.
10131 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010132 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10133 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010134 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010135 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010136 }
10137
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010138 bool Traverse(const BinaryOperator *E) {
10139 enqueue(E);
10140 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010141 while (!Queue.empty())
10142 process(PrevResult);
10143
10144 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010145
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010146 FinalResult.swap(PrevResult.Val);
10147 return true;
10148 }
10149
10150private:
10151 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10152 return IntEval.Success(Value, E, Result);
10153 }
10154 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10155 return IntEval.Success(Value, E, Result);
10156 }
10157 bool Error(const Expr *E) {
10158 return IntEval.Error(E);
10159 }
10160 bool Error(const Expr *E, diag::kind D) {
10161 return IntEval.Error(E, D);
10162 }
10163
10164 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10165 return Info.CCEDiag(E, D);
10166 }
10167
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010168 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010169 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010170 bool &SuppressRHSDiags);
10171
10172 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10173 const BinaryOperator *E, APValue &Result);
10174
10175 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10176 Result.Failed = !Evaluate(Result.Val, Info, E);
10177 if (Result.Failed)
10178 Result.Val = APValue();
10179 }
10180
Richard Trieuba4d0872012-03-21 23:30:30 +000010181 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010182
10183 void enqueue(const Expr *E) {
10184 E = E->IgnoreParens();
10185 Queue.resize(Queue.size()+1);
10186 Queue.back().E = E;
10187 Queue.back().Kind = Job::AnyExprKind;
10188 }
10189};
10190
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010191}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010192
10193bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010194 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010195 bool &SuppressRHSDiags) {
10196 if (E->getOpcode() == BO_Comma) {
10197 // Ignore LHS but note if we could not evaluate it.
10198 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010199 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010200 return true;
10201 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010202
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010203 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010204 bool LHSAsBool;
10205 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010206 // We were able to evaluate the LHS, see if we can get away with not
10207 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010208 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10209 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010210 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010211 }
10212 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010213 LHSResult.Failed = true;
10214
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010215 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010216 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010217 if (!Info.noteSideEffect())
10218 return false;
10219
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010220 // We can't evaluate the LHS; however, sometimes the result
10221 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10222 // Don't ignore RHS and suppress diagnostics from this arm.
10223 SuppressRHSDiags = true;
10224 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010225
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010226 return true;
10227 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010228
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010229 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10230 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010231
George Burgess IVa145e252016-05-25 22:38:36 +000010232 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010233 return false; // Ignore RHS;
10234
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010235 return true;
10236}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010237
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010238static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10239 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010240 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10241 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10242 // offsets.
10243 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10244 CharUnits &Offset = LVal.getLValueOffset();
10245 uint64_t Offset64 = Offset.getQuantity();
10246 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10247 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10248 : Offset64 + Index64);
10249}
10250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010251bool DataRecursiveIntBinOpEvaluator::
10252 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10253 const BinaryOperator *E, APValue &Result) {
10254 if (E->getOpcode() == BO_Comma) {
10255 if (RHSResult.Failed)
10256 return false;
10257 Result = RHSResult.Val;
10258 return true;
10259 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010260
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010261 if (E->isLogicalOp()) {
10262 bool lhsResult, rhsResult;
10263 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10264 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010265
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010266 if (LHSIsOK) {
10267 if (RHSIsOK) {
10268 if (E->getOpcode() == BO_LOr)
10269 return Success(lhsResult || rhsResult, E, Result);
10270 else
10271 return Success(lhsResult && rhsResult, E, Result);
10272 }
10273 } else {
10274 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010275 // We can't evaluate the LHS; however, sometimes the result
10276 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10277 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010278 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010279 }
10280 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010281
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010282 return false;
10283 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010285 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10286 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010287
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010288 if (LHSResult.Failed || RHSResult.Failed)
10289 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010290
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010291 const APValue &LHSVal = LHSResult.Val;
10292 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010293
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010294 // Handle cases like (unsigned long)&a + 4.
10295 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10296 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010297 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010298 return true;
10299 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010300
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010301 // Handle cases like 4 + (unsigned long)&a
10302 if (E->getOpcode() == BO_Add &&
10303 RHSVal.isLValue() && LHSVal.isInt()) {
10304 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010305 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010306 return true;
10307 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010308
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010309 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10310 // Handle (intptr_t)&&A - (intptr_t)&&B.
10311 if (!LHSVal.getLValueOffset().isZero() ||
10312 !RHSVal.getLValueOffset().isZero())
10313 return false;
10314 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10315 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10316 if (!LHSExpr || !RHSExpr)
10317 return false;
10318 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10319 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10320 if (!LHSAddrExpr || !RHSAddrExpr)
10321 return false;
10322 // Make sure both labels come from the same function.
10323 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10324 RHSAddrExpr->getLabel()->getDeclContext())
10325 return false;
10326 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10327 return true;
10328 }
Richard Smith43e77732013-05-07 04:50:00 +000010329
10330 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010331 if (!LHSVal.isInt() || !RHSVal.isInt())
10332 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010333
10334 // Set up the width and signedness manually, in case it can't be deduced
10335 // from the operation we're performing.
10336 // FIXME: Don't do this in the cases where we can deduce it.
10337 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10338 E->getType()->isUnsignedIntegerOrEnumerationType());
10339 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10340 RHSVal.getInt(), Value))
10341 return false;
10342 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010343}
10344
Richard Trieuba4d0872012-03-21 23:30:30 +000010345void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010346 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000010347
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010348 switch (job.Kind) {
10349 case Job::AnyExprKind: {
10350 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10351 if (shouldEnqueue(Bop)) {
10352 job.Kind = Job::BinOpKind;
10353 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010354 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010355 }
10356 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010357
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010358 EvaluateExpr(job.E, Result);
10359 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010360 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010361 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010362
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010363 case Job::BinOpKind: {
10364 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010365 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010366 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010367 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010368 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010369 }
10370 if (SuppressRHSDiags)
10371 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010372 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010373 job.Kind = Job::BinOpVisitedLHSKind;
10374 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010375 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010376 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010378 case Job::BinOpVisitedLHSKind: {
10379 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10380 EvalResult RHS;
10381 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000010382 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010383 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010384 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010385 }
10386 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010387
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010388 llvm_unreachable("Invalid Job::Kind!");
10389}
10390
George Burgess IV8c892b52016-05-25 22:31:54 +000010391namespace {
10392/// Used when we determine that we should fail, but can keep evaluating prior to
10393/// noting that we had a failure.
10394class DelayedNoteFailureRAII {
10395 EvalInfo &Info;
10396 bool NoteFailure;
10397
10398public:
10399 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10400 : Info(Info), NoteFailure(NoteFailure) {}
10401 ~DelayedNoteFailureRAII() {
10402 if (NoteFailure) {
10403 bool ContinueAfterFailure = Info.noteFailure();
10404 (void)ContinueAfterFailure;
10405 assert(ContinueAfterFailure &&
10406 "Shouldn't have kept evaluating on failure.");
10407 }
10408 }
10409};
10410}
10411
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010412template <class SuccessCB, class AfterCB>
10413static bool
10414EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10415 SuccessCB &&Success, AfterCB &&DoAfter) {
10416 assert(E->isComparisonOp() && "expected comparison operator");
10417 assert((E->getOpcode() == BO_Cmp ||
10418 E->getType()->isIntegralOrEnumerationType()) &&
10419 "unsupported binary expression evaluation");
10420 auto Error = [&](const Expr *E) {
10421 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10422 return false;
10423 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010424
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010425 using CCR = ComparisonCategoryResult;
10426 bool IsRelational = E->isRelationalOp();
10427 bool IsEquality = E->isEqualityOp();
10428 if (E->getOpcode() == BO_Cmp) {
10429 const ComparisonCategoryInfo &CmpInfo =
10430 Info.Ctx.CompCategories.getInfoForType(E->getType());
10431 IsRelational = CmpInfo.isOrdered();
10432 IsEquality = CmpInfo.isEquality();
10433 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000010434
Anders Carlssonacc79812008-11-16 07:17:21 +000010435 QualType LHSTy = E->getLHS()->getType();
10436 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010437
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010438 if (LHSTy->isIntegralOrEnumerationType() &&
10439 RHSTy->isIntegralOrEnumerationType()) {
10440 APSInt LHS, RHS;
10441 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10442 if (!LHSOK && !Info.noteFailure())
10443 return false;
10444 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10445 return false;
10446 if (LHS < RHS)
10447 return Success(CCR::Less, E);
10448 if (LHS > RHS)
10449 return Success(CCR::Greater, E);
10450 return Success(CCR::Equal, E);
10451 }
10452
Leonard Chance1d4f12019-02-21 20:50:09 +000010453 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10454 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10455 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10456
10457 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10458 if (!LHSOK && !Info.noteFailure())
10459 return false;
10460 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10461 return false;
10462 if (LHSFX < RHSFX)
10463 return Success(CCR::Less, E);
10464 if (LHSFX > RHSFX)
10465 return Success(CCR::Greater, E);
10466 return Success(CCR::Equal, E);
10467 }
10468
Chandler Carruthb29a7432014-10-11 11:03:30 +000010469 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010470 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000010471 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000010472 if (E->isAssignmentOp()) {
10473 LValue LV;
10474 EvaluateLValue(E->getLHS(), LV, Info);
10475 LHSOK = false;
10476 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000010477 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10478 if (LHSOK) {
10479 LHS.makeComplexFloat();
10480 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10481 }
10482 } else {
10483 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10484 }
George Burgess IVa145e252016-05-25 22:38:36 +000010485 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010486 return false;
10487
Chandler Carruthb29a7432014-10-11 11:03:30 +000010488 if (E->getRHS()->getType()->isRealFloatingType()) {
10489 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10490 return false;
10491 RHS.makeComplexFloat();
10492 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10493 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010494 return false;
10495
10496 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000010497 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010498 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000010499 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010500 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010501 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10502 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010503 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010504 assert(IsEquality && "invalid complex comparison");
10505 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10506 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10507 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010508 }
10509 }
Mike Stump11289f42009-09-09 15:08:12 +000010510
Anders Carlssonacc79812008-11-16 07:17:21 +000010511 if (LHSTy->isRealFloatingType() &&
10512 RHSTy->isRealFloatingType()) {
10513 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010514
Richard Smith253c2a32012-01-27 01:14:48 +000010515 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010516 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010517 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010518
Richard Smith253c2a32012-01-27 01:14:48 +000010519 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010520 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010521
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010522 assert(E->isComparisonOp() && "Invalid binary operator!");
10523 auto GetCmpRes = [&]() {
10524 switch (LHS.compare(RHS)) {
10525 case APFloat::cmpEqual:
10526 return CCR::Equal;
10527 case APFloat::cmpLessThan:
10528 return CCR::Less;
10529 case APFloat::cmpGreaterThan:
10530 return CCR::Greater;
10531 case APFloat::cmpUnordered:
10532 return CCR::Unordered;
10533 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010534 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010535 };
10536 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010537 }
Mike Stump11289f42009-09-09 15:08:12 +000010538
Eli Friedmana38da572009-04-28 19:17:36 +000010539 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010540 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010541
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010542 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10543 if (!LHSOK && !Info.noteFailure())
10544 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010545
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010546 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10547 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010548
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010549 // Reject differing bases from the normal codepath; we special-case
10550 // comparisons to null.
10551 if (!HasSameBase(LHSValue, RHSValue)) {
10552 // Inequalities and subtractions between unrelated pointers have
10553 // unspecified or undefined behavior.
10554 if (!IsEquality)
10555 return Error(E);
10556 // A constant address may compare equal to the address of a symbol.
10557 // The one exception is that address of an object cannot compare equal
10558 // to a null pointer constant.
10559 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10560 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10561 return Error(E);
10562 // It's implementation-defined whether distinct literals will have
10563 // distinct addresses. In clang, the result of such a comparison is
10564 // unspecified, so it is not a constant expression. However, we do know
10565 // that the address of a literal will be non-null.
10566 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10567 LHSValue.Base && RHSValue.Base)
10568 return Error(E);
10569 // We can't tell whether weak symbols will end up pointing to the same
10570 // object.
10571 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10572 return Error(E);
10573 // We can't compare the address of the start of one object with the
10574 // past-the-end address of another object, per C++ DR1652.
10575 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10576 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10577 (RHSValue.Base && RHSValue.Offset.isZero() &&
10578 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10579 return Error(E);
10580 // We can't tell whether an object is at the same address as another
10581 // zero sized object.
10582 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10583 (LHSValue.Base && isZeroSized(RHSValue)))
10584 return Error(E);
10585 return Success(CCR::Nonequal, E);
10586 }
Eli Friedman64004332009-03-23 04:38:34 +000010587
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010588 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10589 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010590
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010591 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10592 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010593
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010594 // C++11 [expr.rel]p3:
10595 // Pointers to void (after pointer conversions) can be compared, with a
10596 // result defined as follows: If both pointers represent the same
10597 // address or are both the null pointer value, the result is true if the
10598 // operator is <= or >= and false otherwise; otherwise the result is
10599 // unspecified.
10600 // We interpret this as applying to pointers to *cv* void.
10601 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10602 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010603
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010604 // C++11 [expr.rel]p2:
10605 // - If two pointers point to non-static data members of the same object,
10606 // or to subobjects or array elements fo such members, recursively, the
10607 // pointer to the later declared member compares greater provided the
10608 // two members have the same access control and provided their class is
10609 // not a union.
10610 // [...]
10611 // - Otherwise pointer comparisons are unspecified.
10612 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10613 bool WasArrayIndex;
10614 unsigned Mismatch = FindDesignatorMismatch(
10615 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10616 // At the point where the designators diverge, the comparison has a
10617 // specified value if:
10618 // - we are comparing array indices
10619 // - we are comparing fields of a union, or fields with the same access
10620 // Otherwise, the result is unspecified and thus the comparison is not a
10621 // constant expression.
10622 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10623 Mismatch < RHSDesignator.Entries.size()) {
10624 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10625 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10626 if (!LF && !RF)
10627 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10628 else if (!LF)
10629 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010630 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10631 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010632 else if (!RF)
10633 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010634 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10635 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010636 else if (!LF->getParent()->isUnion() &&
10637 LF->getAccess() != RF->getAccess())
10638 Info.CCEDiag(E,
10639 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010640 << LF << LF->getAccess() << RF << RF->getAccess()
10641 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010642 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010643 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010644
10645 // The comparison here must be unsigned, and performed with the same
10646 // width as the pointer.
10647 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10648 uint64_t CompareLHS = LHSOffset.getQuantity();
10649 uint64_t CompareRHS = RHSOffset.getQuantity();
10650 assert(PtrSize <= 64 && "Unexpected pointer width");
10651 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10652 CompareLHS &= Mask;
10653 CompareRHS &= Mask;
10654
10655 // If there is a base and this is a relational operator, we can only
10656 // compare pointers within the object in question; otherwise, the result
10657 // depends on where the object is located in memory.
10658 if (!LHSValue.Base.isNull() && IsRelational) {
10659 QualType BaseTy = getType(LHSValue.Base);
10660 if (BaseTy->isIncompleteType())
10661 return Error(E);
10662 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10663 uint64_t OffsetLimit = Size.getQuantity();
10664 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10665 return Error(E);
10666 }
10667
10668 if (CompareLHS < CompareRHS)
10669 return Success(CCR::Less, E);
10670 if (CompareLHS > CompareRHS)
10671 return Success(CCR::Greater, E);
10672 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010673 }
Richard Smith7bb00672012-02-01 01:42:44 +000010674
10675 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010676 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010677 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10678
10679 MemberPtr LHSValue, RHSValue;
10680
10681 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010682 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010683 return false;
10684
10685 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10686 return false;
10687
10688 // C++11 [expr.eq]p2:
10689 // If both operands are null, they compare equal. Otherwise if only one is
10690 // null, they compare unequal.
10691 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10692 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010693 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010694 }
10695
10696 // Otherwise if either is a pointer to a virtual member function, the
10697 // result is unspecified.
10698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10699 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010700 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010701 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10702 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010703 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010704
10705 // Otherwise they compare equal if and only if they would refer to the
10706 // same member of the same most derived object or the same subobject if
10707 // they were dereferenced with a hypothetical object of the associated
10708 // class type.
10709 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010710 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010711 }
10712
Richard Smithab44d9b2012-02-14 22:35:28 +000010713 if (LHSTy->isNullPtrType()) {
10714 assert(E->isComparisonOp() && "unexpected nullptr operation");
10715 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10716 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10717 // are compared, the result is true of the operator is <=, >= or ==, and
10718 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010719 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010720 }
10721
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010722 return DoAfter();
10723}
10724
10725bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10726 if (!CheckLiteralType(Info, E))
10727 return false;
10728
10729 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10730 const BinaryOperator *E) {
10731 // Evaluation succeeded. Lookup the information for the comparison category
10732 // type and fetch the VarDecl for the result.
10733 const ComparisonCategoryInfo &CmpInfo =
10734 Info.Ctx.CompCategories.getInfoForType(E->getType());
10735 const VarDecl *VD =
10736 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10737 // Check and evaluate the result as a constant expression.
10738 LValue LV;
10739 LV.set(VD);
10740 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10741 return false;
10742 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10743 };
10744 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10745 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10746 });
10747}
10748
10749bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10750 // We don't call noteFailure immediately because the assignment happens after
10751 // we evaluate LHS and RHS.
10752 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10753 return Error(E);
10754
10755 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10756 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10757 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10758
10759 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10760 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010761 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010762
10763 if (E->isComparisonOp()) {
10764 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10765 // comparisons and then translating the result.
10766 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10767 const BinaryOperator *E) {
10768 using CCR = ComparisonCategoryResult;
10769 bool IsEqual = ResKind == CCR::Equal,
10770 IsLess = ResKind == CCR::Less,
10771 IsGreater = ResKind == CCR::Greater;
10772 auto Op = E->getOpcode();
10773 switch (Op) {
10774 default:
10775 llvm_unreachable("unsupported binary operator");
10776 case BO_EQ:
10777 case BO_NE:
10778 return Success(IsEqual == (Op == BO_EQ), E);
10779 case BO_LT: return Success(IsLess, E);
10780 case BO_GT: return Success(IsGreater, E);
10781 case BO_LE: return Success(IsEqual || IsLess, E);
10782 case BO_GE: return Success(IsEqual || IsGreater, E);
10783 }
10784 };
10785 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10786 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10787 });
10788 }
10789
10790 QualType LHSTy = E->getLHS()->getType();
10791 QualType RHSTy = E->getRHS()->getType();
10792
10793 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10794 E->getOpcode() == BO_Sub) {
10795 LValue LHSValue, RHSValue;
10796
10797 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10798 if (!LHSOK && !Info.noteFailure())
10799 return false;
10800
10801 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10802 return false;
10803
10804 // Reject differing bases from the normal codepath; we special-case
10805 // comparisons to null.
10806 if (!HasSameBase(LHSValue, RHSValue)) {
10807 // Handle &&A - &&B.
10808 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10809 return Error(E);
10810 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10811 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10812 if (!LHSExpr || !RHSExpr)
10813 return Error(E);
10814 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10815 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10816 if (!LHSAddrExpr || !RHSAddrExpr)
10817 return Error(E);
10818 // Make sure both labels come from the same function.
10819 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10820 RHSAddrExpr->getLabel()->getDeclContext())
10821 return Error(E);
10822 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10823 }
10824 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10825 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10826
10827 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10828 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10829
10830 // C++11 [expr.add]p6:
10831 // Unless both pointers point to elements of the same array object, or
10832 // one past the last element of the array object, the behavior is
10833 // undefined.
10834 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10835 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10836 RHSDesignator))
10837 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10838
10839 QualType Type = E->getLHS()->getType();
10840 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10841
10842 CharUnits ElementSize;
10843 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10844 return false;
10845
10846 // As an extension, a type may have zero size (empty struct or union in
10847 // C, array of zero length). Pointer subtraction in such cases has
10848 // undefined behavior, so is not constant.
10849 if (ElementSize.isZero()) {
10850 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10851 << ElementType;
10852 return false;
10853 }
10854
10855 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10856 // and produce incorrect results when it overflows. Such behavior
10857 // appears to be non-conforming, but is common, so perhaps we should
10858 // assume the standard intended for such cases to be undefined behavior
10859 // and check for them.
10860
10861 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10862 // overflow in the final conversion to ptrdiff_t.
10863 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10864 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10865 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10866 false);
10867 APSInt TrueResult = (LHS - RHS) / ElemSize;
10868 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10869
10870 if (Result.extend(65) != TrueResult &&
10871 !HandleOverflow(Info, E, TrueResult, E->getType()))
10872 return false;
10873 return Success(Result, E);
10874 }
10875
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010876 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010877}
10878
Peter Collingbournee190dee2011-03-11 19:24:49 +000010879/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10880/// a result as the expression's type.
10881bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10882 const UnaryExprOrTypeTraitExpr *E) {
10883 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010884 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010885 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010886 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010887 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10888 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010889 else
Richard Smith6822bd72018-10-26 19:26:45 +000010890 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10891 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010892 }
Eli Friedman64004332009-03-23 04:38:34 +000010893
Peter Collingbournee190dee2011-03-11 19:24:49 +000010894 case UETT_VecStep: {
10895 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010896
Peter Collingbournee190dee2011-03-11 19:24:49 +000010897 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010898 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010899
Peter Collingbournee190dee2011-03-11 19:24:49 +000010900 // The vec_step built-in functions that take a 3-component
10901 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10902 if (n == 3)
10903 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010904
Peter Collingbournee190dee2011-03-11 19:24:49 +000010905 return Success(n, E);
10906 } else
10907 return Success(1, E);
10908 }
10909
10910 case UETT_SizeOf: {
10911 QualType SrcTy = E->getTypeOfArgument();
10912 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10913 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010914 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10915 SrcTy = Ref->getPointeeType();
10916
Richard Smithd62306a2011-11-10 06:34:14 +000010917 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010918 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010919 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010920 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010921 }
Alexey Bataev00396512015-07-02 03:40:19 +000010922 case UETT_OpenMPRequiredSimdAlign:
10923 assert(E->isArgumentType());
10924 return Success(
10925 Info.Ctx.toCharUnitsFromBits(
10926 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10927 .getQuantity(),
10928 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010929 }
10930
10931 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010932}
10933
Peter Collingbournee9200682011-05-13 03:29:01 +000010934bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010935 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010936 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010937 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010938 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010939 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010940 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010941 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010942 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010943 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010944 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010945 APSInt IdxResult;
10946 if (!EvaluateInteger(Idx, IdxResult, Info))
10947 return false;
10948 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10949 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010950 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010951 CurrentType = AT->getElementType();
10952 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10953 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010954 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010955 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010956
James Y Knight7281c352015-12-29 22:31:18 +000010957 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010958 FieldDecl *MemberDecl = ON.getField();
10959 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010960 if (!RT)
10961 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010962 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010963 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010964 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010965 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010966 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010967 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010968 CurrentType = MemberDecl->getType().getNonReferenceType();
10969 break;
10970 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010971
James Y Knight7281c352015-12-29 22:31:18 +000010972 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010973 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010974
James Y Knight7281c352015-12-29 22:31:18 +000010975 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010976 CXXBaseSpecifier *BaseSpec = ON.getBase();
10977 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010978 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010979
10980 // Find the layout of the class whose base we are looking into.
10981 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010982 if (!RT)
10983 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010984 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010985 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010986 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10987
10988 // Find the base class itself.
10989 CurrentType = BaseSpec->getType();
10990 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10991 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010992 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010993
Douglas Gregord1702062010-04-29 00:18:15 +000010994 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010995 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010996 break;
10997 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010998 }
10999 }
Peter Collingbournee9200682011-05-13 03:29:01 +000011000 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011001}
11002
Chris Lattnere13042c2008-07-11 19:10:17 +000011003bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011004 switch (E->getOpcode()) {
11005 default:
11006 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11007 // See C99 6.6p3.
11008 return Error(E);
11009 case UO_Extension:
11010 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11011 // If so, we could clear the diagnostic ID.
11012 return Visit(E->getSubExpr());
11013 case UO_Plus:
11014 // The result is just the value.
11015 return Visit(E->getSubExpr());
11016 case UO_Minus: {
11017 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000011018 return false;
11019 if (!Result.isInt()) return Error(E);
11020 const APSInt &Value = Result.getInt();
11021 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11022 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11023 E->getType()))
11024 return false;
Richard Smithfe800032012-01-31 04:08:20 +000011025 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011026 }
11027 case UO_Not: {
11028 if (!Visit(E->getSubExpr()))
11029 return false;
11030 if (!Result.isInt()) return Error(E);
11031 return Success(~Result.getInt(), E);
11032 }
11033 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000011034 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000011035 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000011036 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000011037 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000011038 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011039 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011040}
Mike Stump11289f42009-09-09 15:08:12 +000011041
Chris Lattner477c4be2008-07-12 01:15:53 +000011042/// HandleCast - This is used to evaluate implicit or explicit casts where the
11043/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000011044bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11045 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011046 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000011047 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011048
Eli Friedmanc757de22011-03-25 00:43:55 +000011049 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000011050 case CK_BaseToDerived:
11051 case CK_DerivedToBase:
11052 case CK_UncheckedDerivedToBase:
11053 case CK_Dynamic:
11054 case CK_ToUnion:
11055 case CK_ArrayToPointerDecay:
11056 case CK_FunctionToPointerDecay:
11057 case CK_NullToPointer:
11058 case CK_NullToMemberPointer:
11059 case CK_BaseToDerivedMemberPointer:
11060 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000011061 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000011062 case CK_ConstructorConversion:
11063 case CK_IntegralToPointer:
11064 case CK_ToVoid:
11065 case CK_VectorSplat:
11066 case CK_IntegralToFloating:
11067 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011068 case CK_CPointerToObjCPointerCast:
11069 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011070 case CK_AnyPointerToBlockPointerCast:
11071 case CK_ObjCObjectLValueCast:
11072 case CK_FloatingRealToComplex:
11073 case CK_FloatingComplexToReal:
11074 case CK_FloatingComplexCast:
11075 case CK_FloatingComplexToIntegralComplex:
11076 case CK_IntegralRealToComplex:
11077 case CK_IntegralComplexCast:
11078 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000011079 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011080 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011081 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011082 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011083 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011084 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011085 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000011086 llvm_unreachable("invalid cast kind for integral value");
11087
Eli Friedman9faf2f92011-03-25 19:07:11 +000011088 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011089 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011090 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000011091 case CK_ARCProduceObject:
11092 case CK_ARCConsumeObject:
11093 case CK_ARCReclaimReturnedObject:
11094 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011095 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011096 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011097
Richard Smith4ef685b2012-01-17 21:17:26 +000011098 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000011099 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011100 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000011101 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011102 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011103 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011104
11105 case CK_MemberPointerToBoolean:
11106 case CK_PointerToBoolean:
11107 case CK_IntegralToBoolean:
11108 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011109 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011110 case CK_FloatingComplexToBoolean:
11111 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011112 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011113 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011114 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011115 uint64_t IntResult = BoolResult;
11116 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11117 IntResult = (uint64_t)-1;
11118 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011119 }
11120
Leonard Chan8f7caae2019-03-06 00:28:43 +000011121 case CK_FixedPointToIntegral: {
11122 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11123 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11124 return false;
11125 bool Overflowed;
11126 llvm::APSInt Result = Src.convertToInt(
11127 Info.Ctx.getIntWidth(DestType),
11128 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11129 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11130 return false;
11131 return Success(Result, E);
11132 }
11133
Leonard Chanb4ba4672018-10-23 17:55:35 +000011134 case CK_FixedPointToBoolean: {
11135 // Unsigned padding does not affect this.
11136 APValue Val;
11137 if (!Evaluate(Val, Info, SubExpr))
11138 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011139 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011140 }
11141
Eli Friedmanc757de22011-03-25 00:43:55 +000011142 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011143 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011144 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011145
Eli Friedman742421e2009-02-20 01:15:07 +000011146 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011147 // Allow casts of address-of-label differences if they are no-ops
11148 // or narrowing. (The narrowing case isn't actually guaranteed to
11149 // be constant-evaluatable except in some narrow cases which are hard
11150 // to detect here. We let it through on the assumption the user knows
11151 // what they are doing.)
11152 if (Result.isAddrLabelDiff())
11153 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011154 // Only allow casts of lvalues if they are lossless.
11155 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11156 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011157
Richard Smith911e1422012-01-30 22:27:01 +000011158 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11159 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011160 }
Mike Stump11289f42009-09-09 15:08:12 +000011161
Eli Friedmanc757de22011-03-25 00:43:55 +000011162 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011163 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11164
John McCall45d55e42010-05-07 21:00:08 +000011165 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011166 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011167 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011168
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011169 if (LV.getLValueBase()) {
11170 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011171 // FIXME: Allow a larger integer size than the pointer size, and allow
11172 // narrowing back down to pointer width in subsequent integral casts.
11173 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011174 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011175 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011176
Richard Smithcf74da72011-11-16 07:18:12 +000011177 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011178 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011179 return true;
11180 }
11181
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011182 APSInt AsInt;
11183 APValue V;
11184 LV.moveInto(V);
11185 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11186 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011187
Richard Smith911e1422012-01-30 22:27:01 +000011188 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011189 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011190
Eli Friedmanc757de22011-03-25 00:43:55 +000011191 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011192 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011193 if (!EvaluateComplex(SubExpr, C, Info))
11194 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011195 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011196 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011197
Eli Friedmanc757de22011-03-25 00:43:55 +000011198 case CK_FloatingToIntegral: {
11199 APFloat F(0.0);
11200 if (!EvaluateFloat(SubExpr, F, Info))
11201 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011202
Richard Smith357362d2011-12-13 06:39:58 +000011203 APSInt Value;
11204 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11205 return false;
11206 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011207 }
11208 }
Mike Stump11289f42009-09-09 15:08:12 +000011209
Eli Friedmanc757de22011-03-25 00:43:55 +000011210 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011211}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011212
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011213bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11214 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011215 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011216 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11217 return false;
11218 if (!LV.isComplexInt())
11219 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011220 return Success(LV.getComplexIntReal(), E);
11221 }
11222
11223 return Visit(E->getSubExpr());
11224}
11225
Eli Friedman4e7a2412009-02-27 04:45:43 +000011226bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011227 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011228 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011229 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11230 return false;
11231 if (!LV.isComplexInt())
11232 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011233 return Success(LV.getComplexIntImag(), E);
11234 }
11235
Richard Smith4a678122011-10-24 18:44:57 +000011236 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011237 return Success(0, E);
11238}
11239
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011240bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11241 return Success(E->getPackLength(), E);
11242}
11243
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011244bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11245 return Success(E->getValue(), E);
11246}
11247
Leonard Chandb01c3a2018-06-20 17:19:40 +000011248bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11249 switch (E->getOpcode()) {
11250 default:
11251 // Invalid unary operators
11252 return Error(E);
11253 case UO_Plus:
11254 // The result is just the value.
11255 return Visit(E->getSubExpr());
11256 case UO_Minus: {
11257 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011258 if (!Result.isFixedPoint())
11259 return Error(E);
11260 bool Overflowed;
11261 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11262 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11263 return false;
11264 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011265 }
11266 case UO_LNot: {
11267 bool bres;
11268 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11269 return false;
11270 return Success(!bres, E);
11271 }
11272 }
11273}
11274
Leonard Chand3f3e162019-01-18 21:04:25 +000011275bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11276 const Expr *SubExpr = E->getSubExpr();
11277 QualType DestType = E->getType();
11278 assert(DestType->isFixedPointType() &&
11279 "Expected destination type to be a fixed point type");
11280 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11281
11282 switch (E->getCastKind()) {
11283 case CK_FixedPointCast: {
11284 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11285 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11286 return false;
11287 bool Overflowed;
11288 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11289 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11290 return false;
11291 return Success(Result, E);
11292 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011293 case CK_IntegralToFixedPoint: {
11294 APSInt Src;
11295 if (!EvaluateInteger(SubExpr, Src, Info))
11296 return false;
11297
11298 bool Overflowed;
11299 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11300 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11301
11302 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11303 return false;
11304
11305 return Success(IntResult, E);
11306 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011307 case CK_NoOp:
11308 case CK_LValueToRValue:
11309 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11310 default:
11311 return Error(E);
11312 }
11313}
11314
11315bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11316 const Expr *LHS = E->getLHS();
11317 const Expr *RHS = E->getRHS();
11318 FixedPointSemantics ResultFXSema =
11319 Info.Ctx.getFixedPointSemantics(E->getType());
11320
11321 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11322 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11323 return false;
11324 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11325 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11326 return false;
11327
11328 switch (E->getOpcode()) {
11329 case BO_Add: {
11330 bool AddOverflow, ConversionOverflow;
11331 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11332 .convert(ResultFXSema, &ConversionOverflow);
11333 if ((AddOverflow || ConversionOverflow) &&
11334 !HandleOverflow(Info, E, Result, E->getType()))
11335 return false;
11336 return Success(Result, E);
11337 }
11338 default:
11339 return false;
11340 }
11341 llvm_unreachable("Should've exited before this");
11342}
11343
Chris Lattner05706e882008-07-11 18:11:29 +000011344//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000011345// Float Evaluation
11346//===----------------------------------------------------------------------===//
11347
11348namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011349class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011350 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000011351 APFloat &Result;
11352public:
11353 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011354 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000011355
Richard Smith2e312c82012-03-03 22:46:17 +000011356 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011357 Result = V.getFloat();
11358 return true;
11359 }
Eli Friedman24c01542008-08-22 00:06:13 +000011360
Richard Smithfddd3842011-12-30 21:15:51 +000011361 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000011362 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11363 return true;
11364 }
11365
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011366 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011367
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011368 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011369 bool VisitBinaryOperator(const BinaryOperator *E);
11370 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011371 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000011372
John McCallb1fb0d32010-05-07 22:08:54 +000011373 bool VisitUnaryReal(const UnaryOperator *E);
11374 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000011375
Richard Smithfddd3842011-12-30 21:15:51 +000011376 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000011377};
11378} // end anonymous namespace
11379
11380static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011381 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011382 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000011383}
11384
Jay Foad39c79802011-01-12 09:06:06 +000011385static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000011386 QualType ResultTy,
11387 const Expr *Arg,
11388 bool SNaN,
11389 llvm::APFloat &Result) {
11390 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11391 if (!S) return false;
11392
11393 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11394
11395 llvm::APInt fill;
11396
11397 // Treat empty strings as if they were zero.
11398 if (S->getString().empty())
11399 fill = llvm::APInt(32, 0);
11400 else if (S->getString().getAsInteger(0, fill))
11401 return false;
11402
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000011403 if (Context.getTargetInfo().isNan2008()) {
11404 if (SNaN)
11405 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11406 else
11407 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11408 } else {
11409 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11410 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11411 // a different encoding to what became a standard in 2008, and for pre-
11412 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11413 // sNaN. This is now known as "legacy NaN" encoding.
11414 if (SNaN)
11415 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11416 else
11417 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11418 }
11419
John McCall16291492010-02-28 13:00:19 +000011420 return true;
11421}
11422
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011423bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000011424 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011425 default:
11426 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11427
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011428 case Builtin::BI__builtin_huge_val:
11429 case Builtin::BI__builtin_huge_valf:
11430 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011431 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011432 case Builtin::BI__builtin_inf:
11433 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011434 case Builtin::BI__builtin_infl:
11435 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011436 const llvm::fltSemantics &Sem =
11437 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000011438 Result = llvm::APFloat::getInf(Sem);
11439 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011440 }
Mike Stump11289f42009-09-09 15:08:12 +000011441
John McCall16291492010-02-28 13:00:19 +000011442 case Builtin::BI__builtin_nans:
11443 case Builtin::BI__builtin_nansf:
11444 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011445 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011446 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11447 true, Result))
11448 return Error(E);
11449 return true;
John McCall16291492010-02-28 13:00:19 +000011450
Chris Lattner0b7282e2008-10-06 06:31:58 +000011451 case Builtin::BI__builtin_nan:
11452 case Builtin::BI__builtin_nanf:
11453 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011454 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000011455 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000011456 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000011457 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11458 false, Result))
11459 return Error(E);
11460 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011461
11462 case Builtin::BI__builtin_fabs:
11463 case Builtin::BI__builtin_fabsf:
11464 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011465 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011466 if (!EvaluateFloat(E->getArg(0), Result, Info))
11467 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011468
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011469 if (Result.isNegative())
11470 Result.changeSign();
11471 return true;
11472
Richard Smith8889a3d2013-06-13 06:26:32 +000011473 // FIXME: Builtin::BI__builtin_powi
11474 // FIXME: Builtin::BI__builtin_powif
11475 // FIXME: Builtin::BI__builtin_powil
11476
Mike Stump11289f42009-09-09 15:08:12 +000011477 case Builtin::BI__builtin_copysign:
11478 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011479 case Builtin::BI__builtin_copysignl:
11480 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011481 APFloat RHS(0.);
11482 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11483 !EvaluateFloat(E->getArg(1), RHS, Info))
11484 return false;
11485 Result.copySign(RHS);
11486 return true;
11487 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011488 }
11489}
11490
John McCallb1fb0d32010-05-07 22:08:54 +000011491bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011492 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11493 ComplexValue CV;
11494 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11495 return false;
11496 Result = CV.FloatReal;
11497 return true;
11498 }
11499
11500 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000011501}
11502
11503bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011504 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11505 ComplexValue CV;
11506 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11507 return false;
11508 Result = CV.FloatImag;
11509 return true;
11510 }
11511
Richard Smith4a678122011-10-24 18:44:57 +000011512 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011513 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11514 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011515 return true;
11516}
11517
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011518bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011519 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011520 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011521 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011522 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011523 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011524 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11525 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011526 Result.changeSign();
11527 return true;
11528 }
11529}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011530
Eli Friedman24c01542008-08-22 00:06:13 +000011531bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011532 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011534
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011535 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011536 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011537 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011538 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011539 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11540 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011541}
11542
11543bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11544 Result = E->getValue();
11545 return true;
11546}
11547
Peter Collingbournee9200682011-05-13 03:29:01 +000011548bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11549 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011550
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011551 switch (E->getCastKind()) {
11552 default:
Richard Smith11562c52011-10-28 17:51:58 +000011553 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011554
11555 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011556 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011557 return EvaluateInteger(SubExpr, IntResult, Info) &&
11558 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11559 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011560 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011561
11562 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011563 if (!Visit(SubExpr))
11564 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011565 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11566 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011567 }
John McCalld7646252010-11-14 08:17:51 +000011568
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011569 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011570 ComplexValue V;
11571 if (!EvaluateComplex(SubExpr, V, Info))
11572 return false;
11573 Result = V.getComplexFloatReal();
11574 return true;
11575 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011576 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011577}
11578
Eli Friedman24c01542008-08-22 00:06:13 +000011579//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011580// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011581//===----------------------------------------------------------------------===//
11582
11583namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011584class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011585 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011586 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011587
Anders Carlsson537969c2008-11-16 20:27:53 +000011588public:
John McCall93d91dc2010-05-07 17:22:02 +000011589 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011590 : ExprEvaluatorBaseTy(info), Result(Result) {}
11591
Richard Smith2e312c82012-03-03 22:46:17 +000011592 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011593 Result.setFrom(V);
11594 return true;
11595 }
Mike Stump11289f42009-09-09 15:08:12 +000011596
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011597 bool ZeroInitialization(const Expr *E);
11598
Anders Carlsson537969c2008-11-16 20:27:53 +000011599 //===--------------------------------------------------------------------===//
11600 // Visitor Methods
11601 //===--------------------------------------------------------------------===//
11602
Peter Collingbournee9200682011-05-13 03:29:01 +000011603 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011604 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011605 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011606 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011607 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011608};
11609} // end anonymous namespace
11610
John McCall93d91dc2010-05-07 17:22:02 +000011611static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11612 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011613 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011614 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011615}
11616
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011617bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011618 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011619 if (ElemTy->isRealFloatingType()) {
11620 Result.makeComplexFloat();
11621 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11622 Result.FloatReal = Zero;
11623 Result.FloatImag = Zero;
11624 } else {
11625 Result.makeComplexInt();
11626 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11627 Result.IntReal = Zero;
11628 Result.IntImag = Zero;
11629 }
11630 return true;
11631}
11632
Peter Collingbournee9200682011-05-13 03:29:01 +000011633bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11634 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011635
11636 if (SubExpr->getType()->isRealFloatingType()) {
11637 Result.makeComplexFloat();
11638 APFloat &Imag = Result.FloatImag;
11639 if (!EvaluateFloat(SubExpr, Imag, Info))
11640 return false;
11641
11642 Result.FloatReal = APFloat(Imag.getSemantics());
11643 return true;
11644 } else {
11645 assert(SubExpr->getType()->isIntegerType() &&
11646 "Unexpected imaginary literal.");
11647
11648 Result.makeComplexInt();
11649 APSInt &Imag = Result.IntImag;
11650 if (!EvaluateInteger(SubExpr, Imag, Info))
11651 return false;
11652
11653 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11654 return true;
11655 }
11656}
11657
Peter Collingbournee9200682011-05-13 03:29:01 +000011658bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011659
John McCallfcef3cf2010-12-14 17:51:41 +000011660 switch (E->getCastKind()) {
11661 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011662 case CK_BaseToDerived:
11663 case CK_DerivedToBase:
11664 case CK_UncheckedDerivedToBase:
11665 case CK_Dynamic:
11666 case CK_ToUnion:
11667 case CK_ArrayToPointerDecay:
11668 case CK_FunctionToPointerDecay:
11669 case CK_NullToPointer:
11670 case CK_NullToMemberPointer:
11671 case CK_BaseToDerivedMemberPointer:
11672 case CK_DerivedToBaseMemberPointer:
11673 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011674 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011675 case CK_ConstructorConversion:
11676 case CK_IntegralToPointer:
11677 case CK_PointerToIntegral:
11678 case CK_PointerToBoolean:
11679 case CK_ToVoid:
11680 case CK_VectorSplat:
11681 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011682 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011683 case CK_IntegralToBoolean:
11684 case CK_IntegralToFloating:
11685 case CK_FloatingToIntegral:
11686 case CK_FloatingToBoolean:
11687 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011688 case CK_CPointerToObjCPointerCast:
11689 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011690 case CK_AnyPointerToBlockPointerCast:
11691 case CK_ObjCObjectLValueCast:
11692 case CK_FloatingComplexToReal:
11693 case CK_FloatingComplexToBoolean:
11694 case CK_IntegralComplexToReal:
11695 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011696 case CK_ARCProduceObject:
11697 case CK_ARCConsumeObject:
11698 case CK_ARCReclaimReturnedObject:
11699 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011700 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011701 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011702 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011703 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011704 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011705 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011706 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011707 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011708 case CK_FixedPointToIntegral:
11709 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011710 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011711
John McCallfcef3cf2010-12-14 17:51:41 +000011712 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011713 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011714 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011715 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011716 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011717
11718 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011719 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011720 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011721 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011722
11723 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011724 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011725 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011726 return false;
11727
John McCallfcef3cf2010-12-14 17:51:41 +000011728 Result.makeComplexFloat();
11729 Result.FloatImag = APFloat(Real.getSemantics());
11730 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011731 }
11732
John McCallfcef3cf2010-12-14 17:51:41 +000011733 case CK_FloatingComplexCast: {
11734 if (!Visit(E->getSubExpr()))
11735 return false;
11736
11737 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11738 QualType From
11739 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11740
Richard Smith357362d2011-12-13 06:39:58 +000011741 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11742 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011743 }
11744
11745 case CK_FloatingComplexToIntegralComplex: {
11746 if (!Visit(E->getSubExpr()))
11747 return false;
11748
11749 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11750 QualType From
11751 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11752 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011753 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11754 To, Result.IntReal) &&
11755 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11756 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011757 }
11758
11759 case CK_IntegralRealToComplex: {
11760 APSInt &Real = Result.IntReal;
11761 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11762 return false;
11763
11764 Result.makeComplexInt();
11765 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11766 return true;
11767 }
11768
11769 case CK_IntegralComplexCast: {
11770 if (!Visit(E->getSubExpr()))
11771 return false;
11772
11773 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11774 QualType From
11775 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11776
Richard Smith911e1422012-01-30 22:27:01 +000011777 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11778 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011779 return true;
11780 }
11781
11782 case CK_IntegralComplexToFloatingComplex: {
11783 if (!Visit(E->getSubExpr()))
11784 return false;
11785
Ted Kremenek28831752012-08-23 20:46:57 +000011786 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011787 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011788 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011789 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011790 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11791 To, Result.FloatReal) &&
11792 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11793 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011794 }
11795 }
11796
11797 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011798}
11799
John McCall93d91dc2010-05-07 17:22:02 +000011800bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011801 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011802 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11803
Chandler Carrutha216cad2014-10-11 00:57:18 +000011804 // Track whether the LHS or RHS is real at the type system level. When this is
11805 // the case we can simplify our evaluation strategy.
11806 bool LHSReal = false, RHSReal = false;
11807
11808 bool LHSOK;
11809 if (E->getLHS()->getType()->isRealFloatingType()) {
11810 LHSReal = true;
11811 APFloat &Real = Result.FloatReal;
11812 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11813 if (LHSOK) {
11814 Result.makeComplexFloat();
11815 Result.FloatImag = APFloat(Real.getSemantics());
11816 }
11817 } else {
11818 LHSOK = Visit(E->getLHS());
11819 }
George Burgess IVa145e252016-05-25 22:38:36 +000011820 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011821 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011822
John McCall93d91dc2010-05-07 17:22:02 +000011823 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011824 if (E->getRHS()->getType()->isRealFloatingType()) {
11825 RHSReal = true;
11826 APFloat &Real = RHS.FloatReal;
11827 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11828 return false;
11829 RHS.makeComplexFloat();
11830 RHS.FloatImag = APFloat(Real.getSemantics());
11831 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011832 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011833
Chandler Carrutha216cad2014-10-11 00:57:18 +000011834 assert(!(LHSReal && RHSReal) &&
11835 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011836 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011837 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011838 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011839 if (Result.isComplexFloat()) {
11840 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11841 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011842 if (LHSReal)
11843 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11844 else if (!RHSReal)
11845 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11846 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011847 } else {
11848 Result.getComplexIntReal() += RHS.getComplexIntReal();
11849 Result.getComplexIntImag() += RHS.getComplexIntImag();
11850 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011851 break;
John McCalle3027922010-08-25 11:45:40 +000011852 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011853 if (Result.isComplexFloat()) {
11854 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11855 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011856 if (LHSReal) {
11857 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11858 Result.getComplexFloatImag().changeSign();
11859 } else if (!RHSReal) {
11860 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11861 APFloat::rmNearestTiesToEven);
11862 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011863 } else {
11864 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11865 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11866 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011867 break;
John McCalle3027922010-08-25 11:45:40 +000011868 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011869 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011870 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011871 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011872 // following naming scheme:
11873 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011874 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011875 APFloat &A = LHS.getComplexFloatReal();
11876 APFloat &B = LHS.getComplexFloatImag();
11877 APFloat &C = RHS.getComplexFloatReal();
11878 APFloat &D = RHS.getComplexFloatImag();
11879 APFloat &ResR = Result.getComplexFloatReal();
11880 APFloat &ResI = Result.getComplexFloatImag();
11881 if (LHSReal) {
11882 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11883 ResR = A * C;
11884 ResI = A * D;
11885 } else if (RHSReal) {
11886 ResR = C * A;
11887 ResI = C * B;
11888 } else {
11889 // In the fully general case, we need to handle NaNs and infinities
11890 // robustly.
11891 APFloat AC = A * C;
11892 APFloat BD = B * D;
11893 APFloat AD = A * D;
11894 APFloat BC = B * C;
11895 ResR = AC - BD;
11896 ResI = AD + BC;
11897 if (ResR.isNaN() && ResI.isNaN()) {
11898 bool Recalc = false;
11899 if (A.isInfinity() || B.isInfinity()) {
11900 A = APFloat::copySign(
11901 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11902 B = APFloat::copySign(
11903 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11904 if (C.isNaN())
11905 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11906 if (D.isNaN())
11907 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11908 Recalc = true;
11909 }
11910 if (C.isInfinity() || D.isInfinity()) {
11911 C = APFloat::copySign(
11912 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11913 D = APFloat::copySign(
11914 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11915 if (A.isNaN())
11916 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11917 if (B.isNaN())
11918 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11919 Recalc = true;
11920 }
11921 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11922 AD.isInfinity() || BC.isInfinity())) {
11923 if (A.isNaN())
11924 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11925 if (B.isNaN())
11926 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11927 if (C.isNaN())
11928 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11929 if (D.isNaN())
11930 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11931 Recalc = true;
11932 }
11933 if (Recalc) {
11934 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11935 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11936 }
11937 }
11938 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011939 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011940 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011941 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011942 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11943 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011944 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011945 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11946 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11947 }
11948 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011949 case BO_Div:
11950 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011951 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011952 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011953 // following naming scheme:
11954 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011955 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011956 APFloat &A = LHS.getComplexFloatReal();
11957 APFloat &B = LHS.getComplexFloatImag();
11958 APFloat &C = RHS.getComplexFloatReal();
11959 APFloat &D = RHS.getComplexFloatImag();
11960 APFloat &ResR = Result.getComplexFloatReal();
11961 APFloat &ResI = Result.getComplexFloatImag();
11962 if (RHSReal) {
11963 ResR = A / C;
11964 ResI = B / C;
11965 } else {
11966 if (LHSReal) {
11967 // No real optimizations we can do here, stub out with zero.
11968 B = APFloat::getZero(A.getSemantics());
11969 }
11970 int DenomLogB = 0;
11971 APFloat MaxCD = maxnum(abs(C), abs(D));
11972 if (MaxCD.isFinite()) {
11973 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011974 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11975 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011976 }
11977 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011978 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11979 APFloat::rmNearestTiesToEven);
11980 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11981 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011982 if (ResR.isNaN() && ResI.isNaN()) {
11983 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11984 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11985 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11986 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11987 D.isFinite()) {
11988 A = APFloat::copySign(
11989 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11990 B = APFloat::copySign(
11991 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11992 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11993 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11994 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11995 C = APFloat::copySign(
11996 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11997 D = APFloat::copySign(
11998 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11999 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
12000 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12001 }
12002 }
12003 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012004 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012005 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12006 return Error(E, diag::note_expr_divide_by_zero);
12007
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012008 ComplexValue LHS = Result;
12009 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12010 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12011 Result.getComplexIntReal() =
12012 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12013 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12014 Result.getComplexIntImag() =
12015 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12016 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12017 }
12018 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012019 }
12020
John McCall93d91dc2010-05-07 17:22:02 +000012021 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012022}
12023
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012024bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12025 // Get the operand value into 'Result'.
12026 if (!Visit(E->getSubExpr()))
12027 return false;
12028
12029 switch (E->getOpcode()) {
12030 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012031 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012032 case UO_Extension:
12033 return true;
12034 case UO_Plus:
12035 // The result is always just the subexpr.
12036 return true;
12037 case UO_Minus:
12038 if (Result.isComplexFloat()) {
12039 Result.getComplexFloatReal().changeSign();
12040 Result.getComplexFloatImag().changeSign();
12041 }
12042 else {
12043 Result.getComplexIntReal() = -Result.getComplexIntReal();
12044 Result.getComplexIntImag() = -Result.getComplexIntImag();
12045 }
12046 return true;
12047 case UO_Not:
12048 if (Result.isComplexFloat())
12049 Result.getComplexFloatImag().changeSign();
12050 else
12051 Result.getComplexIntImag() = -Result.getComplexIntImag();
12052 return true;
12053 }
12054}
12055
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012056bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12057 if (E->getNumInits() == 2) {
12058 if (E->getType()->isComplexType()) {
12059 Result.makeComplexFloat();
12060 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12061 return false;
12062 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12063 return false;
12064 } else {
12065 Result.makeComplexInt();
12066 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12067 return false;
12068 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12069 return false;
12070 }
12071 return true;
12072 }
12073 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12074}
12075
Anders Carlsson537969c2008-11-16 20:27:53 +000012076//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000012077// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12078// implicit conversion.
12079//===----------------------------------------------------------------------===//
12080
12081namespace {
12082class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000012083 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012084 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000012085 APValue &Result;
12086public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012087 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12088 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000012089
12090 bool Success(const APValue &V, const Expr *E) {
12091 Result = V;
12092 return true;
12093 }
12094
12095 bool ZeroInitialization(const Expr *E) {
12096 ImplicitValueInitExpr VIE(
12097 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012098 // For atomic-qualified class (and array) types in C++, initialize the
12099 // _Atomic-wrapped subobject directly, in-place.
12100 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12101 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000012102 }
12103
12104 bool VisitCastExpr(const CastExpr *E) {
12105 switch (E->getCastKind()) {
12106 default:
12107 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12108 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012109 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12110 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012111 }
12112 }
12113};
12114} // end anonymous namespace
12115
Richard Smith64cb9ca2017-02-22 22:09:50 +000012116static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12117 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012118 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012119 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012120}
12121
12122//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012123// Void expression evaluation, primarily for a cast to void on the LHS of a
12124// comma operator
12125//===----------------------------------------------------------------------===//
12126
12127namespace {
12128class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012129 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012130public:
12131 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12132
Richard Smith2e312c82012-03-03 22:46:17 +000012133 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012134
Richard Smith7cd577b2017-08-17 19:35:50 +000012135 bool ZeroInitialization(const Expr *E) { return true; }
12136
Richard Smith42d3af92011-12-07 00:43:50 +000012137 bool VisitCastExpr(const CastExpr *E) {
12138 switch (E->getCastKind()) {
12139 default:
12140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12141 case CK_ToVoid:
12142 VisitIgnoredValue(E->getSubExpr());
12143 return true;
12144 }
12145 }
Hal Finkela8443c32014-07-17 14:49:58 +000012146
12147 bool VisitCallExpr(const CallExpr *E) {
12148 switch (E->getBuiltinCallee()) {
12149 default:
12150 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12151 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012152 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012153 // The argument is not evaluated!
12154 return true;
12155 }
12156 }
Richard Smith42d3af92011-12-07 00:43:50 +000012157};
12158} // end anonymous namespace
12159
12160static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12161 assert(E->isRValue() && E->getType()->isVoidType());
12162 return VoidExprEvaluator(Info).Visit(E);
12163}
12164
12165//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012166// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012167//===----------------------------------------------------------------------===//
12168
Richard Smith2e312c82012-03-03 22:46:17 +000012169static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012170 // In C, function designators are not lvalues, but we evaluate them as if they
12171 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012172 QualType T = E->getType();
12173 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012174 LValue LV;
12175 if (!EvaluateLValue(E, LV, Info))
12176 return false;
12177 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012178 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012179 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012180 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012181 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012182 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012183 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012184 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012185 LValue LV;
12186 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012187 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012188 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012189 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012190 llvm::APFloat F(0.0);
12191 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012192 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012193 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012194 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012195 ComplexValue C;
12196 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012197 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012198 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012199 } else if (T->isFixedPointType()) {
12200 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012201 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012202 MemberPtr P;
12203 if (!EvaluateMemberPointer(E, P, Info))
12204 return false;
12205 P.moveInto(Result);
12206 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012207 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012208 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012209 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012210 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012211 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012212 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012213 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012214 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012215 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012216 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012217 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012218 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012219 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012220 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012221 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012222 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012223 if (!EvaluateVoid(E, Info))
12224 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012225 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012226 QualType Unqual = T.getAtomicUnqualifiedType();
12227 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12228 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012229 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012230 if (!EvaluateAtomic(E, &LV, Value, Info))
12231 return false;
12232 } else {
12233 if (!EvaluateAtomic(E, nullptr, Result, Info))
12234 return false;
12235 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012236 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000012237 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000012238 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012239 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000012240 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000012241 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012242 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012243
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000012244 return true;
12245}
12246
Richard Smithb228a862012-02-15 02:18:13 +000012247/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12248/// cases, the in-place evaluation is essential, since later initializers for
12249/// an object can indirectly refer to subobjects which were initialized earlier.
12250static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000012251 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000012252 assert(!E->isValueDependent());
12253
Richard Smith7525ff62013-05-09 07:14:00 +000012254 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000012255 return false;
12256
12257 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000012258 // Evaluate arrays and record types in-place, so that later initializers can
12259 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000012260 QualType T = E->getType();
12261 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000012262 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012263 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000012264 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012265 else if (T->isAtomicType()) {
12266 QualType Unqual = T.getAtomicUnqualifiedType();
12267 if (Unqual->isArrayType() || Unqual->isRecordType())
12268 return EvaluateAtomic(E, &This, Result, Info);
12269 }
Richard Smithed5165f2011-11-04 05:33:44 +000012270 }
12271
12272 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000012273 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000012274}
12275
Richard Smithf57d8cb2011-12-09 22:58:01 +000012276/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12277/// lvalue-to-rvalue cast if it is an lvalue.
12278static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000012279 if (E->getType().isNull())
12280 return false;
12281
Nick Lewyckyc190f962017-05-02 01:06:16 +000012282 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000012283 return false;
12284
Richard Smith2e312c82012-03-03 22:46:17 +000012285 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012286 return false;
12287
12288 if (E->isGLValue()) {
12289 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000012290 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000012291 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012292 return false;
12293 }
12294
Richard Smith2e312c82012-03-03 22:46:17 +000012295 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000012296 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012297}
Richard Smith11562c52011-10-28 17:51:58 +000012298
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012299static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000012300 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012301 // Fast-path evaluations of integer literals, since we sometimes see files
12302 // containing vast quantities of these.
12303 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12304 Result.Val = APValue(APSInt(L->getValue(),
12305 L->getType()->isUnsignedIntegerType()));
12306 IsConst = true;
12307 return true;
12308 }
James Dennett0492ef02014-03-14 17:44:10 +000012309
12310 // This case should be rare, but we need to check it before we check on
12311 // the type below.
12312 if (Exp->getType().isNull()) {
12313 IsConst = false;
12314 return true;
12315 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012316
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012317 // FIXME: Evaluating values of large array and record types can cause
12318 // performance problems. Only do so in C++11 for now.
12319 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12320 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000012321 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012322 IsConst = false;
12323 return true;
12324 }
12325 return false;
12326}
12327
Fangrui Song407659a2018-11-30 23:41:18 +000012328static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12329 Expr::SideEffectsKind SEK) {
12330 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12331 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12332}
12333
12334static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12335 const ASTContext &Ctx, EvalInfo &Info) {
12336 bool IsConst;
12337 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12338 return IsConst;
12339
12340 return EvaluateAsRValue(Info, E, Result.Val);
12341}
12342
12343static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12344 const ASTContext &Ctx,
12345 Expr::SideEffectsKind AllowSideEffects,
12346 EvalInfo &Info) {
12347 if (!E->getType()->isIntegralOrEnumerationType())
12348 return false;
12349
12350 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12351 !ExprResult.Val.isInt() ||
12352 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12353 return false;
12354
12355 return true;
12356}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012357
Leonard Chand3f3e162019-01-18 21:04:25 +000012358static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12359 const ASTContext &Ctx,
12360 Expr::SideEffectsKind AllowSideEffects,
12361 EvalInfo &Info) {
12362 if (!E->getType()->isFixedPointType())
12363 return false;
12364
12365 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12366 return false;
12367
12368 if (!ExprResult.Val.isFixedPoint() ||
12369 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12370 return false;
12371
12372 return true;
12373}
12374
Richard Smith7b553f12011-10-29 00:50:52 +000012375/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000012376/// any crazy technique (that has nothing to do with language standards) that
12377/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000012378/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12379/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000012380bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12381 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012382 assert(!isValueDependent() &&
12383 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000012384 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012385 Info.InConstantContext = InConstantContext;
12386 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000012387}
12388
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012389bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12390 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012391 assert(!isValueDependent() &&
12392 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000012393 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012394 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000012395 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000012396}
12397
Fangrui Song407659a2018-11-30 23:41:18 +000012398bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012399 SideEffectsKind AllowSideEffects,
12400 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012401 assert(!isValueDependent() &&
12402 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000012403 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012404 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000012405 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000012406}
12407
Leonard Chand3f3e162019-01-18 21:04:25 +000012408bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012409 SideEffectsKind AllowSideEffects,
12410 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012411 assert(!isValueDependent() &&
12412 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000012413 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012414 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000012415 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12416}
12417
Richard Trieube234c32016-04-21 21:04:55 +000012418bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012419 SideEffectsKind AllowSideEffects,
12420 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012421 assert(!isValueDependent() &&
12422 "Expression evaluator can't be called on a dependent expression.");
12423
Richard Trieube234c32016-04-21 21:04:55 +000012424 if (!getType()->isRealFloatingType())
12425 return false;
12426
12427 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012428 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12429 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000012430 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000012431 return false;
12432
12433 Result = ExprResult.Val.getFloat();
12434 return true;
12435}
12436
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012437bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12438 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012439 assert(!isValueDependent() &&
12440 "Expression evaluator can't be called on a dependent expression.");
12441
Richard Smith6d4c6582013-11-05 22:18:15 +000012442 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012443 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000012444 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000012445 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12446 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000012447 Ctx.getLValueReferenceType(getType()), LV,
12448 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000012449 return false;
12450
Richard Smith2e312c82012-03-03 22:46:17 +000012451 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000012452 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000012453}
12454
Reid Kleckner1a840d22018-05-10 18:57:35 +000012455bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12456 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012457 assert(!isValueDependent() &&
12458 "Expression evaluator can't be called on a dependent expression.");
12459
Reid Kleckner1a840d22018-05-10 18:57:35 +000012460 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12461 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000012462 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000012463
Reid Kleckner1a840d22018-05-10 18:57:35 +000012464 if (!::Evaluate(Result.Val, Info, this))
12465 return false;
12466
12467 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12468 Usage);
12469}
12470
Richard Smithd0b4dd62011-12-19 06:19:21 +000012471bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12472 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012473 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012474 assert(!isValueDependent() &&
12475 "Expression evaluator can't be called on a dependent expression.");
12476
Richard Smithdafff942012-01-14 04:30:29 +000012477 // FIXME: Evaluating initializers for large array and record types can cause
12478 // performance problems. Only do so in C++11 for now.
12479 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012480 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000012481 return false;
12482
Richard Smithd0b4dd62011-12-19 06:19:21 +000012483 Expr::EvalStatus EStatus;
12484 EStatus.Diag = &Notes;
12485
Richard Smith0c6124b2015-12-03 01:36:22 +000012486 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12487 ? EvalInfo::EM_ConstantExpression
12488 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012489 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000012490 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000012491
12492 LValue LVal;
12493 LVal.set(VD);
12494
Richard Smithfddd3842011-12-30 21:15:51 +000012495 // C++11 [basic.start.init]p2:
12496 // Variables with static storage duration or thread storage duration shall be
12497 // zero-initialized before any other initialization takes place.
12498 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012499 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000012500 !VD->getType()->isReferenceType()) {
12501 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000012502 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000012503 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000012504 return false;
12505 }
12506
Richard Smith7525ff62013-05-09 07:14:00 +000012507 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12508 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012509 EStatus.HasSideEffects)
12510 return false;
12511
12512 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12513 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012514}
12515
Richard Smith7b553f12011-10-29 00:50:52 +000012516/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12517/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012518bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012519 assert(!isValueDependent() &&
12520 "Expression evaluator can't be called on a dependent expression.");
12521
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012522 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012523 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012524 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012525}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012526
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012527APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012528 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012529 assert(!isValueDependent() &&
12530 "Expression evaluator can't be called on a dependent expression.");
12531
Fangrui Song407659a2018-11-30 23:41:18 +000012532 EvalResult EVResult;
12533 EVResult.Diag = Diag;
12534 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12535 Info.InConstantContext = true;
12536
12537 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012538 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012539 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012540 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012541
Fangrui Song407659a2018-11-30 23:41:18 +000012542 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012543}
John McCall864e3962010-05-07 05:32:02 +000012544
David Bolvansky3b6ae572018-10-18 20:49:06 +000012545APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12546 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012547 assert(!isValueDependent() &&
12548 "Expression evaluator can't be called on a dependent expression.");
12549
Fangrui Song407659a2018-11-30 23:41:18 +000012550 EvalResult EVResult;
12551 EVResult.Diag = Diag;
12552 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12553 Info.InConstantContext = true;
12554
12555 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012556 (void)Result;
12557 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012558 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012559
Fangrui Song407659a2018-11-30 23:41:18 +000012560 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012561}
12562
Richard Smithe9ff7702013-11-05 22:23:30 +000012563void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012564 assert(!isValueDependent() &&
12565 "Expression evaluator can't be called on a dependent expression.");
12566
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012567 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012568 EvalResult EVResult;
12569 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12570 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12571 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012572 }
12573}
12574
Richard Smithe6c01442013-06-05 00:46:14 +000012575bool Expr::EvalResult::isGlobalLValue() const {
12576 assert(Val.isLValue());
12577 return IsGlobalLValue(Val.getLValueBase());
12578}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012579
12580
John McCall864e3962010-05-07 05:32:02 +000012581/// isIntegerConstantExpr - this recursive routine will test if an expression is
12582/// an integer constant expression.
12583
12584/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12585/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012586
12587// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012588// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12589// and a (possibly null) SourceLocation indicating the location of the problem.
12590//
John McCall864e3962010-05-07 05:32:02 +000012591// Note that to reduce code duplication, this helper does no evaluation
12592// itself; the caller checks whether the expression is evaluatable, and
12593// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012594// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012595
Dan Gohman28ade552010-07-26 21:25:24 +000012596namespace {
12597
Richard Smith9e575da2012-12-28 13:25:52 +000012598enum ICEKind {
12599 /// This expression is an ICE.
12600 IK_ICE,
12601 /// This expression is not an ICE, but if it isn't evaluated, it's
12602 /// a legal subexpression for an ICE. This return value is used to handle
12603 /// the comma operator in C99 mode, and non-constant subexpressions.
12604 IK_ICEIfUnevaluated,
12605 /// This expression is not an ICE, and is not a legal subexpression for one.
12606 IK_NotICE
12607};
12608
John McCall864e3962010-05-07 05:32:02 +000012609struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012610 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012611 SourceLocation Loc;
12612
Richard Smith9e575da2012-12-28 13:25:52 +000012613 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012614};
12615
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012616}
Dan Gohman28ade552010-07-26 21:25:24 +000012617
Richard Smith9e575da2012-12-28 13:25:52 +000012618static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12619
12620static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012621
Craig Toppera31a8822013-08-22 07:09:37 +000012622static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012623 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012624 Expr::EvalStatus Status;
12625 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12626
12627 Info.InConstantContext = true;
12628 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012629 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012630 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012631
John McCall864e3962010-05-07 05:32:02 +000012632 return NoDiag();
12633}
12634
Craig Toppera31a8822013-08-22 07:09:37 +000012635static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012636 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012637 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012638 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012639
12640 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012641#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012642#define STMT(Node, Base) case Expr::Node##Class:
12643#define EXPR(Node, Base)
12644#include "clang/AST/StmtNodes.inc"
12645 case Expr::PredefinedExprClass:
12646 case Expr::FloatingLiteralClass:
12647 case Expr::ImaginaryLiteralClass:
12648 case Expr::StringLiteralClass:
12649 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012650 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012651 case Expr::MemberExprClass:
12652 case Expr::CompoundAssignOperatorClass:
12653 case Expr::CompoundLiteralExprClass:
12654 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012655 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012656 case Expr::ArrayInitLoopExprClass:
12657 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012658 case Expr::NoInitExprClass:
12659 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012660 case Expr::ImplicitValueInitExprClass:
12661 case Expr::ParenListExprClass:
12662 case Expr::VAArgExprClass:
12663 case Expr::AddrLabelExprClass:
12664 case Expr::StmtExprClass:
12665 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012666 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012667 case Expr::CXXDynamicCastExprClass:
12668 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012669 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012670 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012671 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012672 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012673 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012674 case Expr::CXXThisExprClass:
12675 case Expr::CXXThrowExprClass:
12676 case Expr::CXXNewExprClass:
12677 case Expr::CXXDeleteExprClass:
12678 case Expr::CXXPseudoDestructorExprClass:
12679 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012680 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012681 case Expr::DependentScopeDeclRefExprClass:
12682 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012683 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012684 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012685 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012686 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012687 case Expr::CXXTemporaryObjectExprClass:
12688 case Expr::CXXUnresolvedConstructExprClass:
12689 case Expr::CXXDependentScopeMemberExprClass:
12690 case Expr::UnresolvedMemberExprClass:
12691 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012692 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012693 case Expr::ObjCArrayLiteralClass:
12694 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012695 case Expr::ObjCEncodeExprClass:
12696 case Expr::ObjCMessageExprClass:
12697 case Expr::ObjCSelectorExprClass:
12698 case Expr::ObjCProtocolExprClass:
12699 case Expr::ObjCIvarRefExprClass:
12700 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012701 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012702 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012703 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012704 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012705 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012706 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012707 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012708 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012709 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012710 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012711 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012712 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012713 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012714 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012715 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012716 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012717 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012718 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012719 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012720 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012721 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012722 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012723
Richard Smithf137f932014-01-25 20:50:08 +000012724 case Expr::InitListExprClass: {
12725 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12726 // form "T x = { a };" is equivalent to "T x = a;".
12727 // Unless we're initializing a reference, T is a scalar as it is known to be
12728 // of integral or enumeration type.
12729 if (E->isRValue())
12730 if (cast<InitListExpr>(E)->getNumInits() == 1)
12731 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012732 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012733 }
12734
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012735 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012736 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012737 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012738 return NoDiag();
12739
John McCall7c454bb2011-07-15 05:09:51 +000012740 case Expr::SubstNonTypeTemplateParmExprClass:
12741 return
12742 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12743
Bill Wendling7c44da22018-10-31 03:48:47 +000012744 case Expr::ConstantExprClass:
12745 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12746
John McCall864e3962010-05-07 05:32:02 +000012747 case Expr::ParenExprClass:
12748 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012749 case Expr::GenericSelectionExprClass:
12750 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012751 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012752 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012753 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012754 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012755 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012756 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012757 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012758 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012759 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012760 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012761 return NoDiag();
12762 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012763 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012764 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12765 // constant expressions, but they can never be ICEs because an ICE cannot
12766 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012767 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012768 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012769 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012770 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012771 }
Richard Smith6365c912012-02-24 22:12:32 +000012772 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012773 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12774 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012775 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012776 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012777 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012778 // Parameter variables are never constants. Without this check,
12779 // getAnyInitializer() can find a default argument, which leads
12780 // to chaos.
12781 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012782 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012783
12784 // C++ 7.1.5.1p2
12785 // A variable of non-volatile const-qualified integral or enumeration
12786 // type initialized by an ICE can be used in ICEs.
12787 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012788 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012789 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012790
Richard Smithd0b4dd62011-12-19 06:19:21 +000012791 const VarDecl *VD;
12792 // Look for a declaration of this variable that has an initializer, and
12793 // check whether it is an ICE.
12794 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12795 return NoDiag();
12796 else
Richard Smith9e575da2012-12-28 13:25:52 +000012797 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012798 }
12799 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012800 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012801 }
John McCall864e3962010-05-07 05:32:02 +000012802 case Expr::UnaryOperatorClass: {
12803 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12804 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012805 case UO_PostInc:
12806 case UO_PostDec:
12807 case UO_PreInc:
12808 case UO_PreDec:
12809 case UO_AddrOf:
12810 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012811 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012812 // C99 6.6/3 allows increment and decrement within unevaluated
12813 // subexpressions of constant expressions, but they can never be ICEs
12814 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012815 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012816 case UO_Extension:
12817 case UO_LNot:
12818 case UO_Plus:
12819 case UO_Minus:
12820 case UO_Not:
12821 case UO_Real:
12822 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012823 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012824 }
Reid Klecknere540d972018-11-01 17:51:48 +000012825 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012826 }
12827 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012828 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12829 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12830 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12831 // compliance: we should warn earlier for offsetof expressions with
12832 // array subscripts that aren't ICEs, and if the array subscripts
12833 // are ICEs, the value of the offsetof must be an integer constant.
12834 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012835 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012836 case Expr::UnaryExprOrTypeTraitExprClass: {
12837 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12838 if ((Exp->getKind() == UETT_SizeOf) &&
12839 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012840 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012841 return NoDiag();
12842 }
12843 case Expr::BinaryOperatorClass: {
12844 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12845 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012846 case BO_PtrMemD:
12847 case BO_PtrMemI:
12848 case BO_Assign:
12849 case BO_MulAssign:
12850 case BO_DivAssign:
12851 case BO_RemAssign:
12852 case BO_AddAssign:
12853 case BO_SubAssign:
12854 case BO_ShlAssign:
12855 case BO_ShrAssign:
12856 case BO_AndAssign:
12857 case BO_XorAssign:
12858 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012859 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12860 // constant expressions, but they can never be ICEs because an ICE cannot
12861 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012862 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012863
John McCalle3027922010-08-25 11:45:40 +000012864 case BO_Mul:
12865 case BO_Div:
12866 case BO_Rem:
12867 case BO_Add:
12868 case BO_Sub:
12869 case BO_Shl:
12870 case BO_Shr:
12871 case BO_LT:
12872 case BO_GT:
12873 case BO_LE:
12874 case BO_GE:
12875 case BO_EQ:
12876 case BO_NE:
12877 case BO_And:
12878 case BO_Xor:
12879 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012880 case BO_Comma:
12881 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012882 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12883 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012884 if (Exp->getOpcode() == BO_Div ||
12885 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012886 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012887 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012888 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012889 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012890 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012891 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012892 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012893 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012894 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012895 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012896 }
12897 }
12898 }
John McCalle3027922010-08-25 11:45:40 +000012899 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012900 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012901 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12902 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012903 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012904 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012905 } else {
12906 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012907 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012908 }
12909 }
Richard Smith9e575da2012-12-28 13:25:52 +000012910 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012911 }
John McCalle3027922010-08-25 11:45:40 +000012912 case BO_LAnd:
12913 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012914 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12915 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012916 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012917 // Rare case where the RHS has a comma "side-effect"; we need
12918 // to actually check the condition to see whether the side
12919 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012920 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012921 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012922 return RHSResult;
12923 return NoDiag();
12924 }
12925
Richard Smith9e575da2012-12-28 13:25:52 +000012926 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012927 }
12928 }
Reid Klecknere540d972018-11-01 17:51:48 +000012929 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012930 }
12931 case Expr::ImplicitCastExprClass:
12932 case Expr::CStyleCastExprClass:
12933 case Expr::CXXFunctionalCastExprClass:
12934 case Expr::CXXStaticCastExprClass:
12935 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012936 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012937 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012938 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012939 if (isa<ExplicitCastExpr>(E)) {
12940 if (const FloatingLiteral *FL
12941 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12942 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12943 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12944 APSInt IgnoredVal(DestWidth, !DestSigned);
12945 bool Ignored;
12946 // If the value does not fit in the destination type, the behavior is
12947 // undefined, so we are not required to treat it as a constant
12948 // expression.
12949 if (FL->getValue().convertToInteger(IgnoredVal,
12950 llvm::APFloat::rmTowardZero,
12951 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012952 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012953 return NoDiag();
12954 }
12955 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012956 switch (cast<CastExpr>(E)->getCastKind()) {
12957 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012958 case CK_AtomicToNonAtomic:
12959 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012960 case CK_NoOp:
12961 case CK_IntegralToBoolean:
12962 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012963 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012964 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012965 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012966 }
John McCall864e3962010-05-07 05:32:02 +000012967 }
John McCallc07a0c72011-02-17 10:25:35 +000012968 case Expr::BinaryConditionalOperatorClass: {
12969 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12970 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012971 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012972 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012973 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12974 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12975 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012976 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012977 return FalseResult;
12978 }
John McCall864e3962010-05-07 05:32:02 +000012979 case Expr::ConditionalOperatorClass: {
12980 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12981 // If the condition (ignoring parens) is a __builtin_constant_p call,
12982 // then only the true side is actually considered in an integer constant
12983 // expression, and it is fully evaluated. This is an important GNU
12984 // extension. See GCC PR38377 for discussion.
12985 if (const CallExpr *CallCE
12986 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012987 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012988 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012989 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012990 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012991 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012992
Richard Smithf57d8cb2011-12-09 22:58:01 +000012993 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12994 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012995
Richard Smith9e575da2012-12-28 13:25:52 +000012996 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012997 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012998 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012999 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013000 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000013001 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000013002 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000013003 return NoDiag();
13004 // Rare case where the diagnostics depend on which side is evaluated
13005 // Note that if we get here, CondResult is 0, and at least one of
13006 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000013007 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000013008 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000013009 return TrueResult;
13010 }
13011 case Expr::CXXDefaultArgExprClass:
13012 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000013013 case Expr::CXXDefaultInitExprClass:
13014 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013015 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000013016 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013017 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000013018 case Expr::BuiltinBitCastExprClass: {
13019 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13020 return ICEDiag(IK_NotICE, E->getBeginLoc());
13021 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13022 }
John McCall864e3962010-05-07 05:32:02 +000013023 }
13024
David Blaikiee4d798f2012-01-20 21:50:17 +000013025 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000013026}
13027
Richard Smithf57d8cb2011-12-09 22:58:01 +000013028/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000013029static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013030 const Expr *E,
13031 llvm::APSInt *Value,
13032 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000013033 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013034 if (Loc) *Loc = E->getExprLoc();
13035 return false;
13036 }
13037
Richard Smith66e05fe2012-01-18 05:21:49 +000013038 APValue Result;
13039 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000013040 return false;
13041
Richard Smith98710fc2014-11-13 23:03:19 +000013042 if (!Result.isInt()) {
13043 if (Loc) *Loc = E->getExprLoc();
13044 return false;
13045 }
13046
Richard Smith66e05fe2012-01-18 05:21:49 +000013047 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000013048 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013049}
13050
Craig Toppera31a8822013-08-22 07:09:37 +000013051bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13052 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013053 assert(!isValueDependent() &&
13054 "Expression evaluator can't be called on a dependent expression.");
13055
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013056 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000013057 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013058
Richard Smith9e575da2012-12-28 13:25:52 +000013059 ICEDiag D = CheckICE(this, Ctx);
13060 if (D.Kind != IK_ICE) {
13061 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000013062 return false;
13063 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000013064 return true;
13065}
13066
Craig Toppera31a8822013-08-22 07:09:37 +000013067bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013068 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013069 assert(!isValueDependent() &&
13070 "Expression evaluator can't be called on a dependent expression.");
13071
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013072 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000013073 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13074
13075 if (!isIntegerConstantExpr(Ctx, Loc))
13076 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013077
Richard Smith5c40f092015-12-04 03:00:44 +000013078 // The only possible side-effects here are due to UB discovered in the
13079 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13080 // required to treat the expression as an ICE, so we produce the folded
13081 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013082 EvalResult ExprResult;
13083 Expr::EvalStatus Status;
13084 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13085 Info.InConstantContext = true;
13086
13087 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013088 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013089
13090 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013091 return true;
13092}
Richard Smith66e05fe2012-01-18 05:21:49 +000013093
Craig Toppera31a8822013-08-22 07:09:37 +000013094bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013095 assert(!isValueDependent() &&
13096 "Expression evaluator can't be called on a dependent expression.");
13097
Richard Smith9e575da2012-12-28 13:25:52 +000013098 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013099}
13100
Craig Toppera31a8822013-08-22 07:09:37 +000013101bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013102 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013103 assert(!isValueDependent() &&
13104 "Expression evaluator can't be called on a dependent expression.");
13105
Richard Smith66e05fe2012-01-18 05:21:49 +000013106 // We support this checking in C++98 mode in order to diagnose compatibility
13107 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013108 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013109
Richard Smith98a0a492012-02-14 21:38:30 +000013110 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013111 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013112 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013113 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013114 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013115
13116 APValue Scratch;
13117 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13118
13119 if (!Diags.empty()) {
13120 IsConstExpr = false;
13121 if (Loc) *Loc = Diags[0].first;
13122 } else if (!IsConstExpr) {
13123 // FIXME: This shouldn't happen.
13124 if (Loc) *Loc = getExprLoc();
13125 }
13126
13127 return IsConstExpr;
13128}
Richard Smith253c2a32012-01-27 01:14:48 +000013129
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013130bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13131 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013132 ArrayRef<const Expr*> Args,
13133 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013134 assert(!isValueDependent() &&
13135 "Expression evaluator can't be called on a dependent expression.");
13136
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013137 Expr::EvalStatus Status;
13138 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013139 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013140
George Burgess IV177399e2017-01-09 04:12:14 +000013141 LValue ThisVal;
13142 const LValue *ThisPtr = nullptr;
13143 if (This) {
13144#ifndef NDEBUG
13145 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13146 assert(MD && "Don't provide `this` for non-methods.");
13147 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13148#endif
13149 if (EvaluateObjectArgument(Info, This, ThisVal))
13150 ThisPtr = &ThisVal;
13151 if (Info.EvalStatus.HasSideEffects)
13152 return false;
13153 }
13154
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013155 ArgVector ArgValues(Args.size());
13156 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13157 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000013158 if ((*I)->isValueDependent() ||
13159 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013160 // If evaluation fails, throw away the argument entirely.
13161 ArgValues[I - Args.begin()] = APValue();
13162 if (Info.EvalStatus.HasSideEffects)
13163 return false;
13164 }
13165
13166 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000013167 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013168 ArgValues.data());
13169 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13170}
13171
Richard Smith253c2a32012-01-27 01:14:48 +000013172bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013173 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000013174 PartialDiagnosticAt> &Diags) {
13175 // FIXME: It would be useful to check constexpr function templates, but at the
13176 // moment the constant expression evaluator cannot cope with the non-rigorous
13177 // ASTs which we build for dependent expressions.
13178 if (FD->isDependentContext())
13179 return true;
13180
13181 Expr::EvalStatus Status;
13182 Status.Diag = &Diags;
13183
Richard Smith6d4c6582013-11-05 22:18:15 +000013184 EvalInfo Info(FD->getASTContext(), Status,
13185 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000013186 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000013187
13188 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000013189 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000013190
Richard Smith7525ff62013-05-09 07:14:00 +000013191 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000013192 // is a temporary being used as the 'this' pointer.
13193 LValue This;
13194 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000013195 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000013196
Richard Smith253c2a32012-01-27 01:14:48 +000013197 ArrayRef<const Expr*> Args;
13198
Richard Smith2e312c82012-03-03 22:46:17 +000013199 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000013200 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13201 // Evaluate the call as a constant initializer, to allow the construction
13202 // of objects of non-literal types.
13203 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000013204 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13205 } else {
13206 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000013207 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000013208 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000013209 }
Richard Smith253c2a32012-01-27 01:14:48 +000013210
13211 return Diags.empty();
13212}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013213
13214bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13215 const FunctionDecl *FD,
13216 SmallVectorImpl<
13217 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013218 assert(!E->isValueDependent() &&
13219 "Expression evaluator can't be called on a dependent expression.");
13220
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013221 Expr::EvalStatus Status;
13222 Status.Diag = &Diags;
13223
13224 EvalInfo Info(FD->getASTContext(), Status,
13225 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013226 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013227
13228 // Fabricate a call stack frame to give the arguments a plausible cover story.
13229 ArrayRef<const Expr*> Args;
13230 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013231 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013232 (void)Success;
13233 assert(Success &&
13234 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000013235 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013236
13237 APValue ResultScratch;
13238 Evaluate(ResultScratch, Info, E);
13239 return Diags.empty();
13240}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013241
13242bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13243 unsigned Type) const {
13244 if (!getType()->isPointerType())
13245 return false;
13246
13247 Expr::EvalStatus Status;
13248 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000013249 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013250}