blob: 6de55f10dc579bf9a0636556d79e1213addc3c94 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000066 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000068 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 //
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000072 //
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
78 return T;
79 }
80 return D->getType();
81 }
Richard Smith84401042013-06-03 05:03:02 +000082
83 const Expr *Base = B.get<const Expr*>();
84
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93 Adjustments);
94 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000095 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000097 return Inner->getType();
98 }
99
100 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000101 }
102
Richard Smithd62306a2011-11-10 06:34:14 +0000103 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000105 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return Value;
110 }
111
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000116 }
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Determine whether this LValue path entry for a base class names a virtual
123 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000125 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127
George Burgess IVe3763372016-12-22 02:50:20 +0000128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 }
133
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
136 ///
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
140 return nullptr;
141
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
148
George Burgess IVe3763372016-12-22 02:50:20 +0000149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
151
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
154 return nullptr;
155 }
156
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 }
163
Richard Smith6f4f0f12017-10-20 22:56:25 +0000164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
169
George Burgess IVe3763372016-12-22 02:50:20 +0000170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000174 static unsigned
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&
182 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000183 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000184 Type = getType(Base);
185
Richard Smith80815602011-11-07 05:07:52 +0000186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000187 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000191 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000192
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
195 } else {
196 assert(I == 0 && "unexpected unsized array designator");
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
199 }
Richard Smith66c96992012-02-18 22:04:06 +0000200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
203 ArraySize = 2;
204 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000205 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
208 ArraySize = 0;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else {
Richard Smith80815602011-11-07 05:07:52 +0000212 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 }
Richard Smith80815602011-11-07 05:07:52 +0000216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000218 }
219
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000223 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 };
225
Richard Smith96e0c102011-11-04 02:25:55 +0000226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000231 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000232
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Daniel Jasperffdee092017-05-02 19:21:42 +0000236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000238
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000240 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000241
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000244 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000245
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 uint64_t MostDerivedArraySize;
254
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000257
Richard Smith80815602011-11-07 05:07:52 +0000258 typedef APValue::LValuePathEntry PathEntry;
259
Richard Smith96e0c102011-11-04 02:25:55 +0000260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
262
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000266 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000270
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000276 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000280 if (V.getLValueBase()) {
281 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000282 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000283 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000288 }
Richard Smith80815602011-11-07 05:07:52 +0000289 }
290 }
291
Richard Smith96e0c102011-11-04 02:25:55 +0000292 void setInvalid() {
293 Invalid = true;
294 Entries.clear();
295 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000296
George Burgess IVe3763372016-12-22 02:50:20 +0000297 /// Determine whether the most derived subobject is an array without a
298 /// known bound.
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000302 }
303
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308 return MostDerivedArraySize;
309 }
310
Richard Smitha8105bc2012-01-06 16:39:00 +0000311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000313 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000314 if (IsOnePastTheEnd)
315 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318 return true;
319 return false;
320 }
321
322 /// Check that this refers to a valid subobject.
323 bool isValidSubobject() const {
324 if (Invalid)
325 return false;
326 return !isOnePastTheEnd();
327 }
328 /// Check that this refers to a valid subobject, and if not, produce a
329 /// relevant diagnostic and set the designator as invalid.
330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
331
332 /// Update this designator to refer to the first element within this array.
333 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000334 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000336 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000337
338 // This is a most-derived object.
339 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000340 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 MostDerivedArraySize = CAT->getSize().getZExtValue();
342 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000343 }
George Burgess IVe3763372016-12-22 02:50:20 +0000344 /// Update this designator to refer to the first element within the array of
345 /// elements of type T. This is an array of unknown size.
346 void addUnsizedArrayUnchecked(QualType ElemTy) {
347 PathEntry Entry;
348 Entry.ArrayIndex = 0;
349 Entries.push_back(Entry);
350
351 MostDerivedType = ElemTy;
352 MostDerivedIsArrayElement = true;
353 // The value in MostDerivedArraySize is undefined in this case. So, set it
354 // to an arbitrary value that's likely to loudly break things if it's
355 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000356 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000357 MostDerivedPathLength = Entries.size();
358 }
Richard Smith96e0c102011-11-04 02:25:55 +0000359 /// Update this designator to refer to the given base or member of this
360 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000362 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000363 APValue::BaseOrMemberType Value(D, Virtual);
364 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // If this isn't a base class, it's a new most-derived object.
368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
369 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000370 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000371 MostDerivedArraySize = 0;
372 MostDerivedPathLength = Entries.size();
373 }
Richard Smith96e0c102011-11-04 02:25:55 +0000374 }
Richard Smith66c96992012-02-18 22:04:06 +0000375 /// Update this designator to refer to the given complex component.
376 void addComplexUnchecked(QualType EltTy, bool Imag) {
377 PathEntry Entry;
378 Entry.ArrayIndex = Imag;
379 Entries.push_back(Entry);
380
381 // This is technically a most-derived object, though in practice this
382 // is unlikely to matter.
383 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000384 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000385 MostDerivedArraySize = 2;
386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
390 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000391 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
393 if (Invalid || !N) return;
394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
395 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000396 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000397 // Can't verify -- trust that the user is doing the right thing (or if
398 // not, trust that the caller will catch the bad behavior).
399 // FIXME: Should we reject if this overflows, at least?
400 Entries.back().ArrayIndex += TruncatedN;
401 return;
402 }
403
404 // [expr.add]p4: For the purposes of these operators, a pointer to a
405 // nonarray object behaves the same as a pointer to the first element of
406 // an array of length one with the type of the object as its element type.
407 bool IsArray = MostDerivedPathLength == Entries.size() &&
408 MostDerivedIsArrayElement;
409 uint64_t ArrayIndex =
410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
411 uint64_t ArraySize =
412 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
413
414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
415 // Calculate the actual index in a wide enough type, so we can include
416 // it in the note.
417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
418 (llvm::APInt&)N += ArrayIndex;
419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
420 diagnosePointerArithmetic(Info, E, N);
421 setInvalid();
422 return;
423 }
424
425 ArrayIndex += TruncatedN;
426 assert(ArrayIndex <= ArraySize &&
427 "bounds check succeeded for out-of-bounds index");
428
429 if (IsArray)
430 Entries.back().ArrayIndex = ArrayIndex;
431 else
432 IsOnePastTheEnd = (ArrayIndex != 0);
433 }
Richard Smith96e0c102011-11-04 02:25:55 +0000434 };
435
Richard Smith254a73d2011-10-28 22:34:42 +0000436 /// A stack frame in the constexpr call stack.
437 struct CallStackFrame {
438 EvalInfo &Info;
439
440 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000441 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000442
Richard Smithf6f003a2011-12-16 19:06:07 +0000443 /// Callee - The function which was called.
444 const FunctionDecl *Callee;
445
Richard Smithd62306a2011-11-10 06:34:14 +0000446 /// This - The binding for the this pointer in this call, if any.
447 const LValue *This;
448
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000449 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000450 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000451 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000452
Eli Friedman4830ec82012-06-25 21:21:08 +0000453 // Note that we intentionally use std::map here so that references to
454 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000455 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 typedef MapTy::const_iterator temp_iterator;
457 /// Temporaries - Temporary lvalues materialized within this stack frame.
458 MapTy Temporaries;
459
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000460 /// CallLoc - The location of the call expression for this call.
461 SourceLocation CallLoc;
462
463 /// Index - The call index of this call.
464 unsigned Index;
465
Faisal Vali051e3a22017-02-16 04:12:21 +0000466 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
467 // on the overall stack usage of deeply-recursing constexpr evaluataions.
468 // (We should cache this map rather than recomputing it repeatedly.)
469 // But let's try this and see how it goes; we can look into caching the map
470 // as a later change.
471
472 /// LambdaCaptureFields - Mapping from captured variables/this to
473 /// corresponding data members in the closure class.
474 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
475 FieldDecl *LambdaThisCaptureField;
476
Richard Smithf6f003a2011-12-16 19:06:07 +0000477 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
478 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000479 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000480 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000481
482 APValue *getTemporary(const void *Key) {
483 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000484 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000485 }
486 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000487 };
488
Richard Smith852c9db2013-04-20 22:23:05 +0000489 /// Temporarily override 'this'.
490 class ThisOverrideRAII {
491 public:
492 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
493 : Frame(Frame), OldThis(Frame.This) {
494 if (Enable)
495 Frame.This = NewThis;
496 }
497 ~ThisOverrideRAII() {
498 Frame.This = OldThis;
499 }
500 private:
501 CallStackFrame &Frame;
502 const LValue *OldThis;
503 };
504
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 /// A partial diagnostic which we might know in advance that we are not going
506 /// to emit.
507 class OptionalDiagnostic {
508 PartialDiagnostic *Diag;
509
510 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000511 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
512 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000513
514 template<typename T>
515 OptionalDiagnostic &operator<<(const T &v) {
516 if (Diag)
517 *Diag << v;
518 return *this;
519 }
Richard Smithfe800032012-01-31 04:08:20 +0000520
521 OptionalDiagnostic &operator<<(const APSInt &I) {
522 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000523 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000524 I.toString(Buffer);
525 *Diag << StringRef(Buffer.data(), Buffer.size());
526 }
527 return *this;
528 }
529
530 OptionalDiagnostic &operator<<(const APFloat &F) {
531 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000532 // FIXME: Force the precision of the source value down so we don't
533 // print digits which are usually useless (we don't really care here if
534 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000535 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000536 // representation which rounds to the correct value, but it's a bit
537 // tricky to implement.
538 unsigned precision =
539 llvm::APFloat::semanticsPrecision(F.getSemantics());
540 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000541 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000542 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000543 *Diag << StringRef(Buffer.data(), Buffer.size());
544 }
545 return *this;
546 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000547 };
548
Richard Smith08d6a2c2013-07-24 07:11:57 +0000549 /// A cleanup, and a flag indicating whether it is lifetime-extended.
550 class Cleanup {
551 llvm::PointerIntPair<APValue*, 1, bool> Value;
552
553 public:
554 Cleanup(APValue *Val, bool IsLifetimeExtended)
555 : Value(Val, IsLifetimeExtended) {}
556
557 bool isLifetimeExtended() const { return Value.getInt(); }
558 void endLifetime() {
559 *Value.getPointer() = APValue();
560 }
561 };
562
Richard Smithb228a862012-02-15 02:18:13 +0000563 /// EvalInfo - This is a private struct used by the evaluator to capture
564 /// information about a subexpression as it is folded. It retains information
565 /// about the AST context, but also maintains information about the folded
566 /// expression.
567 ///
568 /// If an expression could be evaluated, it is still possible it is not a C
569 /// "integer constant expression" or constant expression. If not, this struct
570 /// captures information about how and why not.
571 ///
572 /// One bit of information passed *into* the request for constant folding
573 /// indicates whether the subexpression is "evaluated" or not according to C
574 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
575 /// evaluate the expression regardless of what the RHS is, but C only allows
576 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000577 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000579
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000580 /// EvalStatus - Contains information about the evaluation.
581 Expr::EvalStatus &EvalStatus;
582
583 /// CurrentCall - The top of the constexpr call stack.
584 CallStackFrame *CurrentCall;
585
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000586 /// CallStackDepth - The number of calls in the call stack right now.
587 unsigned CallStackDepth;
588
Richard Smithb228a862012-02-15 02:18:13 +0000589 /// NextCallIndex - The next call index to assign.
590 unsigned NextCallIndex;
591
Richard Smitha3d3bd22013-05-08 02:12:03 +0000592 /// StepsLeft - The remaining number of evaluation steps we're permitted
593 /// to perform. This is essentially a limit for the number of statements
594 /// we will evaluate.
595 unsigned StepsLeft;
596
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000597 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000598 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000599 CallStackFrame BottomFrame;
600
Richard Smith08d6a2c2013-07-24 07:11:57 +0000601 /// A stack of values whose lifetimes end at the end of some surrounding
602 /// evaluation frame.
603 llvm::SmallVector<Cleanup, 16> CleanupStack;
604
Richard Smithd62306a2011-11-10 06:34:14 +0000605 /// EvaluatingDecl - This is the declaration whose initializer is being
606 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000607 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000608
609 /// EvaluatingDeclValue - This is the value being constructed for the
610 /// declaration whose initializer is being evaluated, if any.
611 APValue *EvaluatingDeclValue;
612
Erik Pilkington42925492017-10-04 00:18:55 +0000613 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
614 /// the call index that that lvalue was allocated in.
615 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
616
617 /// EvaluatingConstructors - Set of objects that are currently being
618 /// constructed.
619 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
620
621 struct EvaluatingConstructorRAII {
622 EvalInfo &EI;
623 EvaluatingObject Object;
624 bool DidInsert;
625 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
626 : EI(EI), Object(Object) {
627 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
628 }
629 ~EvaluatingConstructorRAII() {
630 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
631 }
632 };
633
634 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
635 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
636 }
637
Richard Smith410306b2016-12-12 02:53:20 +0000638 /// The current array initialization index, if we're performing array
639 /// initialization.
640 uint64_t ArrayInitIndex = -1;
641
Richard Smith357362d2011-12-13 06:39:58 +0000642 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
643 /// notes attached to it will also be stored, otherwise they will not be.
644 bool HasActiveDiagnostic;
645
Richard Smith0c6124b2015-12-03 01:36:22 +0000646 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
647 /// fold (not just why it's not strictly a constant expression)?
648 bool HasFoldFailureDiagnostic;
649
George Burgess IV8c892b52016-05-25 22:31:54 +0000650 /// \brief Whether or not we're currently speculatively evaluating.
651 bool IsSpeculativelyEvaluating;
652
Richard Smith6d4c6582013-11-05 22:18:15 +0000653 enum EvaluationMode {
654 /// Evaluate as a constant expression. Stop if we find that the expression
655 /// is not a constant expression.
656 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000657
Richard Smith6d4c6582013-11-05 22:18:15 +0000658 /// Evaluate as a potential constant expression. Keep going if we hit a
659 /// construct that we can't evaluate yet (because we don't yet know the
660 /// value of something) but stop if we hit something that could never be
661 /// a constant expression.
662 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Fold the expression to a constant. Stop if we hit a side-effect that
665 /// we can't model.
666 EM_ConstantFold,
667
668 /// Evaluate the expression looking for integer overflow and similar
669 /// issues. Don't worry about side-effects, and try to visit all
670 /// subexpressions.
671 EM_EvaluateForOverflow,
672
673 /// Evaluate in any way we know how. Don't worry about side-effects that
674 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 EM_IgnoreSideEffects,
676
677 /// Evaluate as a constant expression. Stop if we find that the expression
678 /// is not a constant expression. Some expressions can be retried in the
679 /// optimizer if we don't constant fold them here, but in an unevaluated
680 /// context we try to fold them immediately since the optimizer never
681 /// gets a chance to look at it.
682 EM_ConstantExpressionUnevaluated,
683
684 /// Evaluate as a potential constant expression. Keep going if we hit a
685 /// construct that we can't evaluate yet (because we don't yet know the
686 /// value of something) but stop if we hit something that could never be
687 /// a constant expression. Some expressions can be retried in the
688 /// optimizer if we don't constant fold them here, but in an unevaluated
689 /// context we try to fold them immediately since the optimizer never
690 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000691 EM_PotentialConstantExpressionUnevaluated,
692
George Burgess IVf9013bf2017-02-10 22:52:29 +0000693 /// Evaluate as a constant expression. In certain scenarios, if:
694 /// - we find a MemberExpr with a base that can't be evaluated, or
695 /// - we find a variable initialized with a call to a function that has
696 /// the alloc_size attribute on it
697 /// then we may consider evaluation to have succeeded.
698 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000699 /// In either case, the LValue returned shall have an invalid base; in the
700 /// former, the base will be the invalid MemberExpr, in the latter, the
701 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
702 /// said CallExpr.
703 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 } EvalMode;
705
706 /// Are we checking whether the expression is a potential constant
707 /// expression?
708 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000709 return EvalMode == EM_PotentialConstantExpression ||
710 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 }
712
713 /// Are we checking an expression for overflow?
714 // FIXME: We should check for any kind of undefined or suspicious behavior
715 // in such constructs, not just overflow.
716 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
717
718 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000719 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000720 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000721 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000722 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
723 EvaluatingDecl((const ValueDecl *)nullptr),
724 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000725 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
726 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000727
Richard Smith7525ff62013-05-09 07:14:00 +0000728 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
729 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000730 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000731 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000732 }
733
David Blaikiebbafb8a2012-03-11 07:00:24 +0000734 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000735
Richard Smith357362d2011-12-13 06:39:58 +0000736 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000737 // Don't perform any constexpr calls (other than the call we're checking)
738 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000740 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000741 if (NextCallIndex == 0) {
742 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000743 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000744 return false;
745 }
Richard Smith357362d2011-12-13 06:39:58 +0000746 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
747 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000748 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000749 << getLangOpts().ConstexprCallDepth;
750 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000751 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000752
Richard Smithb228a862012-02-15 02:18:13 +0000753 CallStackFrame *getCallFrame(unsigned CallIndex) {
754 assert(CallIndex && "no call index in getCallFrame");
755 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
756 // be null in this loop.
757 CallStackFrame *Frame = CurrentCall;
758 while (Frame->Index > CallIndex)
759 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000760 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000761 }
762
Richard Smitha3d3bd22013-05-08 02:12:03 +0000763 bool nextStep(const Stmt *S) {
764 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000766 return false;
767 }
768 --StepsLeft;
769 return true;
770 }
771
Richard Smith357362d2011-12-13 06:39:58 +0000772 private:
773 /// Add a diagnostic to the diagnostics list.
774 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
775 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
776 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
777 return EvalStatus.Diag->back().second;
778 }
779
Richard Smithf6f003a2011-12-16 19:06:07 +0000780 /// Add notes containing a call stack to the current point of evaluation.
781 void addCallStack(unsigned Limit);
782
Faisal Valie690b7a2016-07-02 22:34:24 +0000783 private:
784 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
785 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000786
Richard Smith92b1ce02011-12-12 09:28:41 +0000787 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 // If we have a prior diagnostic, it will be noting that the expression
789 // isn't a constant expression. This diagnostic is more important,
790 // unless we require this evaluation to produce a constant expression.
791 //
792 // FIXME: We might want to show both diagnostics to the user in
793 // EM_ConstantFold mode.
794 if (!EvalStatus.Diag->empty()) {
795 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000796 case EM_ConstantFold:
797 case EM_IgnoreSideEffects:
798 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000799 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000800 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000801 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000802 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 case EM_ConstantExpression:
804 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000805 case EM_ConstantExpressionUnevaluated:
806 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000807 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 HasActiveDiagnostic = false;
809 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 }
811 }
812
Richard Smithf6f003a2011-12-16 19:06:07 +0000813 unsigned CallStackNotes = CallStackDepth - 1;
814 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
815 if (Limit)
816 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000817 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000818 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000819
Richard Smith357362d2011-12-13 06:39:58 +0000820 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000821 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000822 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
824 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000826 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000827 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000828 }
Richard Smith357362d2011-12-13 06:39:58 +0000829 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000830 return OptionalDiagnostic();
831 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000832 public:
833 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
834 OptionalDiagnostic
835 FFDiag(SourceLocation Loc,
836 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
837 unsigned ExtraNotes = 0) {
838 return Diag(Loc, DiagId, ExtraNotes, false);
839 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000840
Faisal Valie690b7a2016-07-02 22:34:24 +0000841 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000842 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000843 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000844 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000845 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000846 HasActiveDiagnostic = false;
847 return OptionalDiagnostic();
848 }
849
Richard Smith92b1ce02011-12-12 09:28:41 +0000850 /// Diagnose that the evaluation does not produce a C++11 core constant
851 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000852 ///
853 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
854 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000855 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000856 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000857 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000858 // Don't override a previous diagnostic. Don't bother collecting
859 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000860 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000861 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000862 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000863 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000864 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000865 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000866 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
867 = diag::note_invalid_subexpr_in_const_expr,
868 unsigned ExtraNotes = 0) {
869 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
870 }
Richard Smith357362d2011-12-13 06:39:58 +0000871 /// Add a note to a prior diagnostic.
872 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
873 if (!HasActiveDiagnostic)
874 return OptionalDiagnostic();
875 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000876 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000877
878 /// Add a stack of notes to a prior diagnostic.
879 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
880 if (HasActiveDiagnostic) {
881 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
882 Diags.begin(), Diags.end());
883 }
884 }
Richard Smith253c2a32012-01-27 01:14:48 +0000885
Richard Smith6d4c6582013-11-05 22:18:15 +0000886 /// Should we continue evaluation after encountering a side-effect that we
887 /// couldn't model?
888 bool keepEvaluatingAfterSideEffect() {
889 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000890 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000891 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000892 case EM_EvaluateForOverflow:
893 case EM_IgnoreSideEffects:
894 return true;
895
Richard Smith6d4c6582013-11-05 22:18:15 +0000896 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000897 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000898 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000899 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000900 return false;
901 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000902 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 }
904
905 /// Note that we have had a side-effect, and determine whether we should
906 /// keep evaluating.
907 bool noteSideEffect() {
908 EvalStatus.HasSideEffects = true;
909 return keepEvaluatingAfterSideEffect();
910 }
911
Richard Smithce8eca52015-12-08 03:21:47 +0000912 /// Should we continue evaluation after encountering undefined behavior?
913 bool keepEvaluatingAfterUndefinedBehavior() {
914 switch (EvalMode) {
915 case EM_EvaluateForOverflow:
916 case EM_IgnoreSideEffects:
917 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000918 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000919 return true;
920
921 case EM_PotentialConstantExpression:
922 case EM_PotentialConstantExpressionUnevaluated:
923 case EM_ConstantExpression:
924 case EM_ConstantExpressionUnevaluated:
925 return false;
926 }
927 llvm_unreachable("Missed EvalMode case");
928 }
929
930 /// Note that we hit something that was technically undefined behavior, but
931 /// that we can evaluate past it (such as signed overflow or floating-point
932 /// division by zero.)
933 bool noteUndefinedBehavior() {
934 EvalStatus.HasUndefinedBehavior = true;
935 return keepEvaluatingAfterUndefinedBehavior();
936 }
937
Richard Smith253c2a32012-01-27 01:14:48 +0000938 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000940 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 if (!StepsLeft)
942 return false;
943
944 switch (EvalMode) {
945 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000946 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000947 case EM_EvaluateForOverflow:
948 return true;
949
950 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000951 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000952 case EM_ConstantFold:
953 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000954 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000955 return false;
956 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000957 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000958 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000959
George Burgess IV8c892b52016-05-25 22:31:54 +0000960 /// Notes that we failed to evaluate an expression that other expressions
961 /// directly depend on, and determine if we should keep evaluating. This
962 /// should only be called if we actually intend to keep evaluating.
963 ///
964 /// Call noteSideEffect() instead if we may be able to ignore the value that
965 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
966 ///
967 /// (Foo(), 1) // use noteSideEffect
968 /// (Foo() || true) // use noteSideEffect
969 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000970 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000971 // Failure when evaluating some expression often means there is some
972 // subexpression whose evaluation was skipped. Therefore, (because we
973 // don't track whether we skipped an expression when unwinding after an
974 // evaluation failure) every evaluation failure that bubbles up from a
975 // subexpression implies that a side-effect has potentially happened. We
976 // skip setting the HasSideEffects flag to true until we decide to
977 // continue evaluating after that point, which happens here.
978 bool KeepGoing = keepEvaluatingAfterFailure();
979 EvalStatus.HasSideEffects |= KeepGoing;
980 return KeepGoing;
981 }
982
Richard Smith410306b2016-12-12 02:53:20 +0000983 class ArrayInitLoopIndex {
984 EvalInfo &Info;
985 uint64_t OuterIndex;
986
987 public:
988 ArrayInitLoopIndex(EvalInfo &Info)
989 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
990 Info.ArrayInitIndex = 0;
991 }
992 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
993
994 operator uint64_t&() { return Info.ArrayInitIndex; }
995 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000996 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000997
998 /// Object used to treat all foldable expressions as constant expressions.
999 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001000 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001001 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001002 bool HadNoPriorDiags;
1003 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004
Richard Smith6d4c6582013-11-05 22:18:15 +00001005 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1006 : Info(Info),
1007 Enabled(Enabled),
1008 HadNoPriorDiags(Info.EvalStatus.Diag &&
1009 Info.EvalStatus.Diag->empty() &&
1010 !Info.EvalStatus.HasSideEffects),
1011 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001012 if (Enabled &&
1013 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1014 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001015 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001016 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001017 void keepDiagnostics() { Enabled = false; }
1018 ~FoldConstant() {
1019 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001020 !Info.EvalStatus.HasSideEffects)
1021 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001023 }
1024 };
Richard Smith17100ba2012-02-16 02:46:34 +00001025
George Burgess IV3a03fab2015-09-04 21:28:13 +00001026 /// RAII object used to treat the current evaluation as the correct pointer
1027 /// offset fold for the current EvalMode
1028 struct FoldOffsetRAII {
1029 EvalInfo &Info;
1030 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001031 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001032 : Info(Info), OldMode(Info.EvalMode) {
1033 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001034 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001035 }
1036
1037 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1038 };
1039
George Burgess IV8c892b52016-05-25 22:31:54 +00001040 /// RAII object used to optionally suppress diagnostics and side-effects from
1041 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001042 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001043 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001044 Expr::EvalStatus OldStatus;
1045 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001046
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001048 Info = Other.Info;
1049 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001050 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001051 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001052 }
1053
1054 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001055 if (!Info)
1056 return;
1057
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001058 Info->EvalStatus = OldStatus;
1059 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001060 }
1061
Richard Smith17100ba2012-02-16 02:46:34 +00001062 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001063 SpeculativeEvaluationRAII() = default;
1064
1065 SpeculativeEvaluationRAII(
1066 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001067 : Info(&Info), OldStatus(Info.EvalStatus),
1068 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001069 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001070 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001071 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001072
1073 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1074 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1075 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001076 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001077
1078 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1079 maybeRestoreState();
1080 moveFromAndCancel(std::move(Other));
1081 return *this;
1082 }
1083
1084 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001085 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001086
1087 /// RAII object wrapping a full-expression or block scope, and handling
1088 /// the ending of the lifetime of temporaries created within it.
1089 template<bool IsFullExpression>
1090 class ScopeRAII {
1091 EvalInfo &Info;
1092 unsigned OldStackSize;
1093 public:
1094 ScopeRAII(EvalInfo &Info)
1095 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1096 ~ScopeRAII() {
1097 // Body moved to a static method to encourage the compiler to inline away
1098 // instances of this class.
1099 cleanup(Info, OldStackSize);
1100 }
1101 private:
1102 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1103 unsigned NewEnd = OldStackSize;
1104 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1105 I != N; ++I) {
1106 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1107 // Full-expression cleanup of a lifetime-extended temporary: nothing
1108 // to do, just move this cleanup to the right place in the stack.
1109 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1110 ++NewEnd;
1111 } else {
1112 // End the lifetime of the object.
1113 Info.CleanupStack[I].endLifetime();
1114 }
1115 }
1116 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1117 Info.CleanupStack.end());
1118 }
1119 };
1120 typedef ScopeRAII<false> BlockScopeRAII;
1121 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001122}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001123
Richard Smitha8105bc2012-01-06 16:39:00 +00001124bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1125 CheckSubobjectKind CSK) {
1126 if (Invalid)
1127 return false;
1128 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001129 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001130 << CSK;
1131 setInvalid();
1132 return false;
1133 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001134 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1135 // must actually be at least one array element; even a VLA cannot have a
1136 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001137 return true;
1138}
1139
Richard Smith6f4f0f12017-10-20 22:56:25 +00001140void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1141 const Expr *E) {
1142 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1143 // Do not set the designator as invalid: we can represent this situation,
1144 // and correct handling of __builtin_object_size requires us to do so.
1145}
1146
Richard Smitha8105bc2012-01-06 16:39:00 +00001147void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001148 const Expr *E,
1149 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001150 // If we're complaining, we must be able to statically determine the size of
1151 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001152 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001153 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001154 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001155 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001156 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001157 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001158 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001159 setInvalid();
1160}
1161
Richard Smithf6f003a2011-12-16 19:06:07 +00001162CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1163 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001164 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001165 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1166 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001167 Info.CurrentCall = this;
1168 ++Info.CallStackDepth;
1169}
1170
1171CallStackFrame::~CallStackFrame() {
1172 assert(Info.CurrentCall == this && "calls retired out of order");
1173 --Info.CallStackDepth;
1174 Info.CurrentCall = Caller;
1175}
1176
Richard Smith08d6a2c2013-07-24 07:11:57 +00001177APValue &CallStackFrame::createTemporary(const void *Key,
1178 bool IsLifetimeExtended) {
1179 APValue &Result = Temporaries[Key];
1180 assert(Result.isUninit() && "temporary created multiple times");
1181 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1182 return Result;
1183}
1184
Richard Smith84401042013-06-03 05:03:02 +00001185static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001186
1187void EvalInfo::addCallStack(unsigned Limit) {
1188 // Determine which calls to skip, if any.
1189 unsigned ActiveCalls = CallStackDepth - 1;
1190 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1191 if (Limit && Limit < ActiveCalls) {
1192 SkipStart = Limit / 2 + Limit % 2;
1193 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001194 }
1195
Richard Smithf6f003a2011-12-16 19:06:07 +00001196 // Walk the call stack and add the diagnostics.
1197 unsigned CallIdx = 0;
1198 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1199 Frame = Frame->Caller, ++CallIdx) {
1200 // Skip this call?
1201 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1202 if (CallIdx == SkipStart) {
1203 // Note that we're skipping calls.
1204 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1205 << unsigned(ActiveCalls - Limit);
1206 }
1207 continue;
1208 }
1209
Richard Smith5179eb72016-06-28 19:03:57 +00001210 // Use a different note for an inheriting constructor, because from the
1211 // user's perspective it's not really a function at all.
1212 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1213 if (CD->isInheritingConstructor()) {
1214 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1215 << CD->getParent();
1216 continue;
1217 }
1218 }
1219
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001220 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001221 llvm::raw_svector_ostream Out(Buffer);
1222 describeCall(Frame, Out);
1223 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1224 }
1225}
1226
1227namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001228 struct ComplexValue {
1229 private:
1230 bool IsInt;
1231
1232 public:
1233 APSInt IntReal, IntImag;
1234 APFloat FloatReal, FloatImag;
1235
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001236 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001237
1238 void makeComplexFloat() { IsInt = false; }
1239 bool isComplexFloat() const { return !IsInt; }
1240 APFloat &getComplexFloatReal() { return FloatReal; }
1241 APFloat &getComplexFloatImag() { return FloatImag; }
1242
1243 void makeComplexInt() { IsInt = true; }
1244 bool isComplexInt() const { return IsInt; }
1245 APSInt &getComplexIntReal() { return IntReal; }
1246 APSInt &getComplexIntImag() { return IntImag; }
1247
Richard Smith2e312c82012-03-03 22:46:17 +00001248 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001249 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001250 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001251 else
Richard Smith2e312c82012-03-03 22:46:17 +00001252 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001253 }
Richard Smith2e312c82012-03-03 22:46:17 +00001254 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001255 assert(v.isComplexFloat() || v.isComplexInt());
1256 if (v.isComplexFloat()) {
1257 makeComplexFloat();
1258 FloatReal = v.getComplexFloatReal();
1259 FloatImag = v.getComplexFloatImag();
1260 } else {
1261 makeComplexInt();
1262 IntReal = v.getComplexIntReal();
1263 IntImag = v.getComplexIntImag();
1264 }
1265 }
John McCall93d91dc2010-05-07 17:22:02 +00001266 };
John McCall45d55e42010-05-07 21:00:08 +00001267
1268 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001269 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001270 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001271 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001272 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001273 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001275
Richard Smithce40ad62011-11-12 22:28:03 +00001276 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001277 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001278 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001279 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001280 SubobjectDesignator &getLValueDesignator() { return Designator; }
1281 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001282 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001283
Richard Smith2e312c82012-03-03 22:46:17 +00001284 void moveInto(APValue &V) const {
1285 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001286 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1287 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001288 else {
1289 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001290 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001291 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001292 }
John McCall45d55e42010-05-07 21:00:08 +00001293 }
Richard Smith2e312c82012-03-03 22:46:17 +00001294 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001295 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001296 Base = V.getLValueBase();
1297 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001298 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001299 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001300 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001301 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001302 }
1303
Tim Northover01503332017-05-26 02:16:00 +00001304 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001305#ifndef NDEBUG
1306 // We only allow a few types of invalid bases. Enforce that here.
1307 if (BInvalid) {
1308 const auto *E = B.get<const Expr *>();
1309 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1310 "Unexpected type of invalid base");
1311 }
1312#endif
1313
Richard Smithce40ad62011-11-12 22:28:03 +00001314 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001315 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001316 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001317 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001318 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001319 IsNullPtr = false;
1320 }
1321
1322 void setNull(QualType PointerTy, uint64_t TargetVal) {
1323 Base = (Expr *)nullptr;
1324 Offset = CharUnits::fromQuantity(TargetVal);
1325 InvalidBase = false;
1326 CallIndex = 0;
1327 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1328 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001329 }
1330
George Burgess IV3a03fab2015-09-04 21:28:13 +00001331 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1332 set(B, I, true);
1333 }
1334
Richard Smitha8105bc2012-01-06 16:39:00 +00001335 // Check that this LValue is not based on a null pointer. If it is, produce
1336 // a diagnostic and mark the designator as invalid.
1337 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1338 CheckSubobjectKind CSK) {
1339 if (Designator.Invalid)
1340 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001341 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001342 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 << CSK;
1344 Designator.setInvalid();
1345 return false;
1346 }
1347 return true;
1348 }
1349
1350 // Check this LValue refers to an object. If not, set the designator to be
1351 // invalid and emit a diagnostic.
1352 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001353 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001354 Designator.checkSubobject(Info, E, CSK);
1355 }
1356
1357 void addDecl(EvalInfo &Info, const Expr *E,
1358 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001359 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1360 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001361 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001362 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1363 if (!Designator.Entries.empty()) {
1364 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1365 Designator.setInvalid();
1366 return;
1367 }
Richard Smithefdb5032017-11-15 03:03:56 +00001368 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1369 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1370 Designator.FirstEntryIsAnUnsizedArray = true;
1371 Designator.addUnsizedArrayUnchecked(ElemTy);
1372 }
George Burgess IVe3763372016-12-22 02:50:20 +00001373 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001374 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001375 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1376 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001377 }
Richard Smith66c96992012-02-18 22:04:06 +00001378 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001379 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1380 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001381 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001382 void clearIsNullPointer() {
1383 IsNullPtr = false;
1384 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001385 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1386 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001387 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1388 // but we're not required to diagnose it and it's valid in C++.)
1389 if (!Index)
1390 return;
1391
1392 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1393 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1394 // offsets.
1395 uint64_t Offset64 = Offset.getQuantity();
1396 uint64_t ElemSize64 = ElementSize.getQuantity();
1397 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1398 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1399
1400 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001401 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001402 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001403 }
1404 void adjustOffset(CharUnits N) {
1405 Offset += N;
1406 if (N.getQuantity())
1407 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001408 }
John McCall45d55e42010-05-07 21:00:08 +00001409 };
Richard Smith027bf112011-11-17 22:56:20 +00001410
1411 struct MemberPtr {
1412 MemberPtr() {}
1413 explicit MemberPtr(const ValueDecl *Decl) :
1414 DeclAndIsDerivedMember(Decl, false), Path() {}
1415
1416 /// The member or (direct or indirect) field referred to by this member
1417 /// pointer, or 0 if this is a null member pointer.
1418 const ValueDecl *getDecl() const {
1419 return DeclAndIsDerivedMember.getPointer();
1420 }
1421 /// Is this actually a member of some type derived from the relevant class?
1422 bool isDerivedMember() const {
1423 return DeclAndIsDerivedMember.getInt();
1424 }
1425 /// Get the class which the declaration actually lives in.
1426 const CXXRecordDecl *getContainingRecord() const {
1427 return cast<CXXRecordDecl>(
1428 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1429 }
1430
Richard Smith2e312c82012-03-03 22:46:17 +00001431 void moveInto(APValue &V) const {
1432 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001433 }
Richard Smith2e312c82012-03-03 22:46:17 +00001434 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001435 assert(V.isMemberPointer());
1436 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1437 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1438 Path.clear();
1439 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1440 Path.insert(Path.end(), P.begin(), P.end());
1441 }
1442
1443 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1444 /// whether the member is a member of some class derived from the class type
1445 /// of the member pointer.
1446 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1447 /// Path - The path of base/derived classes from the member declaration's
1448 /// class (exclusive) to the class type of the member pointer (inclusive).
1449 SmallVector<const CXXRecordDecl*, 4> Path;
1450
1451 /// Perform a cast towards the class of the Decl (either up or down the
1452 /// hierarchy).
1453 bool castBack(const CXXRecordDecl *Class) {
1454 assert(!Path.empty());
1455 const CXXRecordDecl *Expected;
1456 if (Path.size() >= 2)
1457 Expected = Path[Path.size() - 2];
1458 else
1459 Expected = getContainingRecord();
1460 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1461 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1462 // if B does not contain the original member and is not a base or
1463 // derived class of the class containing the original member, the result
1464 // of the cast is undefined.
1465 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1466 // (D::*). We consider that to be a language defect.
1467 return false;
1468 }
1469 Path.pop_back();
1470 return true;
1471 }
1472 /// Perform a base-to-derived member pointer cast.
1473 bool castToDerived(const CXXRecordDecl *Derived) {
1474 if (!getDecl())
1475 return true;
1476 if (!isDerivedMember()) {
1477 Path.push_back(Derived);
1478 return true;
1479 }
1480 if (!castBack(Derived))
1481 return false;
1482 if (Path.empty())
1483 DeclAndIsDerivedMember.setInt(false);
1484 return true;
1485 }
1486 /// Perform a derived-to-base member pointer cast.
1487 bool castToBase(const CXXRecordDecl *Base) {
1488 if (!getDecl())
1489 return true;
1490 if (Path.empty())
1491 DeclAndIsDerivedMember.setInt(true);
1492 if (isDerivedMember()) {
1493 Path.push_back(Base);
1494 return true;
1495 }
1496 return castBack(Base);
1497 }
1498 };
Richard Smith357362d2011-12-13 06:39:58 +00001499
Richard Smith7bb00672012-02-01 01:42:44 +00001500 /// Compare two member pointers, which are assumed to be of the same type.
1501 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1502 if (!LHS.getDecl() || !RHS.getDecl())
1503 return !LHS.getDecl() && !RHS.getDecl();
1504 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1505 return false;
1506 return LHS.Path == RHS.Path;
1507 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001508}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001509
Richard Smith2e312c82012-03-03 22:46:17 +00001510static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001511static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1512 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001513 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001514static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1515 bool InvalidBaseOK = false);
1516static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1517 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001518static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1519 EvalInfo &Info);
1520static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001521static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001522static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001523 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001524static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001525static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001526static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1527 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001528static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001529
1530//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001531// Misc utilities
1532//===----------------------------------------------------------------------===//
1533
Richard Smithd6cc1982017-01-31 02:23:02 +00001534/// Negate an APSInt in place, converting it to a signed form if necessary, and
1535/// preserving its value (by extending by up to one bit as needed).
1536static void negateAsSigned(APSInt &Int) {
1537 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1538 Int = Int.extend(Int.getBitWidth() + 1);
1539 Int.setIsSigned(true);
1540 }
1541 Int = -Int;
1542}
1543
Richard Smith84401042013-06-03 05:03:02 +00001544/// Produce a string describing the given constexpr call.
1545static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1546 unsigned ArgIndex = 0;
1547 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1548 !isa<CXXConstructorDecl>(Frame->Callee) &&
1549 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1550
1551 if (!IsMemberCall)
1552 Out << *Frame->Callee << '(';
1553
1554 if (Frame->This && IsMemberCall) {
1555 APValue Val;
1556 Frame->This->moveInto(Val);
1557 Val.printPretty(Out, Frame->Info.Ctx,
1558 Frame->This->Designator.MostDerivedType);
1559 // FIXME: Add parens around Val if needed.
1560 Out << "->" << *Frame->Callee << '(';
1561 IsMemberCall = false;
1562 }
1563
1564 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1565 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1566 if (ArgIndex > (unsigned)IsMemberCall)
1567 Out << ", ";
1568
1569 const ParmVarDecl *Param = *I;
1570 const APValue &Arg = Frame->Arguments[ArgIndex];
1571 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1572
1573 if (ArgIndex == 0 && IsMemberCall)
1574 Out << "->" << *Frame->Callee << '(';
1575 }
1576
1577 Out << ')';
1578}
1579
Richard Smithd9f663b2013-04-22 15:31:51 +00001580/// Evaluate an expression to see if it had side-effects, and discard its
1581/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001582/// \return \c true if the caller should keep evaluating.
1583static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001584 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001585 if (!Evaluate(Scratch, Info, E))
1586 // We don't need the value, but we might have skipped a side effect here.
1587 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001588 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001589}
1590
Richard Smithd62306a2011-11-10 06:34:14 +00001591/// Should this call expression be treated as a string literal?
1592static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001593 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001594 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1595 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1596}
1597
Richard Smithce40ad62011-11-12 22:28:03 +00001598static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001599 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1600 // constant expression of pointer type that evaluates to...
1601
1602 // ... a null pointer value, or a prvalue core constant expression of type
1603 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001604 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001605
Richard Smithce40ad62011-11-12 22:28:03 +00001606 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1607 // ... the address of an object with static storage duration,
1608 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1609 return VD->hasGlobalStorage();
1610 // ... the address of a function,
1611 return isa<FunctionDecl>(D);
1612 }
1613
1614 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001615 switch (E->getStmtClass()) {
1616 default:
1617 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001618 case Expr::CompoundLiteralExprClass: {
1619 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1620 return CLE->isFileScope() && CLE->isLValue();
1621 }
Richard Smithe6c01442013-06-05 00:46:14 +00001622 case Expr::MaterializeTemporaryExprClass:
1623 // A materialized temporary might have been lifetime-extended to static
1624 // storage duration.
1625 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001626 // A string literal has static storage duration.
1627 case Expr::StringLiteralClass:
1628 case Expr::PredefinedExprClass:
1629 case Expr::ObjCStringLiteralClass:
1630 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001631 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001632 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001633 return true;
1634 case Expr::CallExprClass:
1635 return IsStringLiteralCall(cast<CallExpr>(E));
1636 // For GCC compatibility, &&label has static storage duration.
1637 case Expr::AddrLabelExprClass:
1638 return true;
1639 // A Block literal expression may be used as the initialization value for
1640 // Block variables at global or local static scope.
1641 case Expr::BlockExprClass:
1642 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001643 case Expr::ImplicitValueInitExprClass:
1644 // FIXME:
1645 // We can never form an lvalue with an implicit value initialization as its
1646 // base through expression evaluation, so these only appear in one case: the
1647 // implicit variable declaration we invent when checking whether a constexpr
1648 // constructor can produce a constant expression. We must assume that such
1649 // an expression might be a global lvalue.
1650 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001651 }
John McCall95007602010-05-10 23:27:23 +00001652}
1653
Richard Smithb228a862012-02-15 02:18:13 +00001654static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1655 assert(Base && "no location for a null lvalue");
1656 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1657 if (VD)
1658 Info.Note(VD->getLocation(), diag::note_declared_at);
1659 else
Ted Kremenek28831752012-08-23 20:46:57 +00001660 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001661 diag::note_constexpr_temporary_here);
1662}
1663
Richard Smith80815602011-11-07 05:07:52 +00001664/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001665/// value for an address or reference constant expression. Return true if we
1666/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001667static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1668 QualType Type, const LValue &LVal) {
1669 bool IsReferenceType = Type->isReferenceType();
1670
Richard Smith357362d2011-12-13 06:39:58 +00001671 APValue::LValueBase Base = LVal.getLValueBase();
1672 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1673
Richard Smith0dea49e2012-02-18 04:58:18 +00001674 // Check that the object is a global. Note that the fake 'this' object we
1675 // manufacture when checking potential constant expressions is conservatively
1676 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001677 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001678 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001679 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001680 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001681 << IsReferenceType << !Designator.Entries.empty()
1682 << !!VD << VD;
1683 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001684 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001685 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001686 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001687 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001688 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001689 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001690 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001691 LVal.getLValueCallIndex() == 0) &&
1692 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001693
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001694 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1695 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001696 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001697 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001698 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001699
Hans Wennborg82dd8772014-06-25 22:19:48 +00001700 // A dllimport variable never acts like a constant.
1701 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001702 return false;
1703 }
1704 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1705 // __declspec(dllimport) must be handled very carefully:
1706 // We must never initialize an expression with the thunk in C++.
1707 // Doing otherwise would allow the same id-expression to yield
1708 // different addresses for the same function in different translation
1709 // units. However, this means that we must dynamically initialize the
1710 // expression with the contents of the import address table at runtime.
1711 //
1712 // The C language has no notion of ODR; furthermore, it has no notion of
1713 // dynamic initialization. This means that we are permitted to
1714 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001715 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001716 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001717 }
1718 }
1719
Richard Smitha8105bc2012-01-06 16:39:00 +00001720 // Allow address constant expressions to be past-the-end pointers. This is
1721 // an extension: the standard requires them to point to an object.
1722 if (!IsReferenceType)
1723 return true;
1724
1725 // A reference constant expression must refer to an object.
1726 if (!Base) {
1727 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001728 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001729 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001730 }
1731
Richard Smith357362d2011-12-13 06:39:58 +00001732 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001733 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001734 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001735 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001736 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001737 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001738 }
1739
Richard Smith80815602011-11-07 05:07:52 +00001740 return true;
1741}
1742
Reid Klecknercd016d82017-07-07 22:04:29 +00001743/// Member pointers are constant expressions unless they point to a
1744/// non-virtual dllimport member function.
1745static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1746 SourceLocation Loc,
1747 QualType Type,
1748 const APValue &Value) {
1749 const ValueDecl *Member = Value.getMemberPointerDecl();
1750 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1751 if (!FD)
1752 return true;
1753 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1754}
1755
Richard Smithfddd3842011-12-30 21:15:51 +00001756/// Check that this core constant expression is of literal type, and if not,
1757/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001758static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001759 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001760 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001761 return true;
1762
Richard Smith7525ff62013-05-09 07:14:00 +00001763 // C++1y: A constant initializer for an object o [...] may also invoke
1764 // constexpr constructors for o and its subobjects even if those objects
1765 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001766 //
1767 // C++11 missed this detail for aggregates, so classes like this:
1768 // struct foo_t { union { int i; volatile int j; } u; };
1769 // are not (obviously) initializable like so:
1770 // __attribute__((__require_constant_initialization__))
1771 // static const foo_t x = {{0}};
1772 // because "i" is a subobject with non-literal initialization (due to the
1773 // volatile member of the union). See:
1774 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1775 // Therefore, we use the C++1y behavior.
1776 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001777 return true;
1778
Richard Smithfddd3842011-12-30 21:15:51 +00001779 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001780 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001781 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001782 << E->getType();
1783 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001784 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001785 return false;
1786}
1787
Richard Smith0b0a0b62011-10-29 20:57:55 +00001788/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001789/// constant expression. If not, report an appropriate diagnostic. Does not
1790/// check that the expression is of literal type.
1791static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1792 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001793 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001794 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001795 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001796 return false;
1797 }
1798
Richard Smith77be48a2014-07-31 06:31:19 +00001799 // We allow _Atomic(T) to be initialized from anything that T can be
1800 // initialized from.
1801 if (const AtomicType *AT = Type->getAs<AtomicType>())
1802 Type = AT->getValueType();
1803
Richard Smithb228a862012-02-15 02:18:13 +00001804 // Core issue 1454: For a literal constant expression of array or class type,
1805 // each subobject of its value shall have been initialized by a constant
1806 // expression.
1807 if (Value.isArray()) {
1808 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1809 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1810 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1811 Value.getArrayInitializedElt(I)))
1812 return false;
1813 }
1814 if (!Value.hasArrayFiller())
1815 return true;
1816 return CheckConstantExpression(Info, DiagLoc, EltTy,
1817 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001818 }
Richard Smithb228a862012-02-15 02:18:13 +00001819 if (Value.isUnion() && Value.getUnionField()) {
1820 return CheckConstantExpression(Info, DiagLoc,
1821 Value.getUnionField()->getType(),
1822 Value.getUnionValue());
1823 }
1824 if (Value.isStruct()) {
1825 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1826 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1827 unsigned BaseIndex = 0;
1828 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1829 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1830 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1831 Value.getStructBase(BaseIndex)))
1832 return false;
1833 }
1834 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001835 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001836 if (I->isUnnamedBitfield())
1837 continue;
1838
David Blaikie2d7c57e2012-04-30 02:36:29 +00001839 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1840 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001841 return false;
1842 }
1843 }
1844
1845 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001846 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001847 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001848 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1849 }
1850
Reid Klecknercd016d82017-07-07 22:04:29 +00001851 if (Value.isMemberPointer())
1852 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1853
Richard Smithb228a862012-02-15 02:18:13 +00001854 // Everything else is fine.
1855 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001856}
1857
Benjamin Kramer8407df72015-03-09 16:47:52 +00001858static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001859 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001860}
1861
1862static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001863 if (Value.CallIndex)
1864 return false;
1865 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1866 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001867}
1868
Richard Smithcecf1842011-11-01 21:06:14 +00001869static bool IsWeakLValue(const LValue &Value) {
1870 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001871 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001872}
1873
David Majnemerb5116032014-12-09 23:32:34 +00001874static bool isZeroSized(const LValue &Value) {
1875 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001876 if (Decl && isa<VarDecl>(Decl)) {
1877 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001878 if (Ty->isArrayType())
1879 return Ty->isIncompleteType() ||
1880 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001881 }
1882 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001883}
1884
Richard Smith2e312c82012-03-03 22:46:17 +00001885static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001886 // A null base expression indicates a null pointer. These are always
1887 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001888 if (!Value.getLValueBase()) {
1889 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001890 return true;
1891 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001892
Richard Smith027bf112011-11-17 22:56:20 +00001893 // We have a non-null base. These are generally known to be true, but if it's
1894 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001895 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001896 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001897 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001898}
1899
Richard Smith2e312c82012-03-03 22:46:17 +00001900static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001901 switch (Val.getKind()) {
1902 case APValue::Uninitialized:
1903 return false;
1904 case APValue::Int:
1905 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001906 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001907 case APValue::Float:
1908 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001909 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001910 case APValue::ComplexInt:
1911 Result = Val.getComplexIntReal().getBoolValue() ||
1912 Val.getComplexIntImag().getBoolValue();
1913 return true;
1914 case APValue::ComplexFloat:
1915 Result = !Val.getComplexFloatReal().isZero() ||
1916 !Val.getComplexFloatImag().isZero();
1917 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001918 case APValue::LValue:
1919 return EvalPointerValueAsBool(Val, Result);
1920 case APValue::MemberPointer:
1921 Result = Val.getMemberPointerDecl();
1922 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001923 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001924 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001925 case APValue::Struct:
1926 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001927 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001928 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001929 }
1930
Richard Smith11562c52011-10-28 17:51:58 +00001931 llvm_unreachable("unknown APValue kind");
1932}
1933
1934static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1935 EvalInfo &Info) {
1936 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001937 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001938 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001939 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001940 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001941}
1942
Richard Smith357362d2011-12-13 06:39:58 +00001943template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001944static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001945 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001946 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001947 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001948 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001949}
1950
1951static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1952 QualType SrcType, const APFloat &Value,
1953 QualType DestType, APSInt &Result) {
1954 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001955 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001956 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001957
Richard Smith357362d2011-12-13 06:39:58 +00001958 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001959 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001960 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1961 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001962 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001963 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001964}
1965
Richard Smith357362d2011-12-13 06:39:58 +00001966static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1967 QualType SrcType, QualType DestType,
1968 APFloat &Result) {
1969 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001970 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001971 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1972 APFloat::rmNearestTiesToEven, &ignored)
1973 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001974 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001975 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001976}
1977
Richard Smith911e1422012-01-30 22:27:01 +00001978static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1979 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001980 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001981 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001982 APSInt Result = Value;
1983 // Figure out if this is a truncate, extend or noop cast.
1984 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001985 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001986 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001987 return Result;
1988}
1989
Richard Smith357362d2011-12-13 06:39:58 +00001990static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1991 QualType SrcType, const APSInt &Value,
1992 QualType DestType, APFloat &Result) {
1993 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1994 if (Result.convertFromAPInt(Value, Value.isSigned(),
1995 APFloat::rmNearestTiesToEven)
1996 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001997 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001998 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001999}
2000
Richard Smith49ca8aa2013-08-06 07:09:20 +00002001static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2002 APValue &Value, const FieldDecl *FD) {
2003 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2004
2005 if (!Value.isInt()) {
2006 // Trying to store a pointer-cast-to-integer into a bitfield.
2007 // FIXME: In this case, we should provide the diagnostic for casting
2008 // a pointer to an integer.
2009 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002010 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002011 return false;
2012 }
2013
2014 APSInt &Int = Value.getInt();
2015 unsigned OldBitWidth = Int.getBitWidth();
2016 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2017 if (NewBitWidth < OldBitWidth)
2018 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2019 return true;
2020}
2021
Eli Friedman803acb32011-12-22 03:51:45 +00002022static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2023 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002024 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002025 if (!Evaluate(SVal, Info, E))
2026 return false;
2027 if (SVal.isInt()) {
2028 Res = SVal.getInt();
2029 return true;
2030 }
2031 if (SVal.isFloat()) {
2032 Res = SVal.getFloat().bitcastToAPInt();
2033 return true;
2034 }
2035 if (SVal.isVector()) {
2036 QualType VecTy = E->getType();
2037 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2038 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2039 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2040 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2041 Res = llvm::APInt::getNullValue(VecSize);
2042 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2043 APValue &Elt = SVal.getVectorElt(i);
2044 llvm::APInt EltAsInt;
2045 if (Elt.isInt()) {
2046 EltAsInt = Elt.getInt();
2047 } else if (Elt.isFloat()) {
2048 EltAsInt = Elt.getFloat().bitcastToAPInt();
2049 } else {
2050 // Don't try to handle vectors of anything other than int or float
2051 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002052 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002053 return false;
2054 }
2055 unsigned BaseEltSize = EltAsInt.getBitWidth();
2056 if (BigEndian)
2057 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2058 else
2059 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2060 }
2061 return true;
2062 }
2063 // Give up if the input isn't an int, float, or vector. For example, we
2064 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002066 return false;
2067}
2068
Richard Smith43e77732013-05-07 04:50:00 +00002069/// Perform the given integer operation, which is known to need at most BitWidth
2070/// bits, and check for overflow in the original type (if that type was not an
2071/// unsigned type).
2072template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002073static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2074 const APSInt &LHS, const APSInt &RHS,
2075 unsigned BitWidth, Operation Op,
2076 APSInt &Result) {
2077 if (LHS.isUnsigned()) {
2078 Result = Op(LHS, RHS);
2079 return true;
2080 }
Richard Smith43e77732013-05-07 04:50:00 +00002081
2082 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002083 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002084 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002085 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002086 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002087 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002088 << Result.toString(10) << E->getType();
2089 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002090 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002091 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002092 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002093}
2094
2095/// Perform the given binary integer operation.
2096static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2097 BinaryOperatorKind Opcode, APSInt RHS,
2098 APSInt &Result) {
2099 switch (Opcode) {
2100 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002101 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002102 return false;
2103 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002104 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2105 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002106 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002107 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2108 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002109 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002110 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2111 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002112 case BO_And: Result = LHS & RHS; return true;
2113 case BO_Xor: Result = LHS ^ RHS; return true;
2114 case BO_Or: Result = LHS | RHS; return true;
2115 case BO_Div:
2116 case BO_Rem:
2117 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002118 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002119 return false;
2120 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002121 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2122 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2123 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002124 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2125 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002126 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2127 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002128 return true;
2129 case BO_Shl: {
2130 if (Info.getLangOpts().OpenCL)
2131 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2132 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2133 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2134 RHS.isUnsigned());
2135 else if (RHS.isSigned() && RHS.isNegative()) {
2136 // During constant-folding, a negative shift is an opposite shift. Such
2137 // a shift is not a constant expression.
2138 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2139 RHS = -RHS;
2140 goto shift_right;
2141 }
2142 shift_left:
2143 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2144 // the shifted type.
2145 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2146 if (SA != RHS) {
2147 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2148 << RHS << E->getType() << LHS.getBitWidth();
2149 } else if (LHS.isSigned()) {
2150 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2151 // operand, and must not overflow the corresponding unsigned type.
2152 if (LHS.isNegative())
2153 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2154 else if (LHS.countLeadingZeros() < SA)
2155 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2156 }
2157 Result = LHS << SA;
2158 return true;
2159 }
2160 case BO_Shr: {
2161 if (Info.getLangOpts().OpenCL)
2162 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2163 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2164 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2165 RHS.isUnsigned());
2166 else if (RHS.isSigned() && RHS.isNegative()) {
2167 // During constant-folding, a negative shift is an opposite shift. Such a
2168 // shift is not a constant expression.
2169 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2170 RHS = -RHS;
2171 goto shift_left;
2172 }
2173 shift_right:
2174 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2175 // shifted type.
2176 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2177 if (SA != RHS)
2178 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2179 << RHS << E->getType() << LHS.getBitWidth();
2180 Result = LHS >> SA;
2181 return true;
2182 }
2183
2184 case BO_LT: Result = LHS < RHS; return true;
2185 case BO_GT: Result = LHS > RHS; return true;
2186 case BO_LE: Result = LHS <= RHS; return true;
2187 case BO_GE: Result = LHS >= RHS; return true;
2188 case BO_EQ: Result = LHS == RHS; return true;
2189 case BO_NE: Result = LHS != RHS; return true;
2190 }
2191}
2192
Richard Smith861b5b52013-05-07 23:34:45 +00002193/// Perform the given binary floating-point operation, in-place, on LHS.
2194static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2195 APFloat &LHS, BinaryOperatorKind Opcode,
2196 const APFloat &RHS) {
2197 switch (Opcode) {
2198 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002199 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002200 return false;
2201 case BO_Mul:
2202 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2203 break;
2204 case BO_Add:
2205 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2206 break;
2207 case BO_Sub:
2208 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2209 break;
2210 case BO_Div:
2211 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2212 break;
2213 }
2214
Richard Smith0c6124b2015-12-03 01:36:22 +00002215 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002216 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002217 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002218 }
Richard Smith861b5b52013-05-07 23:34:45 +00002219 return true;
2220}
2221
Richard Smitha8105bc2012-01-06 16:39:00 +00002222/// Cast an lvalue referring to a base subobject to a derived class, by
2223/// truncating the lvalue's path to the given length.
2224static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2225 const RecordDecl *TruncatedType,
2226 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002227 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002228
2229 // Check we actually point to a derived class object.
2230 if (TruncatedElements == D.Entries.size())
2231 return true;
2232 assert(TruncatedElements >= D.MostDerivedPathLength &&
2233 "not casting to a derived class");
2234 if (!Result.checkSubobject(Info, E, CSK_Derived))
2235 return false;
2236
2237 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002238 const RecordDecl *RD = TruncatedType;
2239 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002240 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002241 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2242 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002243 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002244 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002245 else
Richard Smithd62306a2011-11-10 06:34:14 +00002246 Result.Offset -= Layout.getBaseClassOffset(Base);
2247 RD = Base;
2248 }
Richard Smith027bf112011-11-17 22:56:20 +00002249 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002250 return true;
2251}
2252
John McCalld7bca762012-05-01 00:38:49 +00002253static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002254 const CXXRecordDecl *Derived,
2255 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002256 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002257 if (!RL) {
2258 if (Derived->isInvalidDecl()) return false;
2259 RL = &Info.Ctx.getASTRecordLayout(Derived);
2260 }
2261
Richard Smithd62306a2011-11-10 06:34:14 +00002262 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002263 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002264 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002265}
2266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002268 const CXXRecordDecl *DerivedDecl,
2269 const CXXBaseSpecifier *Base) {
2270 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2271
John McCalld7bca762012-05-01 00:38:49 +00002272 if (!Base->isVirtual())
2273 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002274
Richard Smitha8105bc2012-01-06 16:39:00 +00002275 SubobjectDesignator &D = Obj.Designator;
2276 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002277 return false;
2278
Richard Smitha8105bc2012-01-06 16:39:00 +00002279 // Extract most-derived object and corresponding type.
2280 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2281 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2282 return false;
2283
2284 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002285 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2287 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002289 return true;
2290}
2291
Richard Smith84401042013-06-03 05:03:02 +00002292static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2293 QualType Type, LValue &Result) {
2294 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2295 PathE = E->path_end();
2296 PathI != PathE; ++PathI) {
2297 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2298 *PathI))
2299 return false;
2300 Type = (*PathI)->getType();
2301 }
2302 return true;
2303}
2304
Richard Smithd62306a2011-11-10 06:34:14 +00002305/// Update LVal to refer to the given field, which must be a member of the type
2306/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002307static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002308 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002309 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002310 if (!RL) {
2311 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002312 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002313 }
Richard Smithd62306a2011-11-10 06:34:14 +00002314
2315 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002316 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002317 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002318 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002319}
2320
Richard Smith1b78b3d2012-01-25 22:15:11 +00002321/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002322static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002323 LValue &LVal,
2324 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002325 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002326 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002327 return false;
2328 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002329}
2330
Richard Smithd62306a2011-11-10 06:34:14 +00002331/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002332static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2333 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002334 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2335 // extension.
2336 if (Type->isVoidType() || Type->isFunctionType()) {
2337 Size = CharUnits::One();
2338 return true;
2339 }
2340
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002341 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002342 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002343 return false;
2344 }
2345
Richard Smithd62306a2011-11-10 06:34:14 +00002346 if (!Type->isConstantSizeType()) {
2347 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002348 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002349 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002350 return false;
2351 }
2352
2353 Size = Info.Ctx.getTypeSizeInChars(Type);
2354 return true;
2355}
2356
2357/// Update a pointer value to model pointer arithmetic.
2358/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002359/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002360/// \param LVal - The pointer value to be updated.
2361/// \param EltTy - The pointee type represented by LVal.
2362/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002363static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2364 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002365 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002366 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002367 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002368 return false;
2369
Yaxun Liu402804b2016-12-15 08:09:08 +00002370 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002371 return true;
2372}
2373
Richard Smithd6cc1982017-01-31 02:23:02 +00002374static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2375 LValue &LVal, QualType EltTy,
2376 int64_t Adjustment) {
2377 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2378 APSInt::get(Adjustment));
2379}
2380
Richard Smith66c96992012-02-18 22:04:06 +00002381/// Update an lvalue to refer to a component of a complex number.
2382/// \param Info - Information about the ongoing evaluation.
2383/// \param LVal - The lvalue to be updated.
2384/// \param EltTy - The complex number's component type.
2385/// \param Imag - False for the real component, true for the imaginary.
2386static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2387 LValue &LVal, QualType EltTy,
2388 bool Imag) {
2389 if (Imag) {
2390 CharUnits SizeOfComponent;
2391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2392 return false;
2393 LVal.Offset += SizeOfComponent;
2394 }
2395 LVal.addComplex(Info, E, EltTy, Imag);
2396 return true;
2397}
2398
Faisal Vali051e3a22017-02-16 04:12:21 +00002399static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2400 QualType Type, const LValue &LVal,
2401 APValue &RVal);
2402
Richard Smith27908702011-10-24 17:54:18 +00002403/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002404///
2405/// \param Info Information about the ongoing evaluation.
2406/// \param E An expression to be used when printing diagnostics.
2407/// \param VD The variable whose initializer should be obtained.
2408/// \param Frame The frame in which the variable was created. Must be null
2409/// if this variable is not local to the evaluation.
2410/// \param Result Filled in with a pointer to the value of the variable.
2411static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2412 const VarDecl *VD, CallStackFrame *Frame,
2413 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002414
Richard Smith254a73d2011-10-28 22:34:42 +00002415 // If this is a parameter to an active constexpr function call, perform
2416 // argument substitution.
2417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002418 // Assume arguments of a potential constant expression are unknown
2419 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002420 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002421 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002422 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002423 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002424 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002425 }
Richard Smith3229b742013-05-05 21:17:10 +00002426 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002427 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002428 }
Richard Smith27908702011-10-24 17:54:18 +00002429
Richard Smithd9f663b2013-04-22 15:31:51 +00002430 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002431 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002432 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002433 if (!Result) {
2434 // Assume variables referenced within a lambda's call operator that were
2435 // not declared within the call operator are captures and during checking
2436 // of a potential constant expression, assume they are unknown constant
2437 // expressions.
2438 assert(isLambdaCallOperator(Frame->Callee) &&
2439 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2440 "missing value for local variable");
2441 if (Info.checkingPotentialConstantExpression())
2442 return false;
2443 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002444 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002445 diag::note_unimplemented_constexpr_lambda_feature_ast)
2446 << "captures not currently allowed";
2447 return false;
2448 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002449 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002450 }
2451
Richard Smithd0b4dd62011-12-19 06:19:21 +00002452 // Dig out the initializer, and use the declaration which it's attached to.
2453 const Expr *Init = VD->getAnyInitializer(VD);
2454 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002455 // If we're checking a potential constant expression, the variable could be
2456 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002457 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002459 return false;
2460 }
2461
Richard Smithd62306a2011-11-10 06:34:14 +00002462 // If we're currently evaluating the initializer of this declaration, use that
2463 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002464 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002465 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002466 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002467 }
2468
Richard Smithcecf1842011-11-01 21:06:14 +00002469 // Never evaluate the initializer of a weak variable. We can't be sure that
2470 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002471 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002472 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002473 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002474 }
Richard Smithcecf1842011-11-01 21:06:14 +00002475
Richard Smithd0b4dd62011-12-19 06:19:21 +00002476 // Check that we can fold the initializer. In C++, we will have already done
2477 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002478 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002479 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002480 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002481 Notes.size() + 1) << VD;
2482 Info.Note(VD->getLocation(), diag::note_declared_at);
2483 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002484 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002485 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002486 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002487 Notes.size() + 1) << VD;
2488 Info.Note(VD->getLocation(), diag::note_declared_at);
2489 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002490 }
Richard Smith27908702011-10-24 17:54:18 +00002491
Richard Smith3229b742013-05-05 21:17:10 +00002492 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002493 return true;
Richard Smith27908702011-10-24 17:54:18 +00002494}
2495
Richard Smith11562c52011-10-28 17:51:58 +00002496static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002497 Qualifiers Quals = T.getQualifiers();
2498 return Quals.hasConst() && !Quals.hasVolatile();
2499}
2500
Richard Smithe97cbd72011-11-11 04:05:33 +00002501/// Get the base index of the given base class within an APValue representing
2502/// the given derived class.
2503static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2504 const CXXRecordDecl *Base) {
2505 Base = Base->getCanonicalDecl();
2506 unsigned Index = 0;
2507 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2508 E = Derived->bases_end(); I != E; ++I, ++Index) {
2509 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2510 return Index;
2511 }
2512
2513 llvm_unreachable("base class missing from derived class's bases list");
2514}
2515
Richard Smith3da88fa2013-04-26 14:36:30 +00002516/// Extract the value of a character from a string literal.
2517static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2518 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002519 // FIXME: Support MakeStringConstant
2520 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2521 std::string Str;
2522 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2523 assert(Index <= Str.size() && "Index too large");
2524 return APSInt::getUnsigned(Str.c_str()[Index]);
2525 }
2526
Alexey Bataevec474782014-10-09 08:45:04 +00002527 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2528 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002529 const StringLiteral *S = cast<StringLiteral>(Lit);
2530 const ConstantArrayType *CAT =
2531 Info.Ctx.getAsConstantArrayType(S->getType());
2532 assert(CAT && "string literal isn't an array");
2533 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002534 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002535
2536 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002537 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002538 if (Index < S->getLength())
2539 Value = S->getCodeUnit(Index);
2540 return Value;
2541}
2542
Richard Smith3da88fa2013-04-26 14:36:30 +00002543// Expand a string literal into an array of characters.
2544static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2545 APValue &Result) {
2546 const StringLiteral *S = cast<StringLiteral>(Lit);
2547 const ConstantArrayType *CAT =
2548 Info.Ctx.getAsConstantArrayType(S->getType());
2549 assert(CAT && "string literal isn't an array");
2550 QualType CharType = CAT->getElementType();
2551 assert(CharType->isIntegerType() && "unexpected character type");
2552
2553 unsigned Elts = CAT->getSize().getZExtValue();
2554 Result = APValue(APValue::UninitArray(),
2555 std::min(S->getLength(), Elts), Elts);
2556 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2557 CharType->isUnsignedIntegerType());
2558 if (Result.hasArrayFiller())
2559 Result.getArrayFiller() = APValue(Value);
2560 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2561 Value = S->getCodeUnit(I);
2562 Result.getArrayInitializedElt(I) = APValue(Value);
2563 }
2564}
2565
2566// Expand an array so that it has more than Index filled elements.
2567static void expandArray(APValue &Array, unsigned Index) {
2568 unsigned Size = Array.getArraySize();
2569 assert(Index < Size);
2570
2571 // Always at least double the number of elements for which we store a value.
2572 unsigned OldElts = Array.getArrayInitializedElts();
2573 unsigned NewElts = std::max(Index+1, OldElts * 2);
2574 NewElts = std::min(Size, std::max(NewElts, 8u));
2575
2576 // Copy the data across.
2577 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2578 for (unsigned I = 0; I != OldElts; ++I)
2579 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2580 for (unsigned I = OldElts; I != NewElts; ++I)
2581 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2582 if (NewValue.hasArrayFiller())
2583 NewValue.getArrayFiller() = Array.getArrayFiller();
2584 Array.swap(NewValue);
2585}
2586
Richard Smithb01fe402014-09-16 01:24:02 +00002587/// Determine whether a type would actually be read by an lvalue-to-rvalue
2588/// conversion. If it's of class type, we may assume that the copy operation
2589/// is trivial. Note that this is never true for a union type with fields
2590/// (because the copy always "reads" the active member) and always true for
2591/// a non-class type.
2592static bool isReadByLvalueToRvalueConversion(QualType T) {
2593 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2594 if (!RD || (RD->isUnion() && !RD->field_empty()))
2595 return true;
2596 if (RD->isEmpty())
2597 return false;
2598
2599 for (auto *Field : RD->fields())
2600 if (isReadByLvalueToRvalueConversion(Field->getType()))
2601 return true;
2602
2603 for (auto &BaseSpec : RD->bases())
2604 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2605 return true;
2606
2607 return false;
2608}
2609
2610/// Diagnose an attempt to read from any unreadable field within the specified
2611/// type, which might be a class type.
2612static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2613 QualType T) {
2614 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2615 if (!RD)
2616 return false;
2617
2618 if (!RD->hasMutableFields())
2619 return false;
2620
2621 for (auto *Field : RD->fields()) {
2622 // If we're actually going to read this field in some way, then it can't
2623 // be mutable. If we're in a union, then assigning to a mutable field
2624 // (even an empty one) can change the active member, so that's not OK.
2625 // FIXME: Add core issue number for the union case.
2626 if (Field->isMutable() &&
2627 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002628 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002629 Info.Note(Field->getLocation(), diag::note_declared_at);
2630 return true;
2631 }
2632
2633 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2634 return true;
2635 }
2636
2637 for (auto &BaseSpec : RD->bases())
2638 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2639 return true;
2640
2641 // All mutable fields were empty, and thus not actually read.
2642 return false;
2643}
2644
Richard Smith861b5b52013-05-07 23:34:45 +00002645/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002646enum AccessKinds {
2647 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002648 AK_Assign,
2649 AK_Increment,
2650 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002651};
2652
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002653namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002654/// A handle to a complete object (an object that is not a subobject of
2655/// another object).
2656struct CompleteObject {
2657 /// The value of the complete object.
2658 APValue *Value;
2659 /// The type of the complete object.
2660 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002661 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002662
Craig Topper36250ad2014-05-12 05:36:57 +00002663 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002664 CompleteObject(APValue *Value, QualType Type,
2665 bool LifetimeStartedInEvaluation)
2666 : Value(Value), Type(Type),
2667 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002668 assert(Value && "missing value for complete object");
2669 }
2670
Aaron Ballman67347662015-02-15 22:00:28 +00002671 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002672};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002673} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002674
Richard Smith3da88fa2013-04-26 14:36:30 +00002675/// Find the designated sub-object of an rvalue.
2676template<typename SubobjectHandler>
2677typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002678findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 if (Sub.Invalid)
2681 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002682 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002683 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002684 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002685 Info.FFDiag(E, Sub.isOnePastTheEnd()
2686 ? diag::note_constexpr_access_past_end
2687 : diag::note_constexpr_access_unsized_array)
2688 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002689 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002691 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002692 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002693
Richard Smith3229b742013-05-05 21:17:10 +00002694 APValue *O = Obj.Value;
2695 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002696 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002697 const bool MayReadMutableMembers =
2698 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002699
Richard Smithd62306a2011-11-10 06:34:14 +00002700 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002701 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2702 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002703 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002704 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002705 return handler.failed();
2706 }
2707
Richard Smith49ca8aa2013-08-06 07:09:20 +00002708 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002709 // If we are reading an object of class type, there may still be more
2710 // things we need to check: if there are any mutable subobjects, we
2711 // cannot perform this read. (This only happens when performing a trivial
2712 // copy or assignment.)
2713 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002714 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002715 return handler.failed();
2716
Richard Smith49ca8aa2013-08-06 07:09:20 +00002717 if (!handler.found(*O, ObjType))
2718 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002719
Richard Smith49ca8aa2013-08-06 07:09:20 +00002720 // If we modified a bit-field, truncate it to the right width.
2721 if (handler.AccessKind != AK_Read &&
2722 LastField && LastField->isBitField() &&
2723 !truncateBitfieldValue(Info, E, *O, LastField))
2724 return false;
2725
2726 return true;
2727 }
2728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002730 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002731 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002732 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002733 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002734 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002735 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002736 // Note, it should not be possible to form a pointer with a valid
2737 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002739 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 << handler.AccessKind;
2741 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002742 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002744 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002745
2746 ObjType = CAT->getElementType();
2747
Richard Smith14a94132012-02-17 03:35:37 +00002748 // An array object is represented as either an Array APValue or as an
2749 // LValue which refers to a string literal.
2750 if (O->isLValue()) {
2751 assert(I == N - 1 && "extracting subobject of character?");
2752 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002753 if (handler.AccessKind != AK_Read)
2754 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2755 *O);
2756 else
2757 return handler.foundString(*O, ObjType, Index);
2758 }
2759
2760 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002761 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002762 else if (handler.AccessKind != AK_Read) {
2763 expandArray(*O, Index);
2764 O = &O->getArrayInitializedElt(Index);
2765 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002766 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002767 } else if (ObjType->isAnyComplexType()) {
2768 // Next subobject is a complex number.
2769 uint64_t Index = Sub.Entries[I].ArrayIndex;
2770 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002771 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002772 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002773 << handler.AccessKind;
2774 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002775 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002777 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002778
2779 bool WasConstQualified = ObjType.isConstQualified();
2780 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2781 if (WasConstQualified)
2782 ObjType.addConst();
2783
Richard Smith66c96992012-02-18 22:04:06 +00002784 assert(I == N - 1 && "extracting subobject of scalar?");
2785 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002786 return handler.found(Index ? O->getComplexIntImag()
2787 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002788 } else {
2789 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return handler.found(Index ? O->getComplexFloatImag()
2791 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002792 }
Richard Smithd62306a2011-11-10 06:34:14 +00002793 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002794 // In C++14 onwards, it is permitted to read a mutable member whose
2795 // lifetime began within the evaluation.
2796 // FIXME: Should we also allow this in C++11?
2797 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2798 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002800 << Field;
2801 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002802 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002803 }
2804
Richard Smithd62306a2011-11-10 06:34:14 +00002805 // Next subobject is a class, struct or union field.
2806 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2807 if (RD->isUnion()) {
2808 const FieldDecl *UnionField = O->getUnionField();
2809 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002810 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002811 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 << handler.AccessKind << Field << !UnionField << UnionField;
2813 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002814 }
Richard Smithd62306a2011-11-10 06:34:14 +00002815 O = &O->getUnionValue();
2816 } else
2817 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002818
2819 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002820 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002821 if (WasConstQualified && !Field->isMutable())
2822 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002823
2824 if (ObjType.isVolatileQualified()) {
2825 if (Info.getLangOpts().CPlusPlus) {
2826 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002827 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002828 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002829 Info.Note(Field->getLocation(), diag::note_declared_at);
2830 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002832 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002834 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002835
2836 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002837 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002838 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002839 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2840 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2841 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002842
2843 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002844 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002845 if (WasConstQualified)
2846 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002847 }
2848 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002849}
2850
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002851namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002852struct ExtractSubobjectHandler {
2853 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002854 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002855
2856 static const AccessKinds AccessKind = AK_Read;
2857
2858 typedef bool result_type;
2859 bool failed() { return false; }
2860 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 return true;
2863 }
2864 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002865 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 return true;
2867 }
2868 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002869 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002870 return true;
2871 }
2872 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002873 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002874 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2875 return true;
2876 }
2877};
Richard Smith3229b742013-05-05 21:17:10 +00002878} // end anonymous namespace
2879
Richard Smith3da88fa2013-04-26 14:36:30 +00002880const AccessKinds ExtractSubobjectHandler::AccessKind;
2881
2882/// Extract the designated sub-object of an rvalue.
2883static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002884 const CompleteObject &Obj,
2885 const SubobjectDesignator &Sub,
2886 APValue &Result) {
2887 ExtractSubobjectHandler Handler = { Info, Result };
2888 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002889}
2890
Richard Smith3229b742013-05-05 21:17:10 +00002891namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002892struct ModifySubobjectHandler {
2893 EvalInfo &Info;
2894 APValue &NewVal;
2895 const Expr *E;
2896
2897 typedef bool result_type;
2898 static const AccessKinds AccessKind = AK_Assign;
2899
2900 bool checkConst(QualType QT) {
2901 // Assigning to a const object has undefined behavior.
2902 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002903 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002904 return false;
2905 }
2906 return true;
2907 }
2908
2909 bool failed() { return false; }
2910 bool found(APValue &Subobj, QualType SubobjType) {
2911 if (!checkConst(SubobjType))
2912 return false;
2913 // We've been given ownership of NewVal, so just swap it in.
2914 Subobj.swap(NewVal);
2915 return true;
2916 }
2917 bool found(APSInt &Value, QualType SubobjType) {
2918 if (!checkConst(SubobjType))
2919 return false;
2920 if (!NewVal.isInt()) {
2921 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002922 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002923 return false;
2924 }
2925 Value = NewVal.getInt();
2926 return true;
2927 }
2928 bool found(APFloat &Value, QualType SubobjType) {
2929 if (!checkConst(SubobjType))
2930 return false;
2931 Value = NewVal.getFloat();
2932 return true;
2933 }
2934 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2935 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2936 }
2937};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002938} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002939
Richard Smith3229b742013-05-05 21:17:10 +00002940const AccessKinds ModifySubobjectHandler::AccessKind;
2941
Richard Smith3da88fa2013-04-26 14:36:30 +00002942/// Update the designated sub-object of an rvalue to the given value.
2943static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002944 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002945 const SubobjectDesignator &Sub,
2946 APValue &NewVal) {
2947 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002948 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002949}
2950
Richard Smith84f6dcf2012-02-02 01:16:57 +00002951/// Find the position where two subobject designators diverge, or equivalently
2952/// the length of the common initial subsequence.
2953static unsigned FindDesignatorMismatch(QualType ObjType,
2954 const SubobjectDesignator &A,
2955 const SubobjectDesignator &B,
2956 bool &WasArrayIndex) {
2957 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2958 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002959 if (!ObjType.isNull() &&
2960 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002961 // Next subobject is an array element.
2962 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2963 WasArrayIndex = true;
2964 return I;
2965 }
Richard Smith66c96992012-02-18 22:04:06 +00002966 if (ObjType->isAnyComplexType())
2967 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2968 else
2969 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002970 } else {
2971 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2972 WasArrayIndex = false;
2973 return I;
2974 }
2975 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2976 // Next subobject is a field.
2977 ObjType = FD->getType();
2978 else
2979 // Next subobject is a base class.
2980 ObjType = QualType();
2981 }
2982 }
2983 WasArrayIndex = false;
2984 return I;
2985}
2986
2987/// Determine whether the given subobject designators refer to elements of the
2988/// same array object.
2989static bool AreElementsOfSameArray(QualType ObjType,
2990 const SubobjectDesignator &A,
2991 const SubobjectDesignator &B) {
2992 if (A.Entries.size() != B.Entries.size())
2993 return false;
2994
George Burgess IVa51c4072015-10-16 01:49:01 +00002995 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002996 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2997 // A is a subobject of the array element.
2998 return false;
2999
3000 // If A (and B) designates an array element, the last entry will be the array
3001 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3002 // of length 1' case, and the entire path must match.
3003 bool WasArrayIndex;
3004 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3005 return CommonLength >= A.Entries.size() - IsArray;
3006}
3007
Richard Smith3229b742013-05-05 21:17:10 +00003008/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003009static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3010 AccessKinds AK, const LValue &LVal,
3011 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003012 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003013 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003014 return CompleteObject();
3015 }
3016
Craig Topper36250ad2014-05-12 05:36:57 +00003017 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003018 if (LVal.CallIndex) {
3019 Frame = Info.getCallFrame(LVal.CallIndex);
3020 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003021 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003022 << AK << LVal.Base.is<const ValueDecl*>();
3023 NoteLValueLocation(Info, LVal.Base);
3024 return CompleteObject();
3025 }
Richard Smith3229b742013-05-05 21:17:10 +00003026 }
3027
3028 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3029 // is not a constant expression (even if the object is non-volatile). We also
3030 // apply this rule to C++98, in order to conform to the expected 'volatile'
3031 // semantics.
3032 if (LValType.isVolatileQualified()) {
3033 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003034 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003035 << AK << LValType;
3036 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003037 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003038 return CompleteObject();
3039 }
3040
3041 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003042 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003043 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003044 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003045
3046 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3047 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3048 // In C++11, constexpr, non-volatile variables initialized with constant
3049 // expressions are constant expressions too. Inside constexpr functions,
3050 // parameters are constant expressions even if they're non-const.
3051 // In C++1y, objects local to a constant expression (those with a Frame) are
3052 // both readable and writable inside constant expressions.
3053 // In C, such things can also be folded, although they are not ICEs.
3054 const VarDecl *VD = dyn_cast<VarDecl>(D);
3055 if (VD) {
3056 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3057 VD = VDef;
3058 }
3059 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003060 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003061 return CompleteObject();
3062 }
3063
3064 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003065 if (BaseType.isVolatileQualified()) {
3066 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003067 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003068 << AK << 1 << VD;
3069 Info.Note(VD->getLocation(), diag::note_declared_at);
3070 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003071 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003072 }
3073 return CompleteObject();
3074 }
3075
3076 // Unless we're looking at a local variable or argument in a constexpr call,
3077 // the variable we're reading must be const.
3078 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003079 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003080 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3081 // OK, we can read and modify an object if we're in the process of
3082 // evaluating its initializer, because its lifetime began in this
3083 // evaluation.
3084 } else if (AK != AK_Read) {
3085 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003086 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003087 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003088 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003089 // OK, we can read this variable.
3090 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003091 // In OpenCL if a variable is in constant address space it is a const value.
3092 if (!(BaseType.isConstQualified() ||
3093 (Info.getLangOpts().OpenCL &&
3094 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003095 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003096 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003097 Info.Note(VD->getLocation(), diag::note_declared_at);
3098 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003099 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003100 }
3101 return CompleteObject();
3102 }
3103 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3104 // We support folding of const floating-point types, in order to make
3105 // static const data members of such types (supported as an extension)
3106 // more useful.
3107 if (Info.getLangOpts().CPlusPlus11) {
3108 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3109 Info.Note(VD->getLocation(), diag::note_declared_at);
3110 } else {
3111 Info.CCEDiag(E);
3112 }
George Burgess IVb5316982016-12-27 05:33:20 +00003113 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3114 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3115 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003116 } else {
3117 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003118 if (Info.checkingPotentialConstantExpression() &&
3119 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3120 // The definition of this variable could be constexpr. We can't
3121 // access it right now, but may be able to in future.
3122 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003123 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003124 Info.Note(VD->getLocation(), diag::note_declared_at);
3125 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003126 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003127 }
3128 return CompleteObject();
3129 }
3130 }
3131
3132 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3133 return CompleteObject();
3134 } else {
3135 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3136
3137 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003138 if (const MaterializeTemporaryExpr *MTE =
3139 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3140 assert(MTE->getStorageDuration() == SD_Static &&
3141 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003142
Richard Smithe6c01442013-06-05 00:46:14 +00003143 // Per C++1y [expr.const]p2:
3144 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3145 // - a [...] glvalue of integral or enumeration type that refers to
3146 // a non-volatile const object [...]
3147 // [...]
3148 // - a [...] glvalue of literal type that refers to a non-volatile
3149 // object whose lifetime began within the evaluation of e.
3150 //
3151 // C++11 misses the 'began within the evaluation of e' check and
3152 // instead allows all temporaries, including things like:
3153 // int &&r = 1;
3154 // int x = ++r;
3155 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003156 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003157 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3158 const ValueDecl *ED = MTE->getExtendingDecl();
3159 if (!(BaseType.isConstQualified() &&
3160 BaseType->isIntegralOrEnumerationType()) &&
3161 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003162 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003163 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3164 return CompleteObject();
3165 }
3166
3167 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3168 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003169 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003170 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003171 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003172 return CompleteObject();
3173 }
3174 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003175 BaseVal = Frame->getTemporary(Base);
3176 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003177 }
Richard Smith3229b742013-05-05 21:17:10 +00003178
3179 // Volatile temporary objects cannot be accessed in constant expressions.
3180 if (BaseType.isVolatileQualified()) {
3181 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003182 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003183 << AK << 0;
3184 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3185 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003186 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003187 }
3188 return CompleteObject();
3189 }
3190 }
3191
Richard Smith7525ff62013-05-09 07:14:00 +00003192 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003193 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003194 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003195 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003196 BaseType = Info.Ctx.getCanonicalType(BaseType);
3197 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003198 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003199 }
3200
Richard Smith9defb7d2018-02-21 03:38:30 +00003201 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003202 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003203 //
3204 // FIXME: Not all local state is mutable. Allow local constant subobjects
3205 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003206 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3207 Info.EvalStatus.HasSideEffects) ||
3208 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003209 return CompleteObject();
3210
Richard Smith9defb7d2018-02-21 03:38:30 +00003211 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003212}
3213
Richard Smith243ef902013-05-05 23:31:59 +00003214/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3215/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3216/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003217///
3218/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003219/// \param Conv - The expression for which we are performing the conversion.
3220/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003221/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3222/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003223/// \param LVal - The glvalue on which we are attempting to perform this action.
3224/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003225static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003226 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003227 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003228 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003229 return false;
3230
Richard Smith3229b742013-05-05 21:17:10 +00003231 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003232 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003233 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003234 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3235 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3236 // initializer until now for such expressions. Such an expression can't be
3237 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003238 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003239 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003240 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003241 }
Richard Smith3229b742013-05-05 21:17:10 +00003242 APValue Lit;
3243 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3244 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003245 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003246 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003247 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003248 // We represent a string literal array as an lvalue pointing at the
3249 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003250 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003251 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003252 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003253 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003254 }
Richard Smith11562c52011-10-28 17:51:58 +00003255 }
3256
Richard Smith3229b742013-05-05 21:17:10 +00003257 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3258 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003259}
3260
3261/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003262static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003263 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003264 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003265 return false;
3266
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003267 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003269 return false;
3270 }
3271
Richard Smith3229b742013-05-05 21:17:10 +00003272 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003273 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3274}
3275
3276namespace {
3277struct CompoundAssignSubobjectHandler {
3278 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003279 const Expr *E;
3280 QualType PromotedLHSType;
3281 BinaryOperatorKind Opcode;
3282 const APValue &RHS;
3283
3284 static const AccessKinds AccessKind = AK_Assign;
3285
3286 typedef bool result_type;
3287
3288 bool checkConst(QualType QT) {
3289 // Assigning to a const object has undefined behavior.
3290 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003291 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003292 return false;
3293 }
3294 return true;
3295 }
3296
3297 bool failed() { return false; }
3298 bool found(APValue &Subobj, QualType SubobjType) {
3299 switch (Subobj.getKind()) {
3300 case APValue::Int:
3301 return found(Subobj.getInt(), SubobjType);
3302 case APValue::Float:
3303 return found(Subobj.getFloat(), SubobjType);
3304 case APValue::ComplexInt:
3305 case APValue::ComplexFloat:
3306 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003307 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003308 return false;
3309 case APValue::LValue:
3310 return foundPointer(Subobj, SubobjType);
3311 default:
3312 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003313 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003314 return false;
3315 }
3316 }
3317 bool found(APSInt &Value, QualType SubobjType) {
3318 if (!checkConst(SubobjType))
3319 return false;
3320
3321 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3322 // We don't support compound assignment on integer-cast-to-pointer
3323 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003324 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003325 return false;
3326 }
3327
3328 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3329 SubobjType, Value);
3330 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3331 return false;
3332 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3333 return true;
3334 }
3335 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003336 return checkConst(SubobjType) &&
3337 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3338 Value) &&
3339 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3340 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003341 }
3342 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3343 if (!checkConst(SubobjType))
3344 return false;
3345
3346 QualType PointeeType;
3347 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3348 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003349
3350 if (PointeeType.isNull() || !RHS.isInt() ||
3351 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003352 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003353 return false;
3354 }
3355
Richard Smithd6cc1982017-01-31 02:23:02 +00003356 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003357 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003358 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003359
3360 LValue LVal;
3361 LVal.setFrom(Info.Ctx, Subobj);
3362 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3363 return false;
3364 LVal.moveInto(Subobj);
3365 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003366 }
3367 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3368 llvm_unreachable("shouldn't encounter string elements here");
3369 }
3370};
3371} // end anonymous namespace
3372
3373const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3374
3375/// Perform a compound assignment of LVal <op>= RVal.
3376static bool handleCompoundAssignment(
3377 EvalInfo &Info, const Expr *E,
3378 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3379 BinaryOperatorKind Opcode, const APValue &RVal) {
3380 if (LVal.Designator.Invalid)
3381 return false;
3382
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003383 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003384 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003385 return false;
3386 }
3387
3388 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3389 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3390 RVal };
3391 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3392}
3393
Aaron Ballmana5038552018-01-09 13:07:03 +00003394namespace {
3395struct IncDecSubobjectHandler {
3396 EvalInfo &Info;
3397 const UnaryOperator *E;
3398 AccessKinds AccessKind;
3399 APValue *Old;
3400
Richard Smith243ef902013-05-05 23:31:59 +00003401 typedef bool result_type;
3402
3403 bool checkConst(QualType QT) {
3404 // Assigning to a const object has undefined behavior.
3405 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003407 return false;
3408 }
3409 return true;
3410 }
3411
3412 bool failed() { return false; }
3413 bool found(APValue &Subobj, QualType SubobjType) {
3414 // Stash the old value. Also clear Old, so we don't clobber it later
3415 // if we're post-incrementing a complex.
3416 if (Old) {
3417 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003418 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003419 }
3420
3421 switch (Subobj.getKind()) {
3422 case APValue::Int:
3423 return found(Subobj.getInt(), SubobjType);
3424 case APValue::Float:
3425 return found(Subobj.getFloat(), SubobjType);
3426 case APValue::ComplexInt:
3427 return found(Subobj.getComplexIntReal(),
3428 SubobjType->castAs<ComplexType>()->getElementType()
3429 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3430 case APValue::ComplexFloat:
3431 return found(Subobj.getComplexFloatReal(),
3432 SubobjType->castAs<ComplexType>()->getElementType()
3433 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3434 case APValue::LValue:
3435 return foundPointer(Subobj, SubobjType);
3436 default:
3437 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003438 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003439 return false;
3440 }
3441 }
3442 bool found(APSInt &Value, QualType SubobjType) {
3443 if (!checkConst(SubobjType))
3444 return false;
3445
3446 if (!SubobjType->isIntegerType()) {
3447 // We don't support increment / decrement on integer-cast-to-pointer
3448 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003449 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003450 return false;
3451 }
3452
3453 if (Old) *Old = APValue(Value);
3454
3455 // bool arithmetic promotes to int, and the conversion back to bool
3456 // doesn't reduce mod 2^n, so special-case it.
3457 if (SubobjType->isBooleanType()) {
3458 if (AccessKind == AK_Increment)
3459 Value = 1;
3460 else
3461 Value = !Value;
3462 return true;
3463 }
3464
3465 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003466 if (AccessKind == AK_Increment) {
3467 ++Value;
3468
3469 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3470 APSInt ActualValue(Value, /*IsUnsigned*/true);
3471 return HandleOverflow(Info, E, ActualValue, SubobjType);
3472 }
3473 } else {
3474 --Value;
3475
3476 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3477 unsigned BitWidth = Value.getBitWidth();
3478 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3479 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003480 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003481 }
3482 }
3483 return true;
3484 }
3485 bool found(APFloat &Value, QualType SubobjType) {
3486 if (!checkConst(SubobjType))
3487 return false;
3488
3489 if (Old) *Old = APValue(Value);
3490
3491 APFloat One(Value.getSemantics(), 1);
3492 if (AccessKind == AK_Increment)
3493 Value.add(One, APFloat::rmNearestTiesToEven);
3494 else
3495 Value.subtract(One, APFloat::rmNearestTiesToEven);
3496 return true;
3497 }
3498 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3499 if (!checkConst(SubobjType))
3500 return false;
3501
3502 QualType PointeeType;
3503 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3504 PointeeType = PT->getPointeeType();
3505 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003506 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003507 return false;
3508 }
3509
3510 LValue LVal;
3511 LVal.setFrom(Info.Ctx, Subobj);
3512 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3513 AccessKind == AK_Increment ? 1 : -1))
3514 return false;
3515 LVal.moveInto(Subobj);
3516 return true;
3517 }
3518 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3519 llvm_unreachable("shouldn't encounter string elements here");
3520 }
3521};
3522} // end anonymous namespace
3523
3524/// Perform an increment or decrement on LVal.
3525static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3526 QualType LValType, bool IsIncrement, APValue *Old) {
3527 if (LVal.Designator.Invalid)
3528 return false;
3529
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003530 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003531 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003532 return false;
3533 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003534
3535 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3536 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3537 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3538 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3539}
3540
Richard Smithe97cbd72011-11-11 04:05:33 +00003541/// Build an lvalue for the object argument of a member function call.
3542static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3543 LValue &This) {
3544 if (Object->getType()->isPointerType())
3545 return EvaluatePointer(Object, This, Info);
3546
3547 if (Object->isGLValue())
3548 return EvaluateLValue(Object, This, Info);
3549
Richard Smithd9f663b2013-04-22 15:31:51 +00003550 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003551 return EvaluateTemporary(Object, This, Info);
3552
Faisal Valie690b7a2016-07-02 22:34:24 +00003553 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003554 return false;
3555}
3556
3557/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3558/// lvalue referring to the result.
3559///
3560/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003561/// \param LV - An lvalue referring to the base of the member pointer.
3562/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003563/// \param IncludeMember - Specifies whether the member itself is included in
3564/// the resulting LValue subobject designator. This is not possible when
3565/// creating a bound member function.
3566/// \return The field or method declaration to which the member pointer refers,
3567/// or 0 if evaluation fails.
3568static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003569 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003570 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003571 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003572 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003573 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003574 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003575 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003576
3577 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3578 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003579 if (!MemPtr.getDecl()) {
3580 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003581 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003582 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003583 }
Richard Smith253c2a32012-01-27 01:14:48 +00003584
Richard Smith027bf112011-11-17 22:56:20 +00003585 if (MemPtr.isDerivedMember()) {
3586 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003587 // The end of the derived-to-base path for the base object must match the
3588 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003590 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003591 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003592 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003593 }
Richard Smith027bf112011-11-17 22:56:20 +00003594 unsigned PathLengthToMember =
3595 LV.Designator.Entries.size() - MemPtr.Path.size();
3596 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3597 const CXXRecordDecl *LVDecl = getAsBaseClass(
3598 LV.Designator.Entries[PathLengthToMember + I]);
3599 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003600 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003601 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003602 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003603 }
Richard Smith027bf112011-11-17 22:56:20 +00003604 }
3605
3606 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003607 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003608 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003609 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003610 } else if (!MemPtr.Path.empty()) {
3611 // Extend the LValue path with the member pointer's path.
3612 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3613 MemPtr.Path.size() + IncludeMember);
3614
3615 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003616 if (const PointerType *PT = LVType->getAs<PointerType>())
3617 LVType = PT->getPointeeType();
3618 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3619 assert(RD && "member pointer access on non-class-type expression");
3620 // The first class in the path is that of the lvalue.
3621 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3622 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003623 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003624 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003625 RD = Base;
3626 }
3627 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3629 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003630 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003631 }
3632
3633 // Add the member. Note that we cannot build bound member functions here.
3634 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003635 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003636 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003637 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003638 } else if (const IndirectFieldDecl *IFD =
3639 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003640 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003641 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003642 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003643 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003644 }
Richard Smith027bf112011-11-17 22:56:20 +00003645 }
3646
3647 return MemPtr.getDecl();
3648}
3649
Richard Smith84401042013-06-03 05:03:02 +00003650static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3651 const BinaryOperator *BO,
3652 LValue &LV,
3653 bool IncludeMember = true) {
3654 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3655
3656 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003657 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003658 MemberPtr MemPtr;
3659 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3660 }
Craig Topper36250ad2014-05-12 05:36:57 +00003661 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003662 }
3663
3664 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3665 BO->getRHS(), IncludeMember);
3666}
3667
Richard Smith027bf112011-11-17 22:56:20 +00003668/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3669/// the provided lvalue, which currently refers to the base object.
3670static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3671 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003672 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003673 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003674 return false;
3675
Richard Smitha8105bc2012-01-06 16:39:00 +00003676 QualType TargetQT = E->getType();
3677 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3678 TargetQT = PT->getPointeeType();
3679
3680 // Check this cast lands within the final derived-to-base subobject path.
3681 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003682 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003683 << D.MostDerivedType << TargetQT;
3684 return false;
3685 }
3686
Richard Smith027bf112011-11-17 22:56:20 +00003687 // Check the type of the final cast. We don't need to check the path,
3688 // since a cast can only be formed if the path is unique.
3689 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003690 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3691 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003692 if (NewEntriesSize == D.MostDerivedPathLength)
3693 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3694 else
Richard Smith027bf112011-11-17 22:56:20 +00003695 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003696 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003697 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003698 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003699 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003700 }
Richard Smith027bf112011-11-17 22:56:20 +00003701
3702 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003703 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003704}
3705
Mike Stump876387b2009-10-27 22:09:17 +00003706namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003707enum EvalStmtResult {
3708 /// Evaluation failed.
3709 ESR_Failed,
3710 /// Hit a 'return' statement.
3711 ESR_Returned,
3712 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003713 ESR_Succeeded,
3714 /// Hit a 'continue' statement.
3715 ESR_Continue,
3716 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003717 ESR_Break,
3718 /// Still scanning for 'case' or 'default' statement.
3719 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003720};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003721}
Richard Smith254a73d2011-10-28 22:34:42 +00003722
Richard Smith97fcf4b2016-08-14 23:15:52 +00003723static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3724 // We don't need to evaluate the initializer for a static local.
3725 if (!VD->hasLocalStorage())
3726 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003727
Richard Smith97fcf4b2016-08-14 23:15:52 +00003728 LValue Result;
3729 Result.set(VD, Info.CurrentCall->Index);
3730 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003731
Richard Smith97fcf4b2016-08-14 23:15:52 +00003732 const Expr *InitE = VD->getInit();
3733 if (!InitE) {
3734 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3735 << false << VD->getType();
3736 Val = APValue();
3737 return false;
3738 }
Richard Smith51f03172013-06-20 03:00:05 +00003739
Richard Smith97fcf4b2016-08-14 23:15:52 +00003740 if (InitE->isValueDependent())
3741 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003742
Richard Smith97fcf4b2016-08-14 23:15:52 +00003743 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3744 // Wipe out any partially-computed value, to allow tracking that this
3745 // evaluation failed.
3746 Val = APValue();
3747 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003748 }
3749
3750 return true;
3751}
3752
Richard Smith97fcf4b2016-08-14 23:15:52 +00003753static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3754 bool OK = true;
3755
3756 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3757 OK &= EvaluateVarDecl(Info, VD);
3758
3759 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3760 for (auto *BD : DD->bindings())
3761 if (auto *VD = BD->getHoldingVar())
3762 OK &= EvaluateDecl(Info, VD);
3763
3764 return OK;
3765}
3766
3767
Richard Smith4e18ca52013-05-06 05:56:11 +00003768/// Evaluate a condition (either a variable declaration or an expression).
3769static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3770 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003771 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003772 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3773 return false;
3774 return EvaluateAsBooleanCondition(Cond, Result, Info);
3775}
3776
Richard Smith89210072016-04-04 23:29:43 +00003777namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003778/// \brief A location where the result (returned value) of evaluating a
3779/// statement should be stored.
3780struct StmtResult {
3781 /// The APValue that should be filled in with the returned value.
3782 APValue &Value;
3783 /// The location containing the result, if any (used to support RVO).
3784 const LValue *Slot;
3785};
Richard Smith89210072016-04-04 23:29:43 +00003786}
Richard Smith52a980a2015-08-28 02:43:42 +00003787
3788static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003789 const Stmt *S,
3790 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003791
3792/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003793static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003794 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003795 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003796 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003797 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 case ESR_Break:
3799 return ESR_Succeeded;
3800 case ESR_Succeeded:
3801 case ESR_Continue:
3802 return ESR_Continue;
3803 case ESR_Failed:
3804 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003806 return ESR;
3807 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003808 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003809}
3810
Richard Smith496ddcf2013-05-12 17:32:42 +00003811/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003812static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003813 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003814 BlockScopeRAII Scope(Info);
3815
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003817 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003818 {
3819 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003820 if (const Stmt *Init = SS->getInit()) {
3821 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3822 if (ESR != ESR_Succeeded)
3823 return ESR;
3824 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003825 if (SS->getConditionVariable() &&
3826 !EvaluateDecl(Info, SS->getConditionVariable()))
3827 return ESR_Failed;
3828 if (!EvaluateInteger(SS->getCond(), Value, Info))
3829 return ESR_Failed;
3830 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003831
3832 // Find the switch case corresponding to the value of the condition.
3833 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003834 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003835 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3836 SC = SC->getNextSwitchCase()) {
3837 if (isa<DefaultStmt>(SC)) {
3838 Found = SC;
3839 continue;
3840 }
3841
3842 const CaseStmt *CS = cast<CaseStmt>(SC);
3843 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3844 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3845 : LHS;
3846 if (LHS <= Value && Value <= RHS) {
3847 Found = SC;
3848 break;
3849 }
3850 }
3851
3852 if (!Found)
3853 return ESR_Succeeded;
3854
3855 // Search the switch body for the switch case and evaluate it from there.
3856 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3857 case ESR_Break:
3858 return ESR_Succeeded;
3859 case ESR_Succeeded:
3860 case ESR_Continue:
3861 case ESR_Failed:
3862 case ESR_Returned:
3863 return ESR;
3864 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003865 // This can only happen if the switch case is nested within a statement
3866 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003867 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003868 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003869 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003870 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003871}
3872
Richard Smith254a73d2011-10-28 22:34:42 +00003873// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003874static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003875 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003876 if (!Info.nextStep(S))
3877 return ESR_Failed;
3878
Richard Smith496ddcf2013-05-12 17:32:42 +00003879 // If we're hunting down a 'case' or 'default' label, recurse through
3880 // substatements until we hit the label.
3881 if (Case) {
3882 // FIXME: We don't start the lifetime of objects whose initialization we
3883 // jump over. However, such objects must be of class type with a trivial
3884 // default constructor that initialize all subobjects, so must be empty,
3885 // so this almost never matters.
3886 switch (S->getStmtClass()) {
3887 case Stmt::CompoundStmtClass:
3888 // FIXME: Precompute which substatement of a compound statement we
3889 // would jump to, and go straight there rather than performing a
3890 // linear scan each time.
3891 case Stmt::LabelStmtClass:
3892 case Stmt::AttributedStmtClass:
3893 case Stmt::DoStmtClass:
3894 break;
3895
3896 case Stmt::CaseStmtClass:
3897 case Stmt::DefaultStmtClass:
3898 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003899 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003900 break;
3901
3902 case Stmt::IfStmtClass: {
3903 // FIXME: Precompute which side of an 'if' we would jump to, and go
3904 // straight there rather than scanning both sides.
3905 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003906
3907 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3908 // preceded by our switch label.
3909 BlockScopeRAII Scope(Info);
3910
Richard Smith496ddcf2013-05-12 17:32:42 +00003911 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3912 if (ESR != ESR_CaseNotFound || !IS->getElse())
3913 return ESR;
3914 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3915 }
3916
3917 case Stmt::WhileStmtClass: {
3918 EvalStmtResult ESR =
3919 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3920 if (ESR != ESR_Continue)
3921 return ESR;
3922 break;
3923 }
3924
3925 case Stmt::ForStmtClass: {
3926 const ForStmt *FS = cast<ForStmt>(S);
3927 EvalStmtResult ESR =
3928 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3929 if (ESR != ESR_Continue)
3930 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003931 if (FS->getInc()) {
3932 FullExpressionRAII IncScope(Info);
3933 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3934 return ESR_Failed;
3935 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003936 break;
3937 }
3938
3939 case Stmt::DeclStmtClass:
3940 // FIXME: If the variable has initialization that can't be jumped over,
3941 // bail out of any immediately-surrounding compound-statement too.
3942 default:
3943 return ESR_CaseNotFound;
3944 }
3945 }
3946
Richard Smith254a73d2011-10-28 22:34:42 +00003947 switch (S->getStmtClass()) {
3948 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003949 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003950 // Don't bother evaluating beyond an expression-statement which couldn't
3951 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003952 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003953 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003954 return ESR_Failed;
3955 return ESR_Succeeded;
3956 }
3957
Faisal Valie690b7a2016-07-02 22:34:24 +00003958 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003959 return ESR_Failed;
3960
3961 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003962 return ESR_Succeeded;
3963
Richard Smithd9f663b2013-04-22 15:31:51 +00003964 case Stmt::DeclStmtClass: {
3965 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003966 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 // Each declaration initialization is its own full-expression.
3968 // FIXME: This isn't quite right; if we're performing aggregate
3969 // initialization, each braced subexpression is its own full-expression.
3970 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003971 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003972 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003973 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003974 return ESR_Succeeded;
3975 }
3976
Richard Smith357362d2011-12-13 06:39:58 +00003977 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003978 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003980 if (RetExpr &&
3981 !(Result.Slot
3982 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3983 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003984 return ESR_Failed;
3985 return ESR_Returned;
3986 }
Richard Smith254a73d2011-10-28 22:34:42 +00003987
3988 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 BlockScopeRAII Scope(Info);
3990
Richard Smith254a73d2011-10-28 22:34:42 +00003991 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003992 for (const auto *BI : CS->body()) {
3993 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003994 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003995 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003996 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003997 return ESR;
3998 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003999 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004000 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004001
4002 case Stmt::IfStmtClass: {
4003 const IfStmt *IS = cast<IfStmt>(S);
4004
4005 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004007 if (const Stmt *Init = IS->getInit()) {
4008 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4009 if (ESR != ESR_Succeeded)
4010 return ESR;
4011 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004012 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004013 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004014 return ESR_Failed;
4015
4016 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4017 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4018 if (ESR != ESR_Succeeded)
4019 return ESR;
4020 }
4021 return ESR_Succeeded;
4022 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004023
4024 case Stmt::WhileStmtClass: {
4025 const WhileStmt *WS = cast<WhileStmt>(S);
4026 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004027 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 bool Continue;
4029 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4030 Continue))
4031 return ESR_Failed;
4032 if (!Continue)
4033 break;
4034
4035 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4036 if (ESR != ESR_Continue)
4037 return ESR;
4038 }
4039 return ESR_Succeeded;
4040 }
4041
4042 case Stmt::DoStmtClass: {
4043 const DoStmt *DS = cast<DoStmt>(S);
4044 bool Continue;
4045 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004046 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004047 if (ESR != ESR_Continue)
4048 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004049 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004050
Richard Smith08d6a2c2013-07-24 07:11:57 +00004051 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004052 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4053 return ESR_Failed;
4054 } while (Continue);
4055 return ESR_Succeeded;
4056 }
4057
4058 case Stmt::ForStmtClass: {
4059 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004060 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004061 if (FS->getInit()) {
4062 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4063 if (ESR != ESR_Succeeded)
4064 return ESR;
4065 }
4066 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004067 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004068 bool Continue = true;
4069 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4070 FS->getCond(), Continue))
4071 return ESR_Failed;
4072 if (!Continue)
4073 break;
4074
4075 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4076 if (ESR != ESR_Continue)
4077 return ESR;
4078
Richard Smith08d6a2c2013-07-24 07:11:57 +00004079 if (FS->getInc()) {
4080 FullExpressionRAII IncScope(Info);
4081 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4082 return ESR_Failed;
4083 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004084 }
4085 return ESR_Succeeded;
4086 }
4087
Richard Smith896e0d72013-05-06 06:51:17 +00004088 case Stmt::CXXForRangeStmtClass: {
4089 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004090 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004091
4092 // Initialize the __range variable.
4093 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4094 if (ESR != ESR_Succeeded)
4095 return ESR;
4096
4097 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004098 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4099 if (ESR != ESR_Succeeded)
4100 return ESR;
4101 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004102 if (ESR != ESR_Succeeded)
4103 return ESR;
4104
4105 while (true) {
4106 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004107 {
4108 bool Continue = true;
4109 FullExpressionRAII CondExpr(Info);
4110 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4111 return ESR_Failed;
4112 if (!Continue)
4113 break;
4114 }
Richard Smith896e0d72013-05-06 06:51:17 +00004115
4116 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004118 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4119 if (ESR != ESR_Succeeded)
4120 return ESR;
4121
4122 // Loop body.
4123 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4124 if (ESR != ESR_Continue)
4125 return ESR;
4126
4127 // Increment: ++__begin
4128 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4129 return ESR_Failed;
4130 }
4131
4132 return ESR_Succeeded;
4133 }
4134
Richard Smith496ddcf2013-05-12 17:32:42 +00004135 case Stmt::SwitchStmtClass:
4136 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4137
Richard Smith4e18ca52013-05-06 05:56:11 +00004138 case Stmt::ContinueStmtClass:
4139 return ESR_Continue;
4140
4141 case Stmt::BreakStmtClass:
4142 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004143
4144 case Stmt::LabelStmtClass:
4145 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4146
4147 case Stmt::AttributedStmtClass:
4148 // As a general principle, C++11 attributes can be ignored without
4149 // any semantic impact.
4150 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4151 Case);
4152
4153 case Stmt::CaseStmtClass:
4154 case Stmt::DefaultStmtClass:
4155 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004156 }
4157}
4158
Richard Smithcc36f692011-12-22 02:22:31 +00004159/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4160/// default constructor. If so, we'll fold it whether or not it's marked as
4161/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4162/// so we need special handling.
4163static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004164 const CXXConstructorDecl *CD,
4165 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004166 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4167 return false;
4168
Richard Smith66e05fe2012-01-18 05:21:49 +00004169 // Value-initialization does not call a trivial default constructor, so such a
4170 // call is a core constant expression whether or not the constructor is
4171 // constexpr.
4172 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004173 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004174 // FIXME: If DiagDecl is an implicitly-declared special member function,
4175 // we should be much more explicit about why it's not constexpr.
4176 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4177 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4178 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004179 } else {
4180 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4181 }
4182 }
4183 return true;
4184}
4185
Richard Smith357362d2011-12-13 06:39:58 +00004186/// CheckConstexprFunction - Check that a function can be called in a constant
4187/// expression.
4188static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4189 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004190 const FunctionDecl *Definition,
4191 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004192 // Potential constant expressions can contain calls to declared, but not yet
4193 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004194 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004195 Declaration->isConstexpr())
4196 return false;
4197
Richard Smith0838f3a2013-05-14 05:18:44 +00004198 // Bail out with no diagnostic if the function declaration itself is invalid.
4199 // We will have produced a relevant diagnostic while parsing it.
4200 if (Declaration->isInvalidDecl())
4201 return false;
4202
Richard Smith357362d2011-12-13 06:39:58 +00004203 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004204 if (Definition && Definition->isConstexpr() &&
4205 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004206 return true;
4207
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004208 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004209 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004210
Richard Smith5179eb72016-06-28 19:03:57 +00004211 // If this function is not constexpr because it is an inherited
4212 // non-constexpr constructor, diagnose that directly.
4213 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4214 if (CD && CD->isInheritingConstructor()) {
4215 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004216 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004217 DiagDecl = CD = Inherited;
4218 }
4219
4220 // FIXME: If DiagDecl is an implicitly-declared special member function
4221 // or an inheriting constructor, we should be much more explicit about why
4222 // it's not constexpr.
4223 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004224 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004225 << CD->getInheritedConstructor().getConstructor()->getParent();
4226 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004227 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004228 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004229 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4230 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004231 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004232 }
4233 return false;
4234}
4235
Richard Smithbe6dd812014-11-19 21:27:17 +00004236/// Determine if a class has any fields that might need to be copied by a
4237/// trivial copy or move operation.
4238static bool hasFields(const CXXRecordDecl *RD) {
4239 if (!RD || RD->isEmpty())
4240 return false;
4241 for (auto *FD : RD->fields()) {
4242 if (FD->isUnnamedBitfield())
4243 continue;
4244 return true;
4245 }
4246 for (auto &Base : RD->bases())
4247 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4248 return true;
4249 return false;
4250}
4251
Richard Smithd62306a2011-11-10 06:34:14 +00004252namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004253typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004254}
4255
4256/// EvaluateArgs - Evaluate the arguments to a function call.
4257static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4258 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004259 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004260 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004261 I != E; ++I) {
4262 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4263 // If we're checking for a potential constant expression, evaluate all
4264 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004265 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004266 return false;
4267 Success = false;
4268 }
4269 }
4270 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004271}
4272
Richard Smith254a73d2011-10-28 22:34:42 +00004273/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004274static bool HandleFunctionCall(SourceLocation CallLoc,
4275 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004276 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004277 EvalInfo &Info, APValue &Result,
4278 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004279 ArgVector ArgValues(Args.size());
4280 if (!EvaluateArgs(Args, ArgValues, Info))
4281 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004282
Richard Smith253c2a32012-01-27 01:14:48 +00004283 if (!Info.CheckCallLimit(CallLoc))
4284 return false;
4285
4286 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004287
4288 // For a trivial copy or move assignment, perform an APValue copy. This is
4289 // essential for unions, where the operations performed by the assignment
4290 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004291 //
4292 // Skip this for non-union classes with no fields; in that case, the defaulted
4293 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004294 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004295 if (MD && MD->isDefaulted() &&
4296 (MD->getParent()->isUnion() ||
4297 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004298 assert(This &&
4299 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4300 LValue RHS;
4301 RHS.setFrom(Info.Ctx, ArgValues[0]);
4302 APValue RHSValue;
4303 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4304 RHS, RHSValue))
4305 return false;
4306 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4307 RHSValue))
4308 return false;
4309 This->moveInto(Result);
4310 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004311 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004312 // We're in a lambda; determine the lambda capture field maps unless we're
4313 // just constexpr checking a lambda's call operator. constexpr checking is
4314 // done before the captures have been added to the closure object (unless
4315 // we're inferring constexpr-ness), so we don't have access to them in this
4316 // case. But since we don't need the captures to constexpr check, we can
4317 // just ignore them.
4318 if (!Info.checkingPotentialConstantExpression())
4319 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4320 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004321 }
4322
Richard Smith52a980a2015-08-28 02:43:42 +00004323 StmtResult Ret = {Result, ResultSlot};
4324 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004325 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004326 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004327 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004328 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004329 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004330 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004331}
4332
Richard Smithd62306a2011-11-10 06:34:14 +00004333/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004334static bool HandleConstructorCall(const Expr *E, const LValue &This,
4335 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004336 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004337 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004338 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004339 if (!Info.CheckCallLimit(CallLoc))
4340 return false;
4341
Richard Smith3607ffe2012-02-13 03:54:03 +00004342 const CXXRecordDecl *RD = Definition->getParent();
4343 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004344 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004345 return false;
4346 }
4347
Erik Pilkington42925492017-10-04 00:18:55 +00004348 EvalInfo::EvaluatingConstructorRAII EvalObj(
4349 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004350 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004351
Richard Smith52a980a2015-08-28 02:43:42 +00004352 // FIXME: Creating an APValue just to hold a nonexistent return value is
4353 // wasteful.
4354 APValue RetVal;
4355 StmtResult Ret = {RetVal, nullptr};
4356
Richard Smith5179eb72016-06-28 19:03:57 +00004357 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004358 if (Definition->isDelegatingConstructor()) {
4359 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004360 {
4361 FullExpressionRAII InitScope(Info);
4362 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4363 return false;
4364 }
Richard Smith52a980a2015-08-28 02:43:42 +00004365 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004366 }
4367
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004368 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004369 // essential for unions (or classes with anonymous union members), where the
4370 // operations performed by the constructor cannot be represented by
4371 // ctor-initializers.
4372 //
4373 // Skip this for empty non-union classes; we should not perform an
4374 // lvalue-to-rvalue conversion on them because their copy constructor does not
4375 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004376 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004377 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004378 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004379 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004380 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004381 return handleLValueToRValueConversion(
4382 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4383 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004384 }
4385
4386 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004387 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004388 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004389 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004390
John McCalld7bca762012-05-01 00:38:49 +00004391 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004392 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4393
Richard Smith08d6a2c2013-07-24 07:11:57 +00004394 // A scope for temporaries lifetime-extended by reference members.
4395 BlockScopeRAII LifetimeExtendedScope(Info);
4396
Richard Smith253c2a32012-01-27 01:14:48 +00004397 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004398 unsigned BasesSeen = 0;
4399#ifndef NDEBUG
4400 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4401#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004402 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004403 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004404 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004405 APValue *Value = &Result;
4406
4407 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004408 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004409 if (I->isBaseInitializer()) {
4410 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004411#ifndef NDEBUG
4412 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004413 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004414 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4415 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4416 "base class initializers not in expected order");
4417 ++BaseIt;
4418#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004419 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004420 BaseType->getAsCXXRecordDecl(), &Layout))
4421 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004422 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004423 } else if ((FD = I->getMember())) {
4424 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004425 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004426 if (RD->isUnion()) {
4427 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004428 Value = &Result.getUnionValue();
4429 } else {
4430 Value = &Result.getStructField(FD->getFieldIndex());
4431 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004432 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004433 // Walk the indirect field decl's chain to find the object to initialize,
4434 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004435 auto IndirectFieldChain = IFD->chain();
4436 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004437 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004438 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4439 // Switch the union field if it differs. This happens if we had
4440 // preceding zero-initialization, and we're now initializing a union
4441 // subobject other than the first.
4442 // FIXME: In this case, the values of the other subobjects are
4443 // specified, since zero-initialization sets all padding bits to zero.
4444 if (Value->isUninit() ||
4445 (Value->isUnion() && Value->getUnionField() != FD)) {
4446 if (CD->isUnion())
4447 *Value = APValue(FD);
4448 else
4449 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004450 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004451 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004452 // Store Subobject as its parent before updating it for the last element
4453 // in the chain.
4454 if (C == IndirectFieldChain.back())
4455 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004456 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004457 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004458 if (CD->isUnion())
4459 Value = &Value->getUnionValue();
4460 else
4461 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004462 }
Richard Smithd62306a2011-11-10 06:34:14 +00004463 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004464 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004465 }
Richard Smith253c2a32012-01-27 01:14:48 +00004466
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004467 // Need to override This for implicit field initializers as in this case
4468 // This refers to innermost anonymous struct/union containing initializer,
4469 // not to currently constructed class.
4470 const Expr *Init = I->getInit();
4471 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4472 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004473 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004474 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4475 (FD && FD->isBitField() &&
4476 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004477 // If we're checking for a potential constant expression, evaluate all
4478 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004479 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004480 return false;
4481 Success = false;
4482 }
Richard Smithd62306a2011-11-10 06:34:14 +00004483 }
4484
Richard Smithd9f663b2013-04-22 15:31:51 +00004485 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004486 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004487}
4488
Richard Smith5179eb72016-06-28 19:03:57 +00004489static bool HandleConstructorCall(const Expr *E, const LValue &This,
4490 ArrayRef<const Expr*> Args,
4491 const CXXConstructorDecl *Definition,
4492 EvalInfo &Info, APValue &Result) {
4493 ArgVector ArgValues(Args.size());
4494 if (!EvaluateArgs(Args, ArgValues, Info))
4495 return false;
4496
4497 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4498 Info, Result);
4499}
4500
Eli Friedman9a156e52008-11-12 09:44:48 +00004501//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004502// Generic Evaluation
4503//===----------------------------------------------------------------------===//
4504namespace {
4505
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004507class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004508 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004509private:
Richard Smith52a980a2015-08-28 02:43:42 +00004510 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004511 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004512 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004513 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004514 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004515 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004516 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004517
Richard Smith17100ba2012-02-16 02:46:34 +00004518 // Check whether a conditional operator with a non-constant condition is a
4519 // potential constant expression. If neither arm is a potential constant
4520 // expression, then the conditional operator is not either.
4521 template<typename ConditionalOperator>
4522 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004523 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004524
4525 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004526 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004527 {
Richard Smith17100ba2012-02-16 02:46:34 +00004528 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004529 StmtVisitorTy::Visit(E->getFalseExpr());
4530 if (Diag.empty())
4531 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004532 }
Richard Smith17100ba2012-02-16 02:46:34 +00004533
George Burgess IV8c892b52016-05-25 22:31:54 +00004534 {
4535 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004536 Diag.clear();
4537 StmtVisitorTy::Visit(E->getTrueExpr());
4538 if (Diag.empty())
4539 return;
4540 }
4541
4542 Error(E, diag::note_constexpr_conditional_never_const);
4543 }
4544
4545
4546 template<typename ConditionalOperator>
4547 bool HandleConditionalOperator(const ConditionalOperator *E) {
4548 bool BoolResult;
4549 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004550 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004551 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004552 return false;
4553 }
4554 if (Info.noteFailure()) {
4555 StmtVisitorTy::Visit(E->getTrueExpr());
4556 StmtVisitorTy::Visit(E->getFalseExpr());
4557 }
Richard Smith17100ba2012-02-16 02:46:34 +00004558 return false;
4559 }
4560
4561 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4562 return StmtVisitorTy::Visit(EvalExpr);
4563 }
4564
Peter Collingbournee9200682011-05-13 03:29:01 +00004565protected:
4566 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004567 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004568 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4569
Richard Smith92b1ce02011-12-12 09:28:41 +00004570 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004571 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004572 }
4573
Aaron Ballman68af21c2014-01-03 19:26:43 +00004574 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004575
4576public:
4577 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4578
4579 EvalInfo &getEvalInfo() { return Info; }
4580
Richard Smithf57d8cb2011-12-09 22:58:01 +00004581 /// Report an evaluation error. This should only be called when an error is
4582 /// first discovered. When propagating an error, just return false.
4583 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004584 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004585 return false;
4586 }
4587 bool Error(const Expr *E) {
4588 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4589 }
4590
Aaron Ballman68af21c2014-01-03 19:26:43 +00004591 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004592 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004595 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004596 }
4597
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004599 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004600 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004601 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004602 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004603 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004604 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004605 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004606 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004607 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004608 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004609 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004610 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004611 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004612 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004613 // The initializer may not have been parsed yet, or might be erroneous.
4614 if (!E->getExpr())
4615 return Error(E);
4616 return StmtVisitorTy::Visit(E->getExpr());
4617 }
Richard Smith5894a912011-12-19 22:12:41 +00004618 // We cannot create any objects for which cleanups are required, so there is
4619 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004620 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004621 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004622
Aaron Ballman68af21c2014-01-03 19:26:43 +00004623 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004624 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4625 return static_cast<Derived*>(this)->VisitCastExpr(E);
4626 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004627 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004628 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4629 return static_cast<Derived*>(this)->VisitCastExpr(E);
4630 }
4631
Aaron Ballman68af21c2014-01-03 19:26:43 +00004632 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004633 switch (E->getOpcode()) {
4634 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004635 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004636
4637 case BO_Comma:
4638 VisitIgnoredValue(E->getLHS());
4639 return StmtVisitorTy::Visit(E->getRHS());
4640
4641 case BO_PtrMemD:
4642 case BO_PtrMemI: {
4643 LValue Obj;
4644 if (!HandleMemberPointerAccess(Info, E, Obj))
4645 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004646 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004647 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004648 return false;
4649 return DerivedSuccess(Result, E);
4650 }
4651 }
4652 }
4653
Aaron Ballman68af21c2014-01-03 19:26:43 +00004654 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004655 // Evaluate and cache the common expression. We treat it as a temporary,
4656 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004657 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004658 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004659 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004660
Richard Smith17100ba2012-02-16 02:46:34 +00004661 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004662 }
4663
Aaron Ballman68af21c2014-01-03 19:26:43 +00004664 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004665 bool IsBcpCall = false;
4666 // If the condition (ignoring parens) is a __builtin_constant_p call,
4667 // the result is a constant expression if it can be folded without
4668 // side-effects. This is an important GNU extension. See GCC PR38377
4669 // for discussion.
4670 if (const CallExpr *CallCE =
4671 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004672 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004673 IsBcpCall = true;
4674
4675 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4676 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004677 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004678 return false;
4679
Richard Smith6d4c6582013-11-05 22:18:15 +00004680 FoldConstant Fold(Info, IsBcpCall);
4681 if (!HandleConditionalOperator(E)) {
4682 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004683 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004684 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004685
4686 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004687 }
4688
Aaron Ballman68af21c2014-01-03 19:26:43 +00004689 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004690 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4691 return DerivedSuccess(*Value, E);
4692
4693 const Expr *Source = E->getSourceExpr();
4694 if (!Source)
4695 return Error(E);
4696 if (Source == E) { // sanity checking.
4697 assert(0 && "OpaqueValueExpr recursively refers to itself");
4698 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004699 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004700 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004701 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004702
Aaron Ballman68af21c2014-01-03 19:26:43 +00004703 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004704 APValue Result;
4705 if (!handleCallExpr(E, Result, nullptr))
4706 return false;
4707 return DerivedSuccess(Result, E);
4708 }
4709
4710 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004711 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004712 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004713 QualType CalleeType = Callee->getType();
4714
Craig Topper36250ad2014-05-12 05:36:57 +00004715 const FunctionDecl *FD = nullptr;
4716 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004717 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004718 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004719
Richard Smithe97cbd72011-11-11 04:05:33 +00004720 // Extract function decl and 'this' pointer from the callee.
4721 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004722 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004723 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4724 // Explicit bound member calls, such as x.f() or p->g();
4725 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 return false;
4727 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004728 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004729 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004730 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4731 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004732 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4733 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004734 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004735 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004736 return Error(Callee);
4737
4738 FD = dyn_cast<FunctionDecl>(Member);
4739 if (!FD)
4740 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004741 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004742 LValue Call;
4743 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004744 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004745
Richard Smitha8105bc2012-01-06 16:39:00 +00004746 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004747 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004748 FD = dyn_cast_or_null<FunctionDecl>(
4749 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004750 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004751 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004752 // Don't call function pointers which have been cast to some other type.
4753 // Per DR (no number yet), the caller and callee can differ in noexcept.
4754 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4755 CalleeType->getPointeeType(), FD->getType())) {
4756 return Error(E);
4757 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004758
4759 // Overloaded operator calls to member functions are represented as normal
4760 // calls with '*this' as the first argument.
4761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4762 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004763 // FIXME: When selecting an implicit conversion for an overloaded
4764 // operator delete, we sometimes try to evaluate calls to conversion
4765 // operators without a 'this' parameter!
4766 if (Args.empty())
4767 return Error(E);
4768
Nick Lewycky13073a62017-06-12 21:15:44 +00004769 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004770 return false;
4771 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004772 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004773 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004774 // Map the static invoker for the lambda back to the call operator.
4775 // Conveniently, we don't have to slice out the 'this' argument (as is
4776 // being done for the non-static case), since a static member function
4777 // doesn't have an implicit argument passed in.
4778 const CXXRecordDecl *ClosureClass = MD->getParent();
4779 assert(
4780 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4781 "Number of captures must be zero for conversion to function-ptr");
4782
4783 const CXXMethodDecl *LambdaCallOp =
4784 ClosureClass->getLambdaCallOperator();
4785
4786 // Set 'FD', the function that will be called below, to the call
4787 // operator. If the closure object represents a generic lambda, find
4788 // the corresponding specialization of the call operator.
4789
4790 if (ClosureClass->isGenericLambda()) {
4791 assert(MD->isFunctionTemplateSpecialization() &&
4792 "A generic lambda's static-invoker function must be a "
4793 "template specialization");
4794 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4795 FunctionTemplateDecl *CallOpTemplate =
4796 LambdaCallOp->getDescribedFunctionTemplate();
4797 void *InsertPos = nullptr;
4798 FunctionDecl *CorrespondingCallOpSpecialization =
4799 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4800 assert(CorrespondingCallOpSpecialization &&
4801 "We must always have a function call operator specialization "
4802 "that corresponds to our static invoker specialization");
4803 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4804 } else
4805 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004806 }
4807
Daniel Jasperffdee092017-05-02 19:21:42 +00004808
Richard Smithe97cbd72011-11-11 04:05:33 +00004809 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004810 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004811
Richard Smith47b34932012-02-01 02:39:43 +00004812 if (This && !This->checkSubobject(Info, E, CSK_This))
4813 return false;
4814
Richard Smith3607ffe2012-02-13 03:54:03 +00004815 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4816 // calls to such functions in constant expressions.
4817 if (This && !HasQualifier &&
4818 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4819 return Error(E, diag::note_constexpr_virtual_call);
4820
Craig Topper36250ad2014-05-12 05:36:57 +00004821 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004822 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004823
Nick Lewycky13073a62017-06-12 21:15:44 +00004824 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4825 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004826 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004827 return false;
4828
Richard Smith52a980a2015-08-28 02:43:42 +00004829 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004830 }
4831
Aaron Ballman68af21c2014-01-03 19:26:43 +00004832 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004833 return StmtVisitorTy::Visit(E->getInitializer());
4834 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004836 if (E->getNumInits() == 0)
4837 return DerivedZeroInitialization(E);
4838 if (E->getNumInits() == 1)
4839 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004840 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004841 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004842 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004843 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004844 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004845 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004846 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004847 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004848 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004849 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004850 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004851
Richard Smithd62306a2011-11-10 06:34:14 +00004852 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004853 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004854 assert(!E->isArrow() && "missing call to bound member function?");
4855
Richard Smith2e312c82012-03-03 22:46:17 +00004856 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004857 if (!Evaluate(Val, Info, E->getBase()))
4858 return false;
4859
4860 QualType BaseTy = E->getBase()->getType();
4861
4862 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004863 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004864 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004865 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004866 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4867
Richard Smith9defb7d2018-02-21 03:38:30 +00004868 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004869 SubobjectDesignator Designator(BaseTy);
4870 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004871
Richard Smith3229b742013-05-05 21:17:10 +00004872 APValue Result;
4873 return extractSubobject(Info, E, Obj, Designator, Result) &&
4874 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004875 }
4876
Aaron Ballman68af21c2014-01-03 19:26:43 +00004877 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004878 switch (E->getCastKind()) {
4879 default:
4880 break;
4881
Richard Smitha23ab512013-05-23 00:30:41 +00004882 case CK_AtomicToNonAtomic: {
4883 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004884 // This does not need to be done in place even for class/array types:
4885 // atomic-to-non-atomic conversion implies copying the object
4886 // representation.
4887 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004888 return false;
4889 return DerivedSuccess(AtomicVal, E);
4890 }
4891
Richard Smith11562c52011-10-28 17:51:58 +00004892 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004893 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004894 return StmtVisitorTy::Visit(E->getSubExpr());
4895
4896 case CK_LValueToRValue: {
4897 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004898 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4899 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004900 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004901 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004902 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004903 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004904 return false;
4905 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004906 }
4907 }
4908
Richard Smithf57d8cb2011-12-09 22:58:01 +00004909 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004910 }
4911
Aaron Ballman68af21c2014-01-03 19:26:43 +00004912 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004913 return VisitUnaryPostIncDec(UO);
4914 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004915 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004916 return VisitUnaryPostIncDec(UO);
4917 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004919 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004920 return Error(UO);
4921
4922 LValue LVal;
4923 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4924 return false;
4925 APValue RVal;
4926 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4927 UO->isIncrementOp(), &RVal))
4928 return false;
4929 return DerivedSuccess(RVal, UO);
4930 }
4931
Aaron Ballman68af21c2014-01-03 19:26:43 +00004932 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004933 // We will have checked the full-expressions inside the statement expression
4934 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004935 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004936 return Error(E);
4937
Richard Smith08d6a2c2013-07-24 07:11:57 +00004938 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004939 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004940 if (CS->body_empty())
4941 return true;
4942
Richard Smith51f03172013-06-20 03:00:05 +00004943 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4944 BE = CS->body_end();
4945 /**/; ++BI) {
4946 if (BI + 1 == BE) {
4947 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4948 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004949 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004950 diag::note_constexpr_stmt_expr_unsupported);
4951 return false;
4952 }
4953 return this->Visit(FinalExpr);
4954 }
4955
4956 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004957 StmtResult Result = { ReturnValue, nullptr };
4958 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004959 if (ESR != ESR_Succeeded) {
4960 // FIXME: If the statement-expression terminated due to 'return',
4961 // 'break', or 'continue', it would be nice to propagate that to
4962 // the outer statement evaluation rather than bailing out.
4963 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004964 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004965 diag::note_constexpr_stmt_expr_unsupported);
4966 return false;
4967 }
4968 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004969
4970 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004971 }
4972
Richard Smith4a678122011-10-24 18:44:57 +00004973 /// Visit a value which is evaluated, but whose value is ignored.
4974 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004975 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004976 }
David Majnemere9807b22016-02-26 04:23:19 +00004977
4978 /// Potentially visit a MemberExpr's base expression.
4979 void VisitIgnoredBaseExpression(const Expr *E) {
4980 // While MSVC doesn't evaluate the base expression, it does diagnose the
4981 // presence of side-effecting behavior.
4982 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4983 return;
4984 VisitIgnoredValue(E);
4985 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004986};
4987
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004988}
Peter Collingbournee9200682011-05-13 03:29:01 +00004989
4990//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004991// Common base class for lvalue and temporary evaluation.
4992//===----------------------------------------------------------------------===//
4993namespace {
4994template<class Derived>
4995class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004996 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004997protected:
4998 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004999 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005000 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005001 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005002
5003 bool Success(APValue::LValueBase B) {
5004 Result.set(B);
5005 return true;
5006 }
5007
George Burgess IVf9013bf2017-02-10 22:52:29 +00005008 bool evaluatePointer(const Expr *E, LValue &Result) {
5009 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5010 }
5011
Richard Smith027bf112011-11-17 22:56:20 +00005012public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005013 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5014 : ExprEvaluatorBaseTy(Info), Result(Result),
5015 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005016
Richard Smith2e312c82012-03-03 22:46:17 +00005017 bool Success(const APValue &V, const Expr *E) {
5018 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005019 return true;
5020 }
Richard Smith027bf112011-11-17 22:56:20 +00005021
Richard Smith027bf112011-11-17 22:56:20 +00005022 bool VisitMemberExpr(const MemberExpr *E) {
5023 // Handle non-static data members.
5024 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005025 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005026 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005027 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005028 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005029 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005030 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005031 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005032 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005033 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005034 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005035 BaseTy = E->getBase()->getType();
5036 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005037 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005038 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005039 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005040 Result.setInvalid(E);
5041 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005042 }
Richard Smith027bf112011-11-17 22:56:20 +00005043
Richard Smith1b78b3d2012-01-25 22:15:11 +00005044 const ValueDecl *MD = E->getMemberDecl();
5045 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5046 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5047 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5048 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005049 if (!HandleLValueMember(this->Info, E, Result, FD))
5050 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005051 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005052 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5053 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005054 } else
5055 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005056
Richard Smith1b78b3d2012-01-25 22:15:11 +00005057 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005058 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005059 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005060 RefValue))
5061 return false;
5062 return Success(RefValue, E);
5063 }
5064 return true;
5065 }
5066
5067 bool VisitBinaryOperator(const BinaryOperator *E) {
5068 switch (E->getOpcode()) {
5069 default:
5070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5071
5072 case BO_PtrMemD:
5073 case BO_PtrMemI:
5074 return HandleMemberPointerAccess(this->Info, E, Result);
5075 }
5076 }
5077
5078 bool VisitCastExpr(const CastExpr *E) {
5079 switch (E->getCastKind()) {
5080 default:
5081 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5082
5083 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005084 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005085 if (!this->Visit(E->getSubExpr()))
5086 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005087
5088 // Now figure out the necessary offset to add to the base LV to get from
5089 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005090 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5091 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005092 }
5093 }
5094};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005095}
Richard Smith027bf112011-11-17 22:56:20 +00005096
5097//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005098// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005099//
5100// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5101// function designators (in C), decl references to void objects (in C), and
5102// temporaries (if building with -Wno-address-of-temporary).
5103//
5104// LValue evaluation produces values comprising a base expression of one of the
5105// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005106// - Declarations
5107// * VarDecl
5108// * FunctionDecl
5109// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005110// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005111// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005112// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005113// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005114// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005115// * ObjCEncodeExpr
5116// * AddrLabelExpr
5117// * BlockExpr
5118// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005119// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005120// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005121// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005122// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5123// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005124// * A MaterializeTemporaryExpr that has static storage duration, with no
5125// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005126// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005127//===----------------------------------------------------------------------===//
5128namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005129class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005130 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005131public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005132 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5133 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005134
Richard Smith11562c52011-10-28 17:51:58 +00005135 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005136 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005137
Peter Collingbournee9200682011-05-13 03:29:01 +00005138 bool VisitDeclRefExpr(const DeclRefExpr *E);
5139 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005140 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005141 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5142 bool VisitMemberExpr(const MemberExpr *E);
5143 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5144 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005145 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005146 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005147 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5148 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005149 bool VisitUnaryReal(const UnaryOperator *E);
5150 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005151 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5152 return VisitUnaryPreIncDec(UO);
5153 }
5154 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5155 return VisitUnaryPreIncDec(UO);
5156 }
Richard Smith3229b742013-05-05 21:17:10 +00005157 bool VisitBinAssign(const BinaryOperator *BO);
5158 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005159
Peter Collingbournee9200682011-05-13 03:29:01 +00005160 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005161 switch (E->getCastKind()) {
5162 default:
Richard Smith027bf112011-11-17 22:56:20 +00005163 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005164
Eli Friedmance3e02a2011-10-11 00:13:24 +00005165 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005166 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005167 if (!Visit(E->getSubExpr()))
5168 return false;
5169 Result.Designator.setInvalid();
5170 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005171
Richard Smith027bf112011-11-17 22:56:20 +00005172 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005173 if (!Visit(E->getSubExpr()))
5174 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005175 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005176 }
5177 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005178};
5179} // end anonymous namespace
5180
Richard Smith11562c52011-10-28 17:51:58 +00005181/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005182/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005183/// * function designators in C, and
5184/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005185/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005186static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5187 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005188 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005189 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005190 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005191}
5192
Peter Collingbournee9200682011-05-13 03:29:01 +00005193bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005194 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005195 return Success(FD);
5196 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005197 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005198 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005199 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005200 return Error(E);
5201}
Richard Smith733237d2011-10-24 23:14:33 +00005202
Faisal Vali0528a312016-11-13 06:09:16 +00005203
Richard Smith11562c52011-10-28 17:51:58 +00005204bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005205
5206 // If we are within a lambda's call operator, check whether the 'VD' referred
5207 // to within 'E' actually represents a lambda-capture that maps to a
5208 // data-member/field within the closure object, and if so, evaluate to the
5209 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005210 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5211 isa<DeclRefExpr>(E) &&
5212 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5213 // We don't always have a complete capture-map when checking or inferring if
5214 // the function call operator meets the requirements of a constexpr function
5215 // - but we don't need to evaluate the captures to determine constexprness
5216 // (dcl.constexpr C++17).
5217 if (Info.checkingPotentialConstantExpression())
5218 return false;
5219
Faisal Vali051e3a22017-02-16 04:12:21 +00005220 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005221 // Start with 'Result' referring to the complete closure object...
5222 Result = *Info.CurrentCall->This;
5223 // ... then update it to refer to the field of the closure object
5224 // that represents the capture.
5225 if (!HandleLValueMember(Info, E, Result, FD))
5226 return false;
5227 // And if the field is of reference type, update 'Result' to refer to what
5228 // the field refers to.
5229 if (FD->getType()->isReferenceType()) {
5230 APValue RVal;
5231 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5232 RVal))
5233 return false;
5234 Result.setFrom(Info.Ctx, RVal);
5235 }
5236 return true;
5237 }
5238 }
Craig Topper36250ad2014-05-12 05:36:57 +00005239 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005240 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5241 // Only if a local variable was declared in the function currently being
5242 // evaluated, do we expect to be able to find its value in the current
5243 // frame. (Otherwise it was likely declared in an enclosing context and
5244 // could either have a valid evaluatable value (for e.g. a constexpr
5245 // variable) or be ill-formed (and trigger an appropriate evaluation
5246 // diagnostic)).
5247 if (Info.CurrentCall->Callee &&
5248 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5249 Frame = Info.CurrentCall;
5250 }
5251 }
Richard Smith3229b742013-05-05 21:17:10 +00005252
Richard Smithfec09922011-11-01 16:57:24 +00005253 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005254 if (Frame) {
5255 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005256 return true;
5257 }
Richard Smithce40ad62011-11-12 22:28:03 +00005258 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005259 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005260
Richard Smith3229b742013-05-05 21:17:10 +00005261 APValue *V;
5262 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005263 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005264 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005265 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005266 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005267 return false;
5268 }
Richard Smith3229b742013-05-05 21:17:10 +00005269 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005270}
5271
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005272bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5273 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005274 // Walk through the expression to find the materialized temporary itself.
5275 SmallVector<const Expr *, 2> CommaLHSs;
5276 SmallVector<SubobjectAdjustment, 2> Adjustments;
5277 const Expr *Inner = E->GetTemporaryExpr()->
5278 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005279
Richard Smith84401042013-06-03 05:03:02 +00005280 // If we passed any comma operators, evaluate their LHSs.
5281 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5282 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5283 return false;
5284
Richard Smithe6c01442013-06-05 00:46:14 +00005285 // A materialized temporary with static storage duration can appear within the
5286 // result of a constant expression evaluation, so we need to preserve its
5287 // value for use outside this evaluation.
5288 APValue *Value;
5289 if (E->getStorageDuration() == SD_Static) {
5290 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005291 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005292 Result.set(E);
5293 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005294 Value = &Info.CurrentCall->
5295 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005296 Result.set(E, Info.CurrentCall->Index);
5297 }
5298
Richard Smithea4ad5d2013-06-06 08:19:16 +00005299 QualType Type = Inner->getType();
5300
Richard Smith84401042013-06-03 05:03:02 +00005301 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005302 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5303 (E->getStorageDuration() == SD_Static &&
5304 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5305 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005306 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005307 }
Richard Smith84401042013-06-03 05:03:02 +00005308
5309 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005310 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5311 --I;
5312 switch (Adjustments[I].Kind) {
5313 case SubobjectAdjustment::DerivedToBaseAdjustment:
5314 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5315 Type, Result))
5316 return false;
5317 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5318 break;
5319
5320 case SubobjectAdjustment::FieldAdjustment:
5321 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5322 return false;
5323 Type = Adjustments[I].Field->getType();
5324 break;
5325
5326 case SubobjectAdjustment::MemberPointerAdjustment:
5327 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5328 Adjustments[I].Ptr.RHS))
5329 return false;
5330 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5331 break;
5332 }
5333 }
5334
5335 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005336}
5337
Peter Collingbournee9200682011-05-13 03:29:01 +00005338bool
5339LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005340 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5341 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005342 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5343 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005344 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005345}
5346
Richard Smith6e525142011-12-27 12:18:28 +00005347bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005348 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005349 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005350
Faisal Valie690b7a2016-07-02 22:34:24 +00005351 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005352 << E->getExprOperand()->getType()
5353 << E->getExprOperand()->getSourceRange();
5354 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005355}
5356
Francois Pichet0066db92012-04-16 04:08:35 +00005357bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5358 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005359}
Francois Pichet0066db92012-04-16 04:08:35 +00005360
Peter Collingbournee9200682011-05-13 03:29:01 +00005361bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005362 // Handle static data members.
5363 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005364 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005365 return VisitVarDecl(E, VD);
5366 }
5367
Richard Smith254a73d2011-10-28 22:34:42 +00005368 // Handle static member functions.
5369 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5370 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005371 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005372 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005373 }
5374 }
5375
Richard Smithd62306a2011-11-10 06:34:14 +00005376 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005377 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005378}
5379
Peter Collingbournee9200682011-05-13 03:29:01 +00005380bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005381 // FIXME: Deal with vectors as array subscript bases.
5382 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005383 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005384
Nick Lewyckyad888682017-04-27 07:27:36 +00005385 bool Success = true;
5386 if (!evaluatePointer(E->getBase(), Result)) {
5387 if (!Info.noteFailure())
5388 return false;
5389 Success = false;
5390 }
Mike Stump11289f42009-09-09 15:08:12 +00005391
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005392 APSInt Index;
5393 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005394 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005395
Nick Lewyckyad888682017-04-27 07:27:36 +00005396 return Success &&
5397 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005398}
Eli Friedman9a156e52008-11-12 09:44:48 +00005399
Peter Collingbournee9200682011-05-13 03:29:01 +00005400bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005401 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005402}
5403
Richard Smith66c96992012-02-18 22:04:06 +00005404bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5405 if (!Visit(E->getSubExpr()))
5406 return false;
5407 // __real is a no-op on scalar lvalues.
5408 if (E->getSubExpr()->getType()->isAnyComplexType())
5409 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5410 return true;
5411}
5412
5413bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5414 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5415 "lvalue __imag__ on scalar?");
5416 if (!Visit(E->getSubExpr()))
5417 return false;
5418 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5419 return true;
5420}
5421
Richard Smith243ef902013-05-05 23:31:59 +00005422bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005423 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005424 return Error(UO);
5425
5426 if (!this->Visit(UO->getSubExpr()))
5427 return false;
5428
Richard Smith243ef902013-05-05 23:31:59 +00005429 return handleIncDec(
5430 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005431 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005432}
5433
5434bool LValueExprEvaluator::VisitCompoundAssignOperator(
5435 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005436 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005437 return Error(CAO);
5438
Richard Smith3229b742013-05-05 21:17:10 +00005439 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005440
5441 // The overall lvalue result is the result of evaluating the LHS.
5442 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005443 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005444 Evaluate(RHS, this->Info, CAO->getRHS());
5445 return false;
5446 }
5447
Richard Smith3229b742013-05-05 21:17:10 +00005448 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5449 return false;
5450
Richard Smith43e77732013-05-07 04:50:00 +00005451 return handleCompoundAssignment(
5452 this->Info, CAO,
5453 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5454 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005455}
5456
5457bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005458 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005459 return Error(E);
5460
Richard Smith3229b742013-05-05 21:17:10 +00005461 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005462
5463 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005464 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005465 Evaluate(NewVal, this->Info, E->getRHS());
5466 return false;
5467 }
5468
Richard Smith3229b742013-05-05 21:17:10 +00005469 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5470 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005471
5472 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005473 NewVal);
5474}
5475
Eli Friedman9a156e52008-11-12 09:44:48 +00005476//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005477// Pointer Evaluation
5478//===----------------------------------------------------------------------===//
5479
George Burgess IVe3763372016-12-22 02:50:20 +00005480/// \brief Attempts to compute the number of bytes available at the pointer
5481/// returned by a function with the alloc_size attribute. Returns true if we
5482/// were successful. Places an unsigned number into `Result`.
5483///
5484/// This expects the given CallExpr to be a call to a function with an
5485/// alloc_size attribute.
5486static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5487 const CallExpr *Call,
5488 llvm::APInt &Result) {
5489 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5490
Joel E. Denny81508102018-03-13 14:51:22 +00005491 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5492 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005493 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5494 if (Call->getNumArgs() <= SizeArgNo)
5495 return false;
5496
5497 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5498 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5499 return false;
5500 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5501 return false;
5502 Into = Into.zextOrSelf(BitsInSizeT);
5503 return true;
5504 };
5505
5506 APSInt SizeOfElem;
5507 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5508 return false;
5509
Joel E. Denny81508102018-03-13 14:51:22 +00005510 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005511 Result = std::move(SizeOfElem);
5512 return true;
5513 }
5514
5515 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005516 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005517 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5518 return false;
5519
5520 bool Overflow;
5521 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5522 if (Overflow)
5523 return false;
5524
5525 Result = std::move(BytesAvailable);
5526 return true;
5527}
5528
5529/// \brief Convenience function. LVal's base must be a call to an alloc_size
5530/// function.
5531static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5532 const LValue &LVal,
5533 llvm::APInt &Result) {
5534 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5535 "Can't get the size of a non alloc_size function");
5536 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5537 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5538 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5539}
5540
5541/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5542/// a function with the alloc_size attribute. If it was possible to do so, this
5543/// function will return true, make Result's Base point to said function call,
5544/// and mark Result's Base as invalid.
5545static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5546 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005547 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005548 return false;
5549
5550 // Because we do no form of static analysis, we only support const variables.
5551 //
5552 // Additionally, we can't support parameters, nor can we support static
5553 // variables (in the latter case, use-before-assign isn't UB; in the former,
5554 // we have no clue what they'll be assigned to).
5555 const auto *VD =
5556 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5557 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5558 return false;
5559
5560 const Expr *Init = VD->getAnyInitializer();
5561 if (!Init)
5562 return false;
5563
5564 const Expr *E = Init->IgnoreParens();
5565 if (!tryUnwrapAllocSizeCall(E))
5566 return false;
5567
5568 // Store E instead of E unwrapped so that the type of the LValue's base is
5569 // what the user wanted.
5570 Result.setInvalid(E);
5571
5572 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005573 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005574 return true;
5575}
5576
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005577namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005578class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005579 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005580 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005581 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005582
Peter Collingbournee9200682011-05-13 03:29:01 +00005583 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005584 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005585 return true;
5586 }
George Burgess IVe3763372016-12-22 02:50:20 +00005587
George Burgess IVf9013bf2017-02-10 22:52:29 +00005588 bool evaluateLValue(const Expr *E, LValue &Result) {
5589 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5590 }
5591
5592 bool evaluatePointer(const Expr *E, LValue &Result) {
5593 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5594 }
5595
George Burgess IVe3763372016-12-22 02:50:20 +00005596 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005597public:
Mike Stump11289f42009-09-09 15:08:12 +00005598
George Burgess IVf9013bf2017-02-10 22:52:29 +00005599 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5600 : ExprEvaluatorBaseTy(info), Result(Result),
5601 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005602
Richard Smith2e312c82012-03-03 22:46:17 +00005603 bool Success(const APValue &V, const Expr *E) {
5604 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005605 return true;
5606 }
Richard Smithfddd3842011-12-30 21:15:51 +00005607 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005608 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5609 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005610 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005611 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005612
John McCall45d55e42010-05-07 21:00:08 +00005613 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005614 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005615 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005616 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005617 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005618 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5619 if (Info.noteFailure())
5620 EvaluateIgnoredValue(Info, E->getSubExpr());
5621 return Error(E);
5622 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005623 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005624 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005625 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005626 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005627 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005628 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005629 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005630 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005631 }
Richard Smithd62306a2011-11-10 06:34:14 +00005632 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005633 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005634 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005635 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005636 if (!Info.CurrentCall->This) {
5637 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005638 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005639 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005640 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005641 return false;
5642 }
Richard Smithd62306a2011-11-10 06:34:14 +00005643 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005644 // If we are inside a lambda's call operator, the 'this' expression refers
5645 // to the enclosing '*this' object (either by value or reference) which is
5646 // either copied into the closure object's field that represents the '*this'
5647 // or refers to '*this'.
5648 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5649 // Update 'Result' to refer to the data member/field of the closure object
5650 // that represents the '*this' capture.
5651 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005652 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005653 return false;
5654 // If we captured '*this' by reference, replace the field with its referent.
5655 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5656 ->isPointerType()) {
5657 APValue RVal;
5658 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5659 RVal))
5660 return false;
5661
5662 Result.setFrom(Info.Ctx, RVal);
5663 }
5664 }
Richard Smithd62306a2011-11-10 06:34:14 +00005665 return true;
5666 }
John McCallc07a0c72011-02-17 10:25:35 +00005667
Eli Friedman449fe542009-03-23 04:56:01 +00005668 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005669};
Chris Lattner05706e882008-07-11 18:11:29 +00005670} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005671
George Burgess IVf9013bf2017-02-10 22:52:29 +00005672static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5673 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005674 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005675 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005676}
5677
John McCall45d55e42010-05-07 21:00:08 +00005678bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005679 if (E->getOpcode() != BO_Add &&
5680 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005682
Chris Lattner05706e882008-07-11 18:11:29 +00005683 const Expr *PExp = E->getLHS();
5684 const Expr *IExp = E->getRHS();
5685 if (IExp->getType()->isPointerType())
5686 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005687
George Burgess IVf9013bf2017-02-10 22:52:29 +00005688 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005689 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005690 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005691
John McCall45d55e42010-05-07 21:00:08 +00005692 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005693 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005694 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005695
Richard Smith96e0c102011-11-04 02:25:55 +00005696 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005697 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005698
Ted Kremenek28831752012-08-23 20:46:57 +00005699 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005700 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005701}
Eli Friedman9a156e52008-11-12 09:44:48 +00005702
John McCall45d55e42010-05-07 21:00:08 +00005703bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005704 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005705}
Mike Stump11289f42009-09-09 15:08:12 +00005706
Peter Collingbournee9200682011-05-13 03:29:01 +00005707bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5708 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005709
Eli Friedman847a2bc2009-12-27 05:43:15 +00005710 switch (E->getCastKind()) {
5711 default:
5712 break;
5713
John McCalle3027922010-08-25 11:45:40 +00005714 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005715 case CK_CPointerToObjCPointerCast:
5716 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005717 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005718 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005719 if (!Visit(SubExpr))
5720 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005721 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5722 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5723 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005724 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005725 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005726 if (SubExpr->getType()->isVoidPointerType())
5727 CCEDiag(E, diag::note_constexpr_invalid_cast)
5728 << 3 << SubExpr->getType();
5729 else
5730 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5731 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005732 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5733 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005734 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005735
Anders Carlsson18275092010-10-31 20:41:46 +00005736 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005737 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005738 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005739 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005740 if (!Result.Base && Result.Offset.isZero())
5741 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005742
Richard Smithd62306a2011-11-10 06:34:14 +00005743 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005744 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005745 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5746 castAs<PointerType>()->getPointeeType(),
5747 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005748
Richard Smith027bf112011-11-17 22:56:20 +00005749 case CK_BaseToDerived:
5750 if (!Visit(E->getSubExpr()))
5751 return false;
5752 if (!Result.Base && Result.Offset.isZero())
5753 return true;
5754 return HandleBaseToDerivedCast(Info, E, Result);
5755
Richard Smith0b0a0b62011-10-29 20:57:55 +00005756 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005757 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005758 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005759
John McCalle3027922010-08-25 11:45:40 +00005760 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005761 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5762
Richard Smith2e312c82012-03-03 22:46:17 +00005763 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005764 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005765 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005766
John McCall45d55e42010-05-07 21:00:08 +00005767 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005768 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5769 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005770 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005771 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005772 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005773 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005774 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005775 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005776 return true;
5777 } else {
5778 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005779 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005780 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005781 }
5782 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005783
5784 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005785 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005786 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005787 return false;
5788 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005789 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005790 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005791 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005792 return false;
5793 }
Richard Smith96e0c102011-11-04 02:25:55 +00005794 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005795 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5796 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005797 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005798 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005799 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005800 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005801 }
Richard Smithdd785442011-10-31 20:57:44 +00005802
John McCalle3027922010-08-25 11:45:40 +00005803 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005804 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005805
5806 case CK_LValueToRValue: {
5807 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005808 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005809 return false;
5810
5811 APValue RVal;
5812 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5813 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5814 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005815 return InvalidBaseOK &&
5816 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005817 return Success(RVal, E);
5818 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005819 }
5820
Richard Smith11562c52011-10-28 17:51:58 +00005821 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005822}
Chris Lattner05706e882008-07-11 18:11:29 +00005823
Hal Finkel0dd05d42014-10-03 17:18:37 +00005824static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5825 // C++ [expr.alignof]p3:
5826 // When alignof is applied to a reference type, the result is the
5827 // alignment of the referenced type.
5828 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5829 T = Ref->getPointeeType();
5830
5831 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005832 if (T.getQualifiers().hasUnaligned())
5833 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005834 return Info.Ctx.toCharUnitsFromBits(
5835 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5836}
5837
5838static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5839 E = E->IgnoreParens();
5840
5841 // The kinds of expressions that we have special-case logic here for
5842 // should be kept up to date with the special checks for those
5843 // expressions in Sema.
5844
5845 // alignof decl is always accepted, even if it doesn't make sense: we default
5846 // to 1 in those cases.
5847 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5848 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5849 /*RefAsPointee*/true);
5850
5851 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5852 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5853 /*RefAsPointee*/true);
5854
5855 return GetAlignOfType(Info, E->getType());
5856}
5857
George Burgess IVe3763372016-12-22 02:50:20 +00005858// To be clear: this happily visits unsupported builtins. Better name welcomed.
5859bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5860 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5861 return true;
5862
George Burgess IVf9013bf2017-02-10 22:52:29 +00005863 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005864 return false;
5865
5866 Result.setInvalid(E);
5867 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005868 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005869 return true;
5870}
5871
Peter Collingbournee9200682011-05-13 03:29:01 +00005872bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005873 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005874 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005875
Richard Smith6328cbd2016-11-16 00:57:23 +00005876 if (unsigned BuiltinOp = E->getBuiltinCallee())
5877 return VisitBuiltinCallExpr(E, BuiltinOp);
5878
George Burgess IVe3763372016-12-22 02:50:20 +00005879 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005880}
5881
5882bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5883 unsigned BuiltinOp) {
5884 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005885 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005886 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005887 case Builtin::BI__builtin_assume_aligned: {
5888 // We need to be very careful here because: if the pointer does not have the
5889 // asserted alignment, then the behavior is undefined, and undefined
5890 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005891 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005892 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005893
Hal Finkel0dd05d42014-10-03 17:18:37 +00005894 LValue OffsetResult(Result);
5895 APSInt Alignment;
5896 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5897 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005898 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005899
5900 if (E->getNumArgs() > 2) {
5901 APSInt Offset;
5902 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5903 return false;
5904
Richard Smith642a2362017-01-30 23:30:26 +00005905 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005906 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5907 }
5908
5909 // If there is a base object, then it must have the correct alignment.
5910 if (OffsetResult.Base) {
5911 CharUnits BaseAlignment;
5912 if (const ValueDecl *VD =
5913 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5914 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5915 } else {
5916 BaseAlignment =
5917 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5918 }
5919
5920 if (BaseAlignment < Align) {
5921 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005922 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005923 CCEDiag(E->getArg(0),
5924 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005925 << (unsigned)BaseAlignment.getQuantity()
5926 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005927 return false;
5928 }
5929 }
5930
5931 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005932 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005933 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005934
Richard Smith642a2362017-01-30 23:30:26 +00005935 (OffsetResult.Base
5936 ? CCEDiag(E->getArg(0),
5937 diag::note_constexpr_baa_insufficient_alignment) << 1
5938 : CCEDiag(E->getArg(0),
5939 diag::note_constexpr_baa_value_insufficient_alignment))
5940 << (int)OffsetResult.Offset.getQuantity()
5941 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005942 return false;
5943 }
5944
5945 return true;
5946 }
Richard Smithe9507952016-11-12 01:39:56 +00005947
5948 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005949 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005950 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005951 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005952 if (Info.getLangOpts().CPlusPlus11)
5953 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5954 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005955 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005956 else
5957 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005958 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005959 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005960 case Builtin::BI__builtin_wcschr:
5961 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005962 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005963 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005964 if (!Visit(E->getArg(0)))
5965 return false;
5966 APSInt Desired;
5967 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5968 return false;
5969 uint64_t MaxLength = uint64_t(-1);
5970 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005971 BuiltinOp != Builtin::BIwcschr &&
5972 BuiltinOp != Builtin::BI__builtin_strchr &&
5973 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005974 APSInt N;
5975 if (!EvaluateInteger(E->getArg(2), N, Info))
5976 return false;
5977 MaxLength = N.getExtValue();
5978 }
5979
Richard Smith8110c9d2016-11-29 19:45:17 +00005980 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005981
Richard Smith8110c9d2016-11-29 19:45:17 +00005982 // Figure out what value we're actually looking for (after converting to
5983 // the corresponding unsigned type if necessary).
5984 uint64_t DesiredVal;
5985 bool StopAtNull = false;
5986 switch (BuiltinOp) {
5987 case Builtin::BIstrchr:
5988 case Builtin::BI__builtin_strchr:
5989 // strchr compares directly to the passed integer, and therefore
5990 // always fails if given an int that is not a char.
5991 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5992 E->getArg(1)->getType(),
5993 Desired),
5994 Desired))
5995 return ZeroInitialization(E);
5996 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005997 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005998 case Builtin::BImemchr:
5999 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006000 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006001 // memchr compares by converting both sides to unsigned char. That's also
6002 // correct for strchr if we get this far (to cope with plain char being
6003 // unsigned in the strchr case).
6004 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6005 break;
Richard Smithe9507952016-11-12 01:39:56 +00006006
Richard Smith8110c9d2016-11-29 19:45:17 +00006007 case Builtin::BIwcschr:
6008 case Builtin::BI__builtin_wcschr:
6009 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006010 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006011 case Builtin::BIwmemchr:
6012 case Builtin::BI__builtin_wmemchr:
6013 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6014 DesiredVal = Desired.getZExtValue();
6015 break;
6016 }
Richard Smithe9507952016-11-12 01:39:56 +00006017
6018 for (; MaxLength; --MaxLength) {
6019 APValue Char;
6020 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6021 !Char.isInt())
6022 return false;
6023 if (Char.getInt().getZExtValue() == DesiredVal)
6024 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006025 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006026 break;
6027 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6028 return false;
6029 }
6030 // Not found: return nullptr.
6031 return ZeroInitialization(E);
6032 }
6033
Richard Smith6cbd65d2013-07-11 02:27:57 +00006034 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006035 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006036 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006037}
Chris Lattner05706e882008-07-11 18:11:29 +00006038
6039//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006040// Member Pointer Evaluation
6041//===----------------------------------------------------------------------===//
6042
6043namespace {
6044class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006045 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006046 MemberPtr &Result;
6047
6048 bool Success(const ValueDecl *D) {
6049 Result = MemberPtr(D);
6050 return true;
6051 }
6052public:
6053
6054 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6055 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6056
Richard Smith2e312c82012-03-03 22:46:17 +00006057 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006058 Result.setFrom(V);
6059 return true;
6060 }
Richard Smithfddd3842011-12-30 21:15:51 +00006061 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006062 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006063 }
6064
6065 bool VisitCastExpr(const CastExpr *E);
6066 bool VisitUnaryAddrOf(const UnaryOperator *E);
6067};
6068} // end anonymous namespace
6069
6070static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6071 EvalInfo &Info) {
6072 assert(E->isRValue() && E->getType()->isMemberPointerType());
6073 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6074}
6075
6076bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6077 switch (E->getCastKind()) {
6078 default:
6079 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6080
6081 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006082 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006083 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006084
6085 case CK_BaseToDerivedMemberPointer: {
6086 if (!Visit(E->getSubExpr()))
6087 return false;
6088 if (E->path_empty())
6089 return true;
6090 // Base-to-derived member pointer casts store the path in derived-to-base
6091 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6092 // the wrong end of the derived->base arc, so stagger the path by one class.
6093 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6094 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6095 PathI != PathE; ++PathI) {
6096 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6097 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6098 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006099 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006100 }
6101 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6102 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006103 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006104 return true;
6105 }
6106
6107 case CK_DerivedToBaseMemberPointer:
6108 if (!Visit(E->getSubExpr()))
6109 return false;
6110 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6111 PathE = E->path_end(); PathI != PathE; ++PathI) {
6112 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6113 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6114 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006115 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006116 }
6117 return true;
6118 }
6119}
6120
6121bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6122 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6123 // member can be formed.
6124 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6125}
6126
6127//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006128// Record Evaluation
6129//===----------------------------------------------------------------------===//
6130
6131namespace {
6132 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006133 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006134 const LValue &This;
6135 APValue &Result;
6136 public:
6137
6138 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6139 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6140
Richard Smith2e312c82012-03-03 22:46:17 +00006141 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006142 Result = V;
6143 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006144 }
Richard Smithb8348f52016-05-12 22:16:28 +00006145 bool ZeroInitialization(const Expr *E) {
6146 return ZeroInitialization(E, E->getType());
6147 }
6148 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006149
Richard Smith52a980a2015-08-28 02:43:42 +00006150 bool VisitCallExpr(const CallExpr *E) {
6151 return handleCallExpr(E, Result, &This);
6152 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006153 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006154 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006155 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6156 return VisitCXXConstructExpr(E, E->getType());
6157 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006158 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006159 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006160 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006161 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006162 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006163}
Richard Smithd62306a2011-11-10 06:34:14 +00006164
Richard Smithfddd3842011-12-30 21:15:51 +00006165/// Perform zero-initialization on an object of non-union class type.
6166/// C++11 [dcl.init]p5:
6167/// To zero-initialize an object or reference of type T means:
6168/// [...]
6169/// -- if T is a (possibly cv-qualified) non-union class type,
6170/// each non-static data member and each base-class subobject is
6171/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006172static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6173 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006174 const LValue &This, APValue &Result) {
6175 assert(!RD->isUnion() && "Expected non-union class type");
6176 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6177 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006178 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006179
John McCalld7bca762012-05-01 00:38:49 +00006180 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006181 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6182
6183 if (CD) {
6184 unsigned Index = 0;
6185 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006186 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006187 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6188 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006189 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6190 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006191 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006192 Result.getStructBase(Index)))
6193 return false;
6194 }
6195 }
6196
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006197 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006198 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006199 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006200 continue;
6201
6202 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006203 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006204 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006205
David Blaikie2d7c57e2012-04-30 02:36:29 +00006206 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006207 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006208 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006209 return false;
6210 }
6211
6212 return true;
6213}
6214
Richard Smithb8348f52016-05-12 22:16:28 +00006215bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6216 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006217 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006218 if (RD->isUnion()) {
6219 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6220 // object's first non-static named data member is zero-initialized
6221 RecordDecl::field_iterator I = RD->field_begin();
6222 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006223 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006224 return true;
6225 }
6226
6227 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006228 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006229 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006230 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006231 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006232 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006233 }
6234
Richard Smith5d108602012-02-17 00:44:16 +00006235 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006236 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006237 return false;
6238 }
6239
Richard Smitha8105bc2012-01-06 16:39:00 +00006240 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006241}
6242
Richard Smithe97cbd72011-11-11 04:05:33 +00006243bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6244 switch (E->getCastKind()) {
6245 default:
6246 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6247
6248 case CK_ConstructorConversion:
6249 return Visit(E->getSubExpr());
6250
6251 case CK_DerivedToBase:
6252 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006253 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006254 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006255 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006256 if (!DerivedObject.isStruct())
6257 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006258
6259 // Derived-to-base rvalue conversion: just slice off the derived part.
6260 APValue *Value = &DerivedObject;
6261 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6262 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6263 PathE = E->path_end(); PathI != PathE; ++PathI) {
6264 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6265 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6266 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6267 RD = Base;
6268 }
6269 Result = *Value;
6270 return true;
6271 }
6272 }
6273}
6274
Richard Smithd62306a2011-11-10 06:34:14 +00006275bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006276 if (E->isTransparent())
6277 return Visit(E->getInit(0));
6278
Richard Smithd62306a2011-11-10 06:34:14 +00006279 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006280 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006281 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6282
6283 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006284 const FieldDecl *Field = E->getInitializedFieldInUnion();
6285 Result = APValue(Field);
6286 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006287 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006288
6289 // If the initializer list for a union does not contain any elements, the
6290 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006291 // FIXME: The element should be initialized from an initializer list.
6292 // Is this difference ever observable for initializer lists which
6293 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006294 ImplicitValueInitExpr VIE(Field->getType());
6295 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6296
Richard Smithd62306a2011-11-10 06:34:14 +00006297 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006298 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6299 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006300
6301 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6302 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6303 isa<CXXDefaultInitExpr>(InitExpr));
6304
Richard Smithb228a862012-02-15 02:18:13 +00006305 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006306 }
6307
Richard Smith872307e2016-03-08 22:17:41 +00006308 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006309 if (Result.isUninit())
6310 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6311 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006312 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006313 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006314
6315 // Initialize base classes.
6316 if (CXXRD) {
6317 for (const auto &Base : CXXRD->bases()) {
6318 assert(ElementNo < E->getNumInits() && "missing init for base class");
6319 const Expr *Init = E->getInit(ElementNo);
6320
6321 LValue Subobject = This;
6322 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6323 return false;
6324
6325 APValue &FieldVal = Result.getStructBase(ElementNo);
6326 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006327 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006328 return false;
6329 Success = false;
6330 }
6331 ++ElementNo;
6332 }
6333 }
6334
6335 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006336 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006337 // Anonymous bit-fields are not considered members of the class for
6338 // purposes of aggregate initialization.
6339 if (Field->isUnnamedBitfield())
6340 continue;
6341
6342 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006343
Richard Smith253c2a32012-01-27 01:14:48 +00006344 bool HaveInit = ElementNo < E->getNumInits();
6345
6346 // FIXME: Diagnostics here should point to the end of the initializer
6347 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006348 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006349 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006350 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006351
6352 // Perform an implicit value-initialization for members beyond the end of
6353 // the initializer list.
6354 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006355 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006356
Richard Smith852c9db2013-04-20 22:23:05 +00006357 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6358 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6359 isa<CXXDefaultInitExpr>(Init));
6360
Richard Smith49ca8aa2013-08-06 07:09:20 +00006361 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6362 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6363 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006364 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006365 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006366 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006367 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006368 }
6369 }
6370
Richard Smith253c2a32012-01-27 01:14:48 +00006371 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006372}
6373
Richard Smithb8348f52016-05-12 22:16:28 +00006374bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6375 QualType T) {
6376 // Note that E's type is not necessarily the type of our class here; we might
6377 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006378 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006379 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6380
Richard Smithfddd3842011-12-30 21:15:51 +00006381 bool ZeroInit = E->requiresZeroInitialization();
6382 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006383 // If we've already performed zero-initialization, we're already done.
6384 if (!Result.isUninit())
6385 return true;
6386
Richard Smithda3f4fd2014-03-05 23:32:50 +00006387 // We can get here in two different ways:
6388 // 1) We're performing value-initialization, and should zero-initialize
6389 // the object, or
6390 // 2) We're performing default-initialization of an object with a trivial
6391 // constexpr default constructor, in which case we should start the
6392 // lifetimes of all the base subobjects (there can be no data member
6393 // subobjects in this case) per [basic.life]p1.
6394 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006395 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006396 }
6397
Craig Topper36250ad2014-05-12 05:36:57 +00006398 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006399 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006400
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006401 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006402 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006403
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006404 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006405 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006406 if (const MaterializeTemporaryExpr *ME
6407 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6408 return Visit(ME->GetTemporaryExpr());
6409
Richard Smithb8348f52016-05-12 22:16:28 +00006410 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006411 return false;
6412
Craig Topper5fc8fc22014-08-27 06:28:36 +00006413 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006414 return HandleConstructorCall(E, This, Args,
6415 cast<CXXConstructorDecl>(Definition), Info,
6416 Result);
6417}
6418
6419bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6420 const CXXInheritedCtorInitExpr *E) {
6421 if (!Info.CurrentCall) {
6422 assert(Info.checkingPotentialConstantExpression());
6423 return false;
6424 }
6425
6426 const CXXConstructorDecl *FD = E->getConstructor();
6427 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6428 return false;
6429
6430 const FunctionDecl *Definition = nullptr;
6431 auto Body = FD->getBody(Definition);
6432
6433 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6434 return false;
6435
6436 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006437 cast<CXXConstructorDecl>(Definition), Info,
6438 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006439}
6440
Richard Smithcc1b96d2013-06-12 22:31:48 +00006441bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6442 const CXXStdInitializerListExpr *E) {
6443 const ConstantArrayType *ArrayType =
6444 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6445
6446 LValue Array;
6447 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6448 return false;
6449
6450 // Get a pointer to the first element of the array.
6451 Array.addArray(Info, E, ArrayType);
6452
6453 // FIXME: Perform the checks on the field types in SemaInit.
6454 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6455 RecordDecl::field_iterator Field = Record->field_begin();
6456 if (Field == Record->field_end())
6457 return Error(E);
6458
6459 // Start pointer.
6460 if (!Field->getType()->isPointerType() ||
6461 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6462 ArrayType->getElementType()))
6463 return Error(E);
6464
6465 // FIXME: What if the initializer_list type has base classes, etc?
6466 Result = APValue(APValue::UninitStruct(), 0, 2);
6467 Array.moveInto(Result.getStructField(0));
6468
6469 if (++Field == Record->field_end())
6470 return Error(E);
6471
6472 if (Field->getType()->isPointerType() &&
6473 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6474 ArrayType->getElementType())) {
6475 // End pointer.
6476 if (!HandleLValueArrayAdjustment(Info, E, Array,
6477 ArrayType->getElementType(),
6478 ArrayType->getSize().getZExtValue()))
6479 return false;
6480 Array.moveInto(Result.getStructField(1));
6481 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6482 // Length.
6483 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6484 else
6485 return Error(E);
6486
6487 if (++Field != Record->field_end())
6488 return Error(E);
6489
6490 return true;
6491}
6492
Faisal Valic72a08c2017-01-09 03:02:53 +00006493bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6494 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6495 if (ClosureClass->isInvalidDecl()) return false;
6496
6497 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006498
Faisal Vali051e3a22017-02-16 04:12:21 +00006499 const size_t NumFields =
6500 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006501
6502 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6503 E->capture_init_end()) &&
6504 "The number of lambda capture initializers should equal the number of "
6505 "fields within the closure type");
6506
Faisal Vali051e3a22017-02-16 04:12:21 +00006507 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6508 // Iterate through all the lambda's closure object's fields and initialize
6509 // them.
6510 auto *CaptureInitIt = E->capture_init_begin();
6511 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6512 bool Success = true;
6513 for (const auto *Field : ClosureClass->fields()) {
6514 assert(CaptureInitIt != E->capture_init_end());
6515 // Get the initializer for this field
6516 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006517
Faisal Vali051e3a22017-02-16 04:12:21 +00006518 // If there is no initializer, either this is a VLA or an error has
6519 // occurred.
6520 if (!CurFieldInit)
6521 return Error(E);
6522
6523 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6524 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6525 if (!Info.keepEvaluatingAfterFailure())
6526 return false;
6527 Success = false;
6528 }
6529 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006530 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006531 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006532}
6533
Richard Smithd62306a2011-11-10 06:34:14 +00006534static bool EvaluateRecord(const Expr *E, const LValue &This,
6535 APValue &Result, EvalInfo &Info) {
6536 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006537 "can't evaluate expression as a record rvalue");
6538 return RecordExprEvaluator(Info, This, Result).Visit(E);
6539}
6540
6541//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006542// Temporary Evaluation
6543//
6544// Temporaries are represented in the AST as rvalues, but generally behave like
6545// lvalues. The full-object of which the temporary is a subobject is implicitly
6546// materialized so that a reference can bind to it.
6547//===----------------------------------------------------------------------===//
6548namespace {
6549class TemporaryExprEvaluator
6550 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6551public:
6552 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006553 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006554
6555 /// Visit an expression which constructs the value of this temporary.
6556 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006557 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006558 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6559 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006560 }
6561
6562 bool VisitCastExpr(const CastExpr *E) {
6563 switch (E->getCastKind()) {
6564 default:
6565 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6566
6567 case CK_ConstructorConversion:
6568 return VisitConstructExpr(E->getSubExpr());
6569 }
6570 }
6571 bool VisitInitListExpr(const InitListExpr *E) {
6572 return VisitConstructExpr(E);
6573 }
6574 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6575 return VisitConstructExpr(E);
6576 }
6577 bool VisitCallExpr(const CallExpr *E) {
6578 return VisitConstructExpr(E);
6579 }
Richard Smith513955c2014-12-17 19:24:30 +00006580 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6581 return VisitConstructExpr(E);
6582 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006583 bool VisitLambdaExpr(const LambdaExpr *E) {
6584 return VisitConstructExpr(E);
6585 }
Richard Smith027bf112011-11-17 22:56:20 +00006586};
6587} // end anonymous namespace
6588
6589/// Evaluate an expression of record type as a temporary.
6590static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006591 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006592 return TemporaryExprEvaluator(Info, Result).Visit(E);
6593}
6594
6595//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006596// Vector Evaluation
6597//===----------------------------------------------------------------------===//
6598
6599namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006600 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006601 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006602 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006603 public:
Mike Stump11289f42009-09-09 15:08:12 +00006604
Richard Smith2d406342011-10-22 21:10:00 +00006605 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6606 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006607
Craig Topper9798b932015-09-29 04:30:05 +00006608 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006609 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6610 // FIXME: remove this APValue copy.
6611 Result = APValue(V.data(), V.size());
6612 return true;
6613 }
Richard Smith2e312c82012-03-03 22:46:17 +00006614 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006615 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006616 Result = V;
6617 return true;
6618 }
Richard Smithfddd3842011-12-30 21:15:51 +00006619 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006620
Richard Smith2d406342011-10-22 21:10:00 +00006621 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006622 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006623 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006624 bool VisitInitListExpr(const InitListExpr *E);
6625 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006626 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006627 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006628 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006629 };
6630} // end anonymous namespace
6631
6632static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006633 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006634 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006635}
6636
George Burgess IV533ff002015-12-11 00:23:35 +00006637bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006638 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006639 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006640
Richard Smith161f09a2011-12-06 22:44:34 +00006641 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006642 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006643
Eli Friedmanc757de22011-03-25 00:43:55 +00006644 switch (E->getCastKind()) {
6645 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006646 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006647 if (SETy->isIntegerType()) {
6648 APSInt IntResult;
6649 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006650 return false;
6651 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006652 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006653 APFloat FloatResult(0.0);
6654 if (!EvaluateFloat(SE, FloatResult, Info))
6655 return false;
6656 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006657 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006658 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006659 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006660
6661 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006662 SmallVector<APValue, 4> Elts(NElts, Val);
6663 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006664 }
Eli Friedman803acb32011-12-22 03:51:45 +00006665 case CK_BitCast: {
6666 // Evaluate the operand into an APInt we can extract from.
6667 llvm::APInt SValInt;
6668 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6669 return false;
6670 // Extract the elements
6671 QualType EltTy = VTy->getElementType();
6672 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6673 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6674 SmallVector<APValue, 4> Elts;
6675 if (EltTy->isRealFloatingType()) {
6676 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006677 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006678 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006679 FloatEltSize = 80;
6680 for (unsigned i = 0; i < NElts; i++) {
6681 llvm::APInt Elt;
6682 if (BigEndian)
6683 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6684 else
6685 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006686 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006687 }
6688 } else if (EltTy->isIntegerType()) {
6689 for (unsigned i = 0; i < NElts; i++) {
6690 llvm::APInt Elt;
6691 if (BigEndian)
6692 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6693 else
6694 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6695 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6696 }
6697 } else {
6698 return Error(E);
6699 }
6700 return Success(Elts, E);
6701 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006702 default:
Richard Smith11562c52011-10-28 17:51:58 +00006703 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006704 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006705}
6706
Richard Smith2d406342011-10-22 21:10:00 +00006707bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006708VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006709 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006710 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006711 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006712
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006713 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006714 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006715
Eli Friedmanb9c71292012-01-03 23:24:20 +00006716 // The number of initializers can be less than the number of
6717 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006718 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006719 // should be initialized with zeroes.
6720 unsigned CountInits = 0, CountElts = 0;
6721 while (CountElts < NumElements) {
6722 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006723 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006724 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006725 APValue v;
6726 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6727 return Error(E);
6728 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006729 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006730 Elements.push_back(v.getVectorElt(j));
6731 CountElts += vlen;
6732 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006733 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006734 if (CountInits < NumInits) {
6735 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006736 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006737 } else // trailing integer zero.
6738 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6739 Elements.push_back(APValue(sInt));
6740 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006741 } else {
6742 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006743 if (CountInits < NumInits) {
6744 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006745 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006746 } else // trailing float zero.
6747 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6748 Elements.push_back(APValue(f));
6749 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006750 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006751 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006752 }
Richard Smith2d406342011-10-22 21:10:00 +00006753 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006754}
6755
Richard Smith2d406342011-10-22 21:10:00 +00006756bool
Richard Smithfddd3842011-12-30 21:15:51 +00006757VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006758 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006759 QualType EltTy = VT->getElementType();
6760 APValue ZeroElement;
6761 if (EltTy->isIntegerType())
6762 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6763 else
6764 ZeroElement =
6765 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6766
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006767 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006768 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006769}
6770
Richard Smith2d406342011-10-22 21:10:00 +00006771bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006772 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006773 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006774}
6775
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006776//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006777// Array Evaluation
6778//===----------------------------------------------------------------------===//
6779
6780namespace {
6781 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006782 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006783 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006784 APValue &Result;
6785 public:
6786
Richard Smithd62306a2011-11-10 06:34:14 +00006787 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6788 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006789
6790 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006791 assert((V.isArray() || V.isLValue()) &&
6792 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006793 Result = V;
6794 return true;
6795 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006796
Richard Smithfddd3842011-12-30 21:15:51 +00006797 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006798 const ConstantArrayType *CAT =
6799 Info.Ctx.getAsConstantArrayType(E->getType());
6800 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006801 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006802
6803 Result = APValue(APValue::UninitArray(), 0,
6804 CAT->getSize().getZExtValue());
6805 if (!Result.hasArrayFiller()) return true;
6806
Richard Smithfddd3842011-12-30 21:15:51 +00006807 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006808 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006809 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006810 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006811 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006812 }
6813
Richard Smith52a980a2015-08-28 02:43:42 +00006814 bool VisitCallExpr(const CallExpr *E) {
6815 return handleCallExpr(E, Result, &This);
6816 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006817 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006818 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006819 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006820 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6821 const LValue &Subobject,
6822 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006823 };
6824} // end anonymous namespace
6825
Richard Smithd62306a2011-11-10 06:34:14 +00006826static bool EvaluateArray(const Expr *E, const LValue &This,
6827 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006828 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006829 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006830}
6831
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006832// Return true iff the given array filler may depend on the element index.
6833static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6834 // For now, just whitelist non-class value-initialization and initialization
6835 // lists comprised of them.
6836 if (isa<ImplicitValueInitExpr>(FillerExpr))
6837 return false;
6838 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6839 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6840 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6841 return true;
6842 }
6843 return false;
6844 }
6845 return true;
6846}
6847
Richard Smithf3e9e432011-11-07 09:22:26 +00006848bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6849 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6850 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006851 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006852
Richard Smithca2cfbf2011-12-22 01:07:19 +00006853 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6854 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006855 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006856 LValue LV;
6857 if (!EvaluateLValue(E->getInit(0), LV, Info))
6858 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006859 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006860 LV.moveInto(Val);
6861 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006862 }
6863
Richard Smith253c2a32012-01-27 01:14:48 +00006864 bool Success = true;
6865
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006866 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6867 "zero-initialized array shouldn't have any initialized elts");
6868 APValue Filler;
6869 if (Result.isArray() && Result.hasArrayFiller())
6870 Filler = Result.getArrayFiller();
6871
Richard Smith9543c5e2013-04-22 14:44:29 +00006872 unsigned NumEltsToInit = E->getNumInits();
6873 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006874 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006875
6876 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006877 // array element.
6878 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006879 NumEltsToInit = NumElts;
6880
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006881 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6882 NumEltsToInit << ".\n");
6883
Richard Smith9543c5e2013-04-22 14:44:29 +00006884 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006885
6886 // If the array was previously zero-initialized, preserve the
6887 // zero-initialized values.
6888 if (!Filler.isUninit()) {
6889 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6890 Result.getArrayInitializedElt(I) = Filler;
6891 if (Result.hasArrayFiller())
6892 Result.getArrayFiller() = Filler;
6893 }
6894
Richard Smithd62306a2011-11-10 06:34:14 +00006895 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006896 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006897 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6898 const Expr *Init =
6899 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006900 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006901 Info, Subobject, Init) ||
6902 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006903 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006904 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006905 return false;
6906 Success = false;
6907 }
Richard Smithd62306a2011-11-10 06:34:14 +00006908 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006909
Richard Smith9543c5e2013-04-22 14:44:29 +00006910 if (!Result.hasArrayFiller())
6911 return Success;
6912
6913 // If we get here, we have a trivial filler, which we can just evaluate
6914 // once and splat over the rest of the array elements.
6915 assert(FillerExpr && "no array filler for incomplete init list");
6916 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6917 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006918}
6919
Richard Smith410306b2016-12-12 02:53:20 +00006920bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6921 if (E->getCommonExpr() &&
6922 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6923 Info, E->getCommonExpr()->getSourceExpr()))
6924 return false;
6925
6926 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6927
6928 uint64_t Elements = CAT->getSize().getZExtValue();
6929 Result = APValue(APValue::UninitArray(), Elements, Elements);
6930
6931 LValue Subobject = This;
6932 Subobject.addArray(Info, E, CAT);
6933
6934 bool Success = true;
6935 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6936 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6937 Info, Subobject, E->getSubExpr()) ||
6938 !HandleLValueArrayAdjustment(Info, E, Subobject,
6939 CAT->getElementType(), 1)) {
6940 if (!Info.noteFailure())
6941 return false;
6942 Success = false;
6943 }
6944 }
6945
6946 return Success;
6947}
6948
Richard Smith027bf112011-11-17 22:56:20 +00006949bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006950 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6951}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006952
Richard Smith9543c5e2013-04-22 14:44:29 +00006953bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6954 const LValue &Subobject,
6955 APValue *Value,
6956 QualType Type) {
6957 bool HadZeroInit = !Value->isUninit();
6958
6959 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6960 unsigned N = CAT->getSize().getZExtValue();
6961
6962 // Preserve the array filler if we had prior zero-initialization.
6963 APValue Filler =
6964 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6965 : APValue();
6966
6967 *Value = APValue(APValue::UninitArray(), N, N);
6968
6969 if (HadZeroInit)
6970 for (unsigned I = 0; I != N; ++I)
6971 Value->getArrayInitializedElt(I) = Filler;
6972
6973 // Initialize the elements.
6974 LValue ArrayElt = Subobject;
6975 ArrayElt.addArray(Info, E, CAT);
6976 for (unsigned I = 0; I != N; ++I)
6977 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6978 CAT->getElementType()) ||
6979 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6980 CAT->getElementType(), 1))
6981 return false;
6982
6983 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006984 }
Richard Smith027bf112011-11-17 22:56:20 +00006985
Richard Smith9543c5e2013-04-22 14:44:29 +00006986 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006987 return Error(E);
6988
Richard Smithb8348f52016-05-12 22:16:28 +00006989 return RecordExprEvaluator(Info, Subobject, *Value)
6990 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006991}
6992
Richard Smithf3e9e432011-11-07 09:22:26 +00006993//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006994// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006995//
6996// As a GNU extension, we support casting pointers to sufficiently-wide integer
6997// types and back in constant folding. Integer values are thus represented
6998// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006999//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007000
7001namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007002class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007003 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007004 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007005public:
Richard Smith2e312c82012-03-03 22:46:17 +00007006 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007007 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007008
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007009 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007010 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007011 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007012 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007013 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007014 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007015 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007016 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007017 return true;
7018 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007019 bool Success(const llvm::APSInt &SI, const Expr *E) {
7020 return Success(SI, E, Result);
7021 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007022
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007023 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007024 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007025 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007026 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007027 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007028 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007029 Result.getInt().setIsUnsigned(
7030 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007031 return true;
7032 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007033 bool Success(const llvm::APInt &I, const Expr *E) {
7034 return Success(I, E, Result);
7035 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007036
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007037 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007038 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007039 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007040 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007041 return true;
7042 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007043 bool Success(uint64_t Value, const Expr *E) {
7044 return Success(Value, E, Result);
7045 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007046
Ken Dyckdbc01912011-03-11 02:13:43 +00007047 bool Success(CharUnits Size, const Expr *E) {
7048 return Success(Size.getQuantity(), E);
7049 }
7050
Richard Smith2e312c82012-03-03 22:46:17 +00007051 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007052 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007053 Result = V;
7054 return true;
7055 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007056 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007057 }
Mike Stump11289f42009-09-09 15:08:12 +00007058
Richard Smithfddd3842011-12-30 21:15:51 +00007059 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007060
Peter Collingbournee9200682011-05-13 03:29:01 +00007061 //===--------------------------------------------------------------------===//
7062 // Visitor Methods
7063 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007064
Chris Lattner7174bf32008-07-12 00:38:25 +00007065 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007066 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007067 }
7068 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007069 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007070 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007071
7072 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7073 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007074 if (CheckReferencedDecl(E, E->getDecl()))
7075 return true;
7076
7077 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007078 }
7079 bool VisitMemberExpr(const MemberExpr *E) {
7080 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007081 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007082 return true;
7083 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007084
7085 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007086 }
7087
Peter Collingbournee9200682011-05-13 03:29:01 +00007088 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007089 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007090 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007091 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007092 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007093
Peter Collingbournee9200682011-05-13 03:29:01 +00007094 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007095 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007096
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007097 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007098 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007099 }
Mike Stump11289f42009-09-09 15:08:12 +00007100
Ted Kremeneke65b0862012-03-06 20:05:56 +00007101 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7102 return Success(E->getValue(), E);
7103 }
Richard Smith410306b2016-12-12 02:53:20 +00007104
7105 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7106 if (Info.ArrayInitIndex == uint64_t(-1)) {
7107 // We were asked to evaluate this subexpression independent of the
7108 // enclosing ArrayInitLoopExpr. We can't do that.
7109 Info.FFDiag(E);
7110 return false;
7111 }
7112 return Success(Info.ArrayInitIndex, E);
7113 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007114
Richard Smith4ce706a2011-10-11 21:43:33 +00007115 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007116 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007117 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007118 }
7119
Douglas Gregor29c42f22012-02-24 07:38:34 +00007120 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7121 return Success(E->getValue(), E);
7122 }
7123
John Wiegley6242b6a2011-04-28 00:16:57 +00007124 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7125 return Success(E->getValue(), E);
7126 }
7127
John Wiegleyf9f65842011-04-25 06:54:41 +00007128 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7129 return Success(E->getValue(), E);
7130 }
7131
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007132 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007133 bool VisitUnaryImag(const UnaryOperator *E);
7134
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007135 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007136 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007137
Eli Friedman4e7a2412009-02-27 04:45:43 +00007138 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007139};
Chris Lattner05706e882008-07-11 18:11:29 +00007140} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007141
Richard Smith11562c52011-10-28 17:51:58 +00007142/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7143/// produce either the integer value or a pointer.
7144///
7145/// GCC has a heinous extension which folds casts between pointer types and
7146/// pointer-sized integral types. We support this by allowing the evaluation of
7147/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7148/// Some simple arithmetic on such values is supported (they are treated much
7149/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007150static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007151 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007152 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007153 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007154}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007155
Richard Smithf57d8cb2011-12-09 22:58:01 +00007156static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007157 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007158 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007159 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007160 if (!Val.isInt()) {
7161 // FIXME: It would be better to produce the diagnostic for casting
7162 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007163 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007164 return false;
7165 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007166 Result = Val.getInt();
7167 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007168}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007169
Richard Smithf57d8cb2011-12-09 22:58:01 +00007170/// Check whether the given declaration can be directly converted to an integral
7171/// rvalue. If not, no diagnostic is produced; there are other things we can
7172/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007173bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007174 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007175 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007176 // Check for signedness/width mismatches between E type and ECD value.
7177 bool SameSign = (ECD->getInitVal().isSigned()
7178 == E->getType()->isSignedIntegerOrEnumerationType());
7179 bool SameWidth = (ECD->getInitVal().getBitWidth()
7180 == Info.Ctx.getIntWidth(E->getType()));
7181 if (SameSign && SameWidth)
7182 return Success(ECD->getInitVal(), E);
7183 else {
7184 // Get rid of mismatch (otherwise Success assertions will fail)
7185 // by computing a new value matching the type of E.
7186 llvm::APSInt Val = ECD->getInitVal();
7187 if (!SameSign)
7188 Val.setIsSigned(!ECD->getInitVal().isSigned());
7189 if (!SameWidth)
7190 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7191 return Success(Val, E);
7192 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007193 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007194 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007195}
7196
Chris Lattner86ee2862008-10-06 06:40:35 +00007197/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7198/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007199static int EvaluateBuiltinClassifyType(const CallExpr *E,
7200 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007201 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007202 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007203 enum gcc_type_class {
7204 no_type_class = -1,
7205 void_type_class, integer_type_class, char_type_class,
7206 enumeral_type_class, boolean_type_class,
7207 pointer_type_class, reference_type_class, offset_type_class,
7208 real_type_class, complex_type_class,
7209 function_type_class, method_type_class,
7210 record_type_class, union_type_class,
7211 array_type_class, string_type_class,
7212 lang_type_class
7213 };
Mike Stump11289f42009-09-09 15:08:12 +00007214
7215 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007216 // ideal, however it is what gcc does.
7217 if (E->getNumArgs() == 0)
7218 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007219
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007220 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7221 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7222
7223 switch (CanTy->getTypeClass()) {
7224#define TYPE(ID, BASE)
7225#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7226#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7227#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7228#include "clang/AST/TypeNodes.def"
7229 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7230
7231 case Type::Builtin:
7232 switch (BT->getKind()) {
7233#define BUILTIN_TYPE(ID, SINGLETON_ID)
7234#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7235#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7236#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7237#include "clang/AST/BuiltinTypes.def"
7238 case BuiltinType::Void:
7239 return void_type_class;
7240
7241 case BuiltinType::Bool:
7242 return boolean_type_class;
7243
7244 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7245 case BuiltinType::UChar:
7246 case BuiltinType::UShort:
7247 case BuiltinType::UInt:
7248 case BuiltinType::ULong:
7249 case BuiltinType::ULongLong:
7250 case BuiltinType::UInt128:
7251 return integer_type_class;
7252
7253 case BuiltinType::NullPtr:
7254 return pointer_type_class;
7255
7256 case BuiltinType::WChar_U:
7257 case BuiltinType::Char16:
7258 case BuiltinType::Char32:
7259 case BuiltinType::ObjCId:
7260 case BuiltinType::ObjCClass:
7261 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007262#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7263 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007264#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007265 case BuiltinType::OCLSampler:
7266 case BuiltinType::OCLEvent:
7267 case BuiltinType::OCLClkEvent:
7268 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007269 case BuiltinType::OCLReserveID:
7270 case BuiltinType::Dependent:
7271 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7272 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007273 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007274
7275 case Type::Enum:
7276 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7277 break;
7278
7279 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007280 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007281 break;
7282
7283 case Type::MemberPointer:
7284 if (CanTy->isMemberDataPointerType())
7285 return offset_type_class;
7286 else {
7287 // We expect member pointers to be either data or function pointers,
7288 // nothing else.
7289 assert(CanTy->isMemberFunctionPointerType());
7290 return method_type_class;
7291 }
7292
7293 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007294 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007295
7296 case Type::FunctionNoProto:
7297 case Type::FunctionProto:
7298 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7299
7300 case Type::Record:
7301 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7302 switch (RT->getDecl()->getTagKind()) {
7303 case TagTypeKind::TTK_Struct:
7304 case TagTypeKind::TTK_Class:
7305 case TagTypeKind::TTK_Interface:
7306 return record_type_class;
7307
7308 case TagTypeKind::TTK_Enum:
7309 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7310
7311 case TagTypeKind::TTK_Union:
7312 return union_type_class;
7313 }
7314 }
David Blaikie83d382b2011-09-23 05:06:16 +00007315 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007316
7317 case Type::ConstantArray:
7318 case Type::VariableArray:
7319 case Type::IncompleteArray:
7320 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7321
7322 case Type::BlockPointer:
7323 case Type::LValueReference:
7324 case Type::RValueReference:
7325 case Type::Vector:
7326 case Type::ExtVector:
7327 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007328 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007329 case Type::ObjCObject:
7330 case Type::ObjCInterface:
7331 case Type::ObjCObjectPointer:
7332 case Type::Pipe:
7333 case Type::Atomic:
7334 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7335 }
7336
7337 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007338}
7339
Richard Smith5fab0c92011-12-28 19:48:30 +00007340/// EvaluateBuiltinConstantPForLValue - Determine the result of
7341/// __builtin_constant_p when applied to the given lvalue.
7342///
7343/// An lvalue is only "constant" if it is a pointer or reference to the first
7344/// character of a string literal.
7345template<typename LValue>
7346static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007347 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007348 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7349}
7350
7351/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7352/// GCC as we can manage.
7353static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7354 QualType ArgType = Arg->getType();
7355
7356 // __builtin_constant_p always has one operand. The rules which gcc follows
7357 // are not precisely documented, but are as follows:
7358 //
7359 // - If the operand is of integral, floating, complex or enumeration type,
7360 // and can be folded to a known value of that type, it returns 1.
7361 // - If the operand and can be folded to a pointer to the first character
7362 // of a string literal (or such a pointer cast to an integral type), it
7363 // returns 1.
7364 //
7365 // Otherwise, it returns 0.
7366 //
7367 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7368 // its support for this does not currently work.
7369 if (ArgType->isIntegralOrEnumerationType()) {
7370 Expr::EvalResult Result;
7371 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7372 return false;
7373
7374 APValue &V = Result.Val;
7375 if (V.getKind() == APValue::Int)
7376 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007377 if (V.getKind() == APValue::LValue)
7378 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007379 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7380 return Arg->isEvaluatable(Ctx);
7381 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7382 LValue LV;
7383 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007384 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007385 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7386 : EvaluatePointer(Arg, LV, Info)) &&
7387 !Status.HasSideEffects)
7388 return EvaluateBuiltinConstantPForLValue(LV);
7389 }
7390
7391 // Anything else isn't considered to be sufficiently constant.
7392 return false;
7393}
7394
John McCall95007602010-05-10 23:27:23 +00007395/// Retrieves the "underlying object type" of the given expression,
7396/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007397static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007398 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7399 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007400 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007401 } else if (const Expr *E = B.get<const Expr*>()) {
7402 if (isa<CompoundLiteralExpr>(E))
7403 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007404 }
7405
7406 return QualType();
7407}
7408
George Burgess IV3a03fab2015-09-04 21:28:13 +00007409/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007410/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007411/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007412/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7413///
7414/// Always returns an RValue with a pointer representation.
7415static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7416 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7417
7418 auto *NoParens = E->IgnoreParens();
7419 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007420 if (Cast == nullptr)
7421 return NoParens;
7422
7423 // We only conservatively allow a few kinds of casts, because this code is
7424 // inherently a simple solution that seeks to support the common case.
7425 auto CastKind = Cast->getCastKind();
7426 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7427 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007428 return NoParens;
7429
7430 auto *SubExpr = Cast->getSubExpr();
7431 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7432 return NoParens;
7433 return ignorePointerCastsAndParens(SubExpr);
7434}
7435
George Burgess IVa51c4072015-10-16 01:49:01 +00007436/// Checks to see if the given LValue's Designator is at the end of the LValue's
7437/// record layout. e.g.
7438/// struct { struct { int a, b; } fst, snd; } obj;
7439/// obj.fst // no
7440/// obj.snd // yes
7441/// obj.fst.a // no
7442/// obj.fst.b // no
7443/// obj.snd.a // no
7444/// obj.snd.b // yes
7445///
7446/// Please note: this function is specialized for how __builtin_object_size
7447/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007448///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007449/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7450/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007451static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7452 assert(!LVal.Designator.Invalid);
7453
George Burgess IV4168d752016-06-27 19:40:41 +00007454 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7455 const RecordDecl *Parent = FD->getParent();
7456 Invalid = Parent->isInvalidDecl();
7457 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007458 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007459 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007460 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7461 };
7462
7463 auto &Base = LVal.getLValueBase();
7464 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7465 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007466 bool Invalid;
7467 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7468 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007469 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007470 for (auto *FD : IFD->chain()) {
7471 bool Invalid;
7472 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7473 return Invalid;
7474 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007475 }
7476 }
7477
George Burgess IVe3763372016-12-22 02:50:20 +00007478 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007479 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007480 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007481 // If we don't know the array bound, conservatively assume we're looking at
7482 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007483 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007484 if (BaseType->isIncompleteArrayType())
7485 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7486 else
7487 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007488 }
7489
7490 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7491 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007492 if (BaseType->isArrayType()) {
7493 // Because __builtin_object_size treats arrays as objects, we can ignore
7494 // the index iff this is the last array in the Designator.
7495 if (I + 1 == E)
7496 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007497 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7498 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007499 if (Index + 1 != CAT->getSize())
7500 return false;
7501 BaseType = CAT->getElementType();
7502 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007503 const auto *CT = BaseType->castAs<ComplexType>();
7504 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007505 if (Index != 1)
7506 return false;
7507 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007508 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007509 bool Invalid;
7510 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7511 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007512 BaseType = FD->getType();
7513 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007514 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007515 return false;
7516 }
7517 }
7518 return true;
7519}
7520
George Burgess IVe3763372016-12-22 02:50:20 +00007521/// Tests to see if the LValue has a user-specified designator (that isn't
7522/// necessarily valid). Note that this always returns 'true' if the LValue has
7523/// an unsized array as its first designator entry, because there's currently no
7524/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007525static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007526 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007527 return false;
7528
George Burgess IVe3763372016-12-22 02:50:20 +00007529 if (!LVal.Designator.Entries.empty())
7530 return LVal.Designator.isMostDerivedAnUnsizedArray();
7531
George Burgess IVa51c4072015-10-16 01:49:01 +00007532 if (!LVal.InvalidBase)
7533 return true;
7534
George Burgess IVe3763372016-12-22 02:50:20 +00007535 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7536 // the LValueBase.
7537 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7538 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007539}
7540
George Burgess IVe3763372016-12-22 02:50:20 +00007541/// Attempts to detect a user writing into a piece of memory that's impossible
7542/// to figure out the size of by just using types.
7543static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7544 const SubobjectDesignator &Designator = LVal.Designator;
7545 // Notes:
7546 // - Users can only write off of the end when we have an invalid base. Invalid
7547 // bases imply we don't know where the memory came from.
7548 // - We used to be a bit more aggressive here; we'd only be conservative if
7549 // the array at the end was flexible, or if it had 0 or 1 elements. This
7550 // broke some common standard library extensions (PR30346), but was
7551 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7552 // with some sort of whitelist. OTOH, it seems that GCC is always
7553 // conservative with the last element in structs (if it's an array), so our
7554 // current behavior is more compatible than a whitelisting approach would
7555 // be.
7556 return LVal.InvalidBase &&
7557 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7558 Designator.MostDerivedIsArrayElement &&
7559 isDesignatorAtObjectEnd(Ctx, LVal);
7560}
7561
7562/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7563/// Fails if the conversion would cause loss of precision.
7564static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7565 CharUnits &Result) {
7566 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7567 if (Int.ugt(CharUnitsMax))
7568 return false;
7569 Result = CharUnits::fromQuantity(Int.getZExtValue());
7570 return true;
7571}
7572
7573/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7574/// determine how many bytes exist from the beginning of the object to either
7575/// the end of the current subobject, or the end of the object itself, depending
7576/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007577///
George Burgess IVe3763372016-12-22 02:50:20 +00007578/// If this returns false, the value of Result is undefined.
7579static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7580 unsigned Type, const LValue &LVal,
7581 CharUnits &EndOffset) {
7582 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007583
George Burgess IV7fb7e362017-01-03 23:35:19 +00007584 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7585 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7586 return false;
7587 return HandleSizeof(Info, ExprLoc, Ty, Result);
7588 };
7589
George Burgess IVe3763372016-12-22 02:50:20 +00007590 // We want to evaluate the size of the entire object. This is a valid fallback
7591 // for when Type=1 and the designator is invalid, because we're asked for an
7592 // upper-bound.
7593 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7594 // Type=3 wants a lower bound, so we can't fall back to this.
7595 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007596 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007597
7598 llvm::APInt APEndOffset;
7599 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7600 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7601 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7602
7603 if (LVal.InvalidBase)
7604 return false;
7605
7606 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007607 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007608 }
7609
George Burgess IVe3763372016-12-22 02:50:20 +00007610 // We want to evaluate the size of a subobject.
7611 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007612
7613 // The following is a moderately common idiom in C:
7614 //
7615 // struct Foo { int a; char c[1]; };
7616 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7617 // strcpy(&F->c[0], Bar);
7618 //
George Burgess IVe3763372016-12-22 02:50:20 +00007619 // In order to not break too much legacy code, we need to support it.
7620 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7621 // If we can resolve this to an alloc_size call, we can hand that back,
7622 // because we know for certain how many bytes there are to write to.
7623 llvm::APInt APEndOffset;
7624 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7625 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7626 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7627
7628 // If we cannot determine the size of the initial allocation, then we can't
7629 // given an accurate upper-bound. However, we are still able to give
7630 // conservative lower-bounds for Type=3.
7631 if (Type == 1)
7632 return false;
7633 }
7634
7635 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007636 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007637 return false;
7638
George Burgess IVe3763372016-12-22 02:50:20 +00007639 // According to the GCC documentation, we want the size of the subobject
7640 // denoted by the pointer. But that's not quite right -- what we actually
7641 // want is the size of the immediately-enclosing array, if there is one.
7642 int64_t ElemsRemaining;
7643 if (Designator.MostDerivedIsArrayElement &&
7644 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7645 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7646 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7647 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7648 } else {
7649 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7650 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007651
George Burgess IVe3763372016-12-22 02:50:20 +00007652 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7653 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007654}
7655
George Burgess IVe3763372016-12-22 02:50:20 +00007656/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7657/// returns true and stores the result in @p Size.
7658///
7659/// If @p WasError is non-null, this will report whether the failure to evaluate
7660/// is to be treated as an Error in IntExprEvaluator.
7661static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7662 EvalInfo &Info, uint64_t &Size) {
7663 // Determine the denoted object.
7664 LValue LVal;
7665 {
7666 // The operand of __builtin_object_size is never evaluated for side-effects.
7667 // If there are any, but we can determine the pointed-to object anyway, then
7668 // ignore the side-effects.
7669 SpeculativeEvaluationRAII SpeculativeEval(Info);
7670 FoldOffsetRAII Fold(Info);
7671
7672 if (E->isGLValue()) {
7673 // It's possible for us to be given GLValues if we're called via
7674 // Expr::tryEvaluateObjectSize.
7675 APValue RVal;
7676 if (!EvaluateAsRValue(Info, E, RVal))
7677 return false;
7678 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007679 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7680 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007681 return false;
7682 }
7683
7684 // If we point to before the start of the object, there are no accessible
7685 // bytes.
7686 if (LVal.getLValueOffset().isNegative()) {
7687 Size = 0;
7688 return true;
7689 }
7690
7691 CharUnits EndOffset;
7692 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7693 return false;
7694
7695 // If we've fallen outside of the end offset, just pretend there's nothing to
7696 // write to/read from.
7697 if (EndOffset <= LVal.getLValueOffset())
7698 Size = 0;
7699 else
7700 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7701 return true;
John McCall95007602010-05-10 23:27:23 +00007702}
7703
Peter Collingbournee9200682011-05-13 03:29:01 +00007704bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007705 if (unsigned BuiltinOp = E->getBuiltinCallee())
7706 return VisitBuiltinCallExpr(E, BuiltinOp);
7707
7708 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7709}
7710
7711bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7712 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007713 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007714 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007715 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007716
7717 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007718 // The type was checked when we built the expression.
7719 unsigned Type =
7720 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7721 assert(Type <= 3 && "unexpected type");
7722
George Burgess IVe3763372016-12-22 02:50:20 +00007723 uint64_t Size;
7724 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7725 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007726
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007727 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007728 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007729
Richard Smith01ade172012-05-23 04:13:20 +00007730 // Expression had no side effects, but we couldn't statically determine the
7731 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007732 switch (Info.EvalMode) {
7733 case EvalInfo::EM_ConstantExpression:
7734 case EvalInfo::EM_PotentialConstantExpression:
7735 case EvalInfo::EM_ConstantFold:
7736 case EvalInfo::EM_EvaluateForOverflow:
7737 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007738 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007739 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007740 return Error(E);
7741 case EvalInfo::EM_ConstantExpressionUnevaluated:
7742 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007743 // Reduce it to a constant now.
7744 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007745 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007746
7747 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007748 }
7749
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007750 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007751 case Builtin::BI__builtin_bswap32:
7752 case Builtin::BI__builtin_bswap64: {
7753 APSInt Val;
7754 if (!EvaluateInteger(E->getArg(0), Val, Info))
7755 return false;
7756
7757 return Success(Val.byteSwap(), E);
7758 }
7759
Richard Smith8889a3d2013-06-13 06:26:32 +00007760 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007761 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007762
7763 // FIXME: BI__builtin_clrsb
7764 // FIXME: BI__builtin_clrsbl
7765 // FIXME: BI__builtin_clrsbll
7766
Richard Smith80b3c8e2013-06-13 05:04:16 +00007767 case Builtin::BI__builtin_clz:
7768 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007769 case Builtin::BI__builtin_clzll:
7770 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007771 APSInt Val;
7772 if (!EvaluateInteger(E->getArg(0), Val, Info))
7773 return false;
7774 if (!Val)
7775 return Error(E);
7776
7777 return Success(Val.countLeadingZeros(), E);
7778 }
7779
Richard Smith8889a3d2013-06-13 06:26:32 +00007780 case Builtin::BI__builtin_constant_p:
7781 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7782
Richard Smith80b3c8e2013-06-13 05:04:16 +00007783 case Builtin::BI__builtin_ctz:
7784 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007785 case Builtin::BI__builtin_ctzll:
7786 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007787 APSInt Val;
7788 if (!EvaluateInteger(E->getArg(0), Val, Info))
7789 return false;
7790 if (!Val)
7791 return Error(E);
7792
7793 return Success(Val.countTrailingZeros(), E);
7794 }
7795
Richard Smith8889a3d2013-06-13 06:26:32 +00007796 case Builtin::BI__builtin_eh_return_data_regno: {
7797 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7798 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7799 return Success(Operand, E);
7800 }
7801
7802 case Builtin::BI__builtin_expect:
7803 return Visit(E->getArg(0));
7804
7805 case Builtin::BI__builtin_ffs:
7806 case Builtin::BI__builtin_ffsl:
7807 case Builtin::BI__builtin_ffsll: {
7808 APSInt Val;
7809 if (!EvaluateInteger(E->getArg(0), Val, Info))
7810 return false;
7811
7812 unsigned N = Val.countTrailingZeros();
7813 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7814 }
7815
7816 case Builtin::BI__builtin_fpclassify: {
7817 APFloat Val(0.0);
7818 if (!EvaluateFloat(E->getArg(5), Val, Info))
7819 return false;
7820 unsigned Arg;
7821 switch (Val.getCategory()) {
7822 case APFloat::fcNaN: Arg = 0; break;
7823 case APFloat::fcInfinity: Arg = 1; break;
7824 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7825 case APFloat::fcZero: Arg = 4; break;
7826 }
7827 return Visit(E->getArg(Arg));
7828 }
7829
7830 case Builtin::BI__builtin_isinf_sign: {
7831 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007832 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007833 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7834 }
7835
Richard Smithea3019d2013-10-15 19:07:14 +00007836 case Builtin::BI__builtin_isinf: {
7837 APFloat Val(0.0);
7838 return EvaluateFloat(E->getArg(0), Val, Info) &&
7839 Success(Val.isInfinity() ? 1 : 0, E);
7840 }
7841
7842 case Builtin::BI__builtin_isfinite: {
7843 APFloat Val(0.0);
7844 return EvaluateFloat(E->getArg(0), Val, Info) &&
7845 Success(Val.isFinite() ? 1 : 0, E);
7846 }
7847
7848 case Builtin::BI__builtin_isnan: {
7849 APFloat Val(0.0);
7850 return EvaluateFloat(E->getArg(0), Val, Info) &&
7851 Success(Val.isNaN() ? 1 : 0, E);
7852 }
7853
7854 case Builtin::BI__builtin_isnormal: {
7855 APFloat Val(0.0);
7856 return EvaluateFloat(E->getArg(0), Val, Info) &&
7857 Success(Val.isNormal() ? 1 : 0, E);
7858 }
7859
Richard Smith8889a3d2013-06-13 06:26:32 +00007860 case Builtin::BI__builtin_parity:
7861 case Builtin::BI__builtin_parityl:
7862 case Builtin::BI__builtin_parityll: {
7863 APSInt Val;
7864 if (!EvaluateInteger(E->getArg(0), Val, Info))
7865 return false;
7866
7867 return Success(Val.countPopulation() % 2, E);
7868 }
7869
Richard Smith80b3c8e2013-06-13 05:04:16 +00007870 case Builtin::BI__builtin_popcount:
7871 case Builtin::BI__builtin_popcountl:
7872 case Builtin::BI__builtin_popcountll: {
7873 APSInt Val;
7874 if (!EvaluateInteger(E->getArg(0), Val, Info))
7875 return false;
7876
7877 return Success(Val.countPopulation(), E);
7878 }
7879
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007880 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007881 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007882 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007883 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007884 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007885 << /*isConstexpr*/0 << /*isConstructor*/0
7886 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007887 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007888 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007889 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007890 case Builtin::BI__builtin_strlen:
7891 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007892 // As an extension, we support __builtin_strlen() as a constant expression,
7893 // and support folding strlen() to a constant.
7894 LValue String;
7895 if (!EvaluatePointer(E->getArg(0), String, Info))
7896 return false;
7897
Richard Smith8110c9d2016-11-29 19:45:17 +00007898 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7899
Richard Smithe6c19f22013-11-15 02:10:04 +00007900 // Fast path: if it's a string literal, search the string value.
7901 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7902 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007903 // The string literal may have embedded null characters. Find the first
7904 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007905 StringRef Str = S->getBytes();
7906 int64_t Off = String.Offset.getQuantity();
7907 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007908 S->getCharByteWidth() == 1 &&
7909 // FIXME: Add fast-path for wchar_t too.
7910 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007911 Str = Str.substr(Off);
7912
7913 StringRef::size_type Pos = Str.find(0);
7914 if (Pos != StringRef::npos)
7915 Str = Str.substr(0, Pos);
7916
7917 return Success(Str.size(), E);
7918 }
7919
7920 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007921 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007922
7923 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007924 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7925 APValue Char;
7926 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7927 !Char.isInt())
7928 return false;
7929 if (!Char.getInt())
7930 return Success(Strlen, E);
7931 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7932 return false;
7933 }
7934 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007935
Richard Smithe151bab2016-11-11 23:43:35 +00007936 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007937 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007938 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007939 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007940 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007941 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007942 // A call to strlen is not a constant expression.
7943 if (Info.getLangOpts().CPlusPlus11)
7944 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7945 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007946 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007947 else
7948 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007949 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007950 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007951 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007952 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007953 case Builtin::BI__builtin_wcsncmp:
7954 case Builtin::BI__builtin_memcmp:
7955 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007956 LValue String1, String2;
7957 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7958 !EvaluatePointer(E->getArg(1), String2, Info))
7959 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007960
7961 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7962
Richard Smithe151bab2016-11-11 23:43:35 +00007963 uint64_t MaxLength = uint64_t(-1);
7964 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007965 BuiltinOp != Builtin::BIwcscmp &&
7966 BuiltinOp != Builtin::BI__builtin_strcmp &&
7967 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007968 APSInt N;
7969 if (!EvaluateInteger(E->getArg(2), N, Info))
7970 return false;
7971 MaxLength = N.getExtValue();
7972 }
7973 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007974 BuiltinOp != Builtin::BIwmemcmp &&
7975 BuiltinOp != Builtin::BI__builtin_memcmp &&
7976 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007977 for (; MaxLength; --MaxLength) {
7978 APValue Char1, Char2;
7979 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7980 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7981 !Char1.isInt() || !Char2.isInt())
7982 return false;
7983 if (Char1.getInt() != Char2.getInt())
7984 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7985 if (StopAtNull && !Char1.getInt())
7986 return Success(0, E);
7987 assert(!(StopAtNull && !Char2.getInt()));
7988 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7989 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7990 return false;
7991 }
7992 // We hit the strncmp / memcmp limit.
7993 return Success(0, E);
7994 }
7995
Richard Smith01ba47d2012-04-13 00:45:38 +00007996 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007997 case Builtin::BI__atomic_is_lock_free:
7998 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007999 APSInt SizeVal;
8000 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8001 return false;
8002
8003 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8004 // of two less than the maximum inline atomic width, we know it is
8005 // lock-free. If the size isn't a power of two, or greater than the
8006 // maximum alignment where we promote atomics, we know it is not lock-free
8007 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8008 // the answer can only be determined at runtime; for example, 16-byte
8009 // atomics have lock-free implementations on some, but not all,
8010 // x86-64 processors.
8011
8012 // Check power-of-two.
8013 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008014 if (Size.isPowerOfTwo()) {
8015 // Check against inlining width.
8016 unsigned InlineWidthBits =
8017 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8018 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8019 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8020 Size == CharUnits::One() ||
8021 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8022 Expr::NPC_NeverValueDependent))
8023 // OK, we will inline appropriately-aligned operations of this size,
8024 // and _Atomic(T) is appropriately-aligned.
8025 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008026
Richard Smith01ba47d2012-04-13 00:45:38 +00008027 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8028 castAs<PointerType>()->getPointeeType();
8029 if (!PointeeType->isIncompleteType() &&
8030 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8031 // OK, we will inline operations on this object.
8032 return Success(1, E);
8033 }
8034 }
8035 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008036
Richard Smith01ba47d2012-04-13 00:45:38 +00008037 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8038 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008039 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008040 case Builtin::BIomp_is_initial_device:
8041 // We can decide statically which value the runtime would return if called.
8042 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008043 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008044}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008045
Richard Smith8b3497e2011-10-31 01:37:14 +00008046static bool HasSameBase(const LValue &A, const LValue &B) {
8047 if (!A.getLValueBase())
8048 return !B.getLValueBase();
8049 if (!B.getLValueBase())
8050 return false;
8051
Richard Smithce40ad62011-11-12 22:28:03 +00008052 if (A.getLValueBase().getOpaqueValue() !=
8053 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008054 const Decl *ADecl = GetLValueBaseDecl(A);
8055 if (!ADecl)
8056 return false;
8057 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008058 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008059 return false;
8060 }
8061
8062 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008063 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008064}
8065
Richard Smithd20f1e62014-10-21 23:01:04 +00008066/// \brief Determine whether this is a pointer past the end of the complete
8067/// object referred to by the lvalue.
8068static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8069 const LValue &LV) {
8070 // A null pointer can be viewed as being "past the end" but we don't
8071 // choose to look at it that way here.
8072 if (!LV.getLValueBase())
8073 return false;
8074
8075 // If the designator is valid and refers to a subobject, we're not pointing
8076 // past the end.
8077 if (!LV.getLValueDesignator().Invalid &&
8078 !LV.getLValueDesignator().isOnePastTheEnd())
8079 return false;
8080
David Majnemerc378ca52015-08-29 08:32:55 +00008081 // A pointer to an incomplete type might be past-the-end if the type's size is
8082 // zero. We cannot tell because the type is incomplete.
8083 QualType Ty = getType(LV.getLValueBase());
8084 if (Ty->isIncompleteType())
8085 return true;
8086
Richard Smithd20f1e62014-10-21 23:01:04 +00008087 // We're a past-the-end pointer if we point to the byte after the object,
8088 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008089 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008090 return LV.getLValueOffset() == Size;
8091}
8092
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008093namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008094
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008095/// \brief Data recursive integer evaluator of certain binary operators.
8096///
8097/// We use a data recursive algorithm for binary operators so that we are able
8098/// to handle extreme cases of chained binary operators without causing stack
8099/// overflow.
8100class DataRecursiveIntBinOpEvaluator {
8101 struct EvalResult {
8102 APValue Val;
8103 bool Failed;
8104
8105 EvalResult() : Failed(false) { }
8106
8107 void swap(EvalResult &RHS) {
8108 Val.swap(RHS.Val);
8109 Failed = RHS.Failed;
8110 RHS.Failed = false;
8111 }
8112 };
8113
8114 struct Job {
8115 const Expr *E;
8116 EvalResult LHSResult; // meaningful only for binary operator expression.
8117 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008118
David Blaikie73726062015-08-12 23:09:24 +00008119 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008120 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008121
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008122 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008123 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008124 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008125
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008126 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008127 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008128 };
8129
8130 SmallVector<Job, 16> Queue;
8131
8132 IntExprEvaluator &IntEval;
8133 EvalInfo &Info;
8134 APValue &FinalResult;
8135
8136public:
8137 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8138 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8139
8140 /// \brief True if \param E is a binary operator that we are going to handle
8141 /// data recursively.
8142 /// We handle binary operators that are comma, logical, or that have operands
8143 /// with integral or enumeration type.
8144 static bool shouldEnqueue(const BinaryOperator *E) {
8145 return E->getOpcode() == BO_Comma ||
8146 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008147 (E->isRValue() &&
8148 E->getType()->isIntegralOrEnumerationType() &&
8149 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008150 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008151 }
8152
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008153 bool Traverse(const BinaryOperator *E) {
8154 enqueue(E);
8155 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008156 while (!Queue.empty())
8157 process(PrevResult);
8158
8159 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008160
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008161 FinalResult.swap(PrevResult.Val);
8162 return true;
8163 }
8164
8165private:
8166 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8167 return IntEval.Success(Value, E, Result);
8168 }
8169 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8170 return IntEval.Success(Value, E, Result);
8171 }
8172 bool Error(const Expr *E) {
8173 return IntEval.Error(E);
8174 }
8175 bool Error(const Expr *E, diag::kind D) {
8176 return IntEval.Error(E, D);
8177 }
8178
8179 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8180 return Info.CCEDiag(E, D);
8181 }
8182
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008183 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8184 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008185 bool &SuppressRHSDiags);
8186
8187 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8188 const BinaryOperator *E, APValue &Result);
8189
8190 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8191 Result.Failed = !Evaluate(Result.Val, Info, E);
8192 if (Result.Failed)
8193 Result.Val = APValue();
8194 }
8195
Richard Trieuba4d0872012-03-21 23:30:30 +00008196 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197
8198 void enqueue(const Expr *E) {
8199 E = E->IgnoreParens();
8200 Queue.resize(Queue.size()+1);
8201 Queue.back().E = E;
8202 Queue.back().Kind = Job::AnyExprKind;
8203 }
8204};
8205
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008206}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008207
8208bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008209 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 bool &SuppressRHSDiags) {
8211 if (E->getOpcode() == BO_Comma) {
8212 // Ignore LHS but note if we could not evaluate it.
8213 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008214 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008215 return true;
8216 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008217
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008218 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008219 bool LHSAsBool;
8220 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008221 // We were able to evaluate the LHS, see if we can get away with not
8222 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008223 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8224 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008225 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008226 }
8227 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008228 LHSResult.Failed = true;
8229
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008230 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008231 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008232 if (!Info.noteSideEffect())
8233 return false;
8234
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008235 // We can't evaluate the LHS; however, sometimes the result
8236 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8237 // Don't ignore RHS and suppress diagnostics from this arm.
8238 SuppressRHSDiags = true;
8239 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241 return true;
8242 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008243
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008244 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8245 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008246
George Burgess IVa145e252016-05-25 22:38:36 +00008247 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008248 return false; // Ignore RHS;
8249
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008250 return true;
8251}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008252
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008253static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8254 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008255 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8256 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8257 // offsets.
8258 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8259 CharUnits &Offset = LVal.getLValueOffset();
8260 uint64_t Offset64 = Offset.getQuantity();
8261 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8262 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8263 : Offset64 + Index64);
8264}
8265
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008266bool DataRecursiveIntBinOpEvaluator::
8267 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8268 const BinaryOperator *E, APValue &Result) {
8269 if (E->getOpcode() == BO_Comma) {
8270 if (RHSResult.Failed)
8271 return false;
8272 Result = RHSResult.Val;
8273 return true;
8274 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008275
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008276 if (E->isLogicalOp()) {
8277 bool lhsResult, rhsResult;
8278 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8279 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008280
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281 if (LHSIsOK) {
8282 if (RHSIsOK) {
8283 if (E->getOpcode() == BO_LOr)
8284 return Success(lhsResult || rhsResult, E, Result);
8285 else
8286 return Success(lhsResult && rhsResult, E, Result);
8287 }
8288 } else {
8289 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008290 // We can't evaluate the LHS; however, sometimes the result
8291 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8292 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008294 }
8295 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008296
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008297 return false;
8298 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008299
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008300 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8301 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008302
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008303 if (LHSResult.Failed || RHSResult.Failed)
8304 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008305
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008306 const APValue &LHSVal = LHSResult.Val;
8307 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008308
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008309 // Handle cases like (unsigned long)&a + 4.
8310 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8311 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008312 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008313 return true;
8314 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008316 // Handle cases like 4 + (unsigned long)&a
8317 if (E->getOpcode() == BO_Add &&
8318 RHSVal.isLValue() && LHSVal.isInt()) {
8319 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008320 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008321 return true;
8322 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008323
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008324 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8325 // Handle (intptr_t)&&A - (intptr_t)&&B.
8326 if (!LHSVal.getLValueOffset().isZero() ||
8327 !RHSVal.getLValueOffset().isZero())
8328 return false;
8329 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8330 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8331 if (!LHSExpr || !RHSExpr)
8332 return false;
8333 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8334 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8335 if (!LHSAddrExpr || !RHSAddrExpr)
8336 return false;
8337 // Make sure both labels come from the same function.
8338 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8339 RHSAddrExpr->getLabel()->getDeclContext())
8340 return false;
8341 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8342 return true;
8343 }
Richard Smith43e77732013-05-07 04:50:00 +00008344
8345 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008346 if (!LHSVal.isInt() || !RHSVal.isInt())
8347 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008348
8349 // Set up the width and signedness manually, in case it can't be deduced
8350 // from the operation we're performing.
8351 // FIXME: Don't do this in the cases where we can deduce it.
8352 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8353 E->getType()->isUnsignedIntegerOrEnumerationType());
8354 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8355 RHSVal.getInt(), Value))
8356 return false;
8357 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008358}
8359
Richard Trieuba4d0872012-03-21 23:30:30 +00008360void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008361 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008362
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 switch (job.Kind) {
8364 case Job::AnyExprKind: {
8365 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8366 if (shouldEnqueue(Bop)) {
8367 job.Kind = Job::BinOpKind;
8368 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008369 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008370 }
8371 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008372
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008373 EvaluateExpr(job.E, Result);
8374 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008375 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008376 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008378 case Job::BinOpKind: {
8379 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008380 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008381 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008382 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008383 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008384 }
8385 if (SuppressRHSDiags)
8386 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008387 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008388 job.Kind = Job::BinOpVisitedLHSKind;
8389 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008390 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008391 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008393 case Job::BinOpVisitedLHSKind: {
8394 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8395 EvalResult RHS;
8396 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008397 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008398 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008399 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008400 }
8401 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008402
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008403 llvm_unreachable("Invalid Job::Kind!");
8404}
8405
George Burgess IV8c892b52016-05-25 22:31:54 +00008406namespace {
8407/// Used when we determine that we should fail, but can keep evaluating prior to
8408/// noting that we had a failure.
8409class DelayedNoteFailureRAII {
8410 EvalInfo &Info;
8411 bool NoteFailure;
8412
8413public:
8414 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8415 : Info(Info), NoteFailure(NoteFailure) {}
8416 ~DelayedNoteFailureRAII() {
8417 if (NoteFailure) {
8418 bool ContinueAfterFailure = Info.noteFailure();
8419 (void)ContinueAfterFailure;
8420 assert(ContinueAfterFailure &&
8421 "Shouldn't have kept evaluating on failure.");
8422 }
8423 }
8424};
8425}
8426
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008427bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008428 // We don't call noteFailure immediately because the assignment happens after
8429 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008430 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008431 return Error(E);
8432
George Burgess IV8c892b52016-05-25 22:31:54 +00008433 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008434 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8435 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008436
Anders Carlssonacc79812008-11-16 07:17:21 +00008437 QualType LHSTy = E->getLHS()->getType();
8438 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008439
Chandler Carruthb29a7432014-10-11 11:03:30 +00008440 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008441 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008442 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008443 if (E->isAssignmentOp()) {
8444 LValue LV;
8445 EvaluateLValue(E->getLHS(), LV, Info);
8446 LHSOK = false;
8447 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008448 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8449 if (LHSOK) {
8450 LHS.makeComplexFloat();
8451 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8452 }
8453 } else {
8454 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8455 }
George Burgess IVa145e252016-05-25 22:38:36 +00008456 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008457 return false;
8458
Chandler Carruthb29a7432014-10-11 11:03:30 +00008459 if (E->getRHS()->getType()->isRealFloatingType()) {
8460 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8461 return false;
8462 RHS.makeComplexFloat();
8463 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8464 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008465 return false;
8466
8467 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008468 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008469 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008470 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008471 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8472
John McCalle3027922010-08-25 11:45:40 +00008473 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008474 return Success((CR_r == APFloat::cmpEqual &&
8475 CR_i == APFloat::cmpEqual), E);
8476 else {
John McCalle3027922010-08-25 11:45:40 +00008477 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008478 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008479 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008480 CR_r == APFloat::cmpLessThan ||
8481 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008482 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008483 CR_i == APFloat::cmpLessThan ||
8484 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008485 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008486 } else {
John McCalle3027922010-08-25 11:45:40 +00008487 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008488 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8489 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8490 else {
John McCalle3027922010-08-25 11:45:40 +00008491 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008492 "Invalid compex comparison.");
8493 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8494 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8495 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008496 }
8497 }
Mike Stump11289f42009-09-09 15:08:12 +00008498
Anders Carlssonacc79812008-11-16 07:17:21 +00008499 if (LHSTy->isRealFloatingType() &&
8500 RHSTy->isRealFloatingType()) {
8501 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008502
Richard Smith253c2a32012-01-27 01:14:48 +00008503 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008504 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008505 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008506
Richard Smith253c2a32012-01-27 01:14:48 +00008507 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008508 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008509
Anders Carlssonacc79812008-11-16 07:17:21 +00008510 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008511
Anders Carlssonacc79812008-11-16 07:17:21 +00008512 switch (E->getOpcode()) {
8513 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008514 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008515 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008516 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008517 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008518 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008519 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008520 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008521 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008522 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008523 E);
John McCalle3027922010-08-25 11:45:40 +00008524 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008525 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008526 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008527 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008528 || CR == APFloat::cmpLessThan
8529 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008530 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008531 }
Mike Stump11289f42009-09-09 15:08:12 +00008532
Eli Friedmana38da572009-04-28 19:17:36 +00008533 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008534 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008535 LValue LHSValue, RHSValue;
8536
8537 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008538 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008539 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008540
Richard Smith253c2a32012-01-27 01:14:48 +00008541 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008542 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008543
Richard Smith8b3497e2011-10-31 01:37:14 +00008544 // Reject differing bases from the normal codepath; we special-case
8545 // comparisons to null.
8546 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008547 if (E->getOpcode() == BO_Sub) {
8548 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008549 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008550 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008551 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008552 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008553 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008554 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008555 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8556 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8557 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008558 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008559 // Make sure both labels come from the same function.
8560 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8561 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008562 return Error(E);
8563 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008564 }
Richard Smith83c68212011-10-31 05:11:32 +00008565 // Inequalities and subtractions between unrelated pointers have
8566 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008567 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008568 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008569 // A constant address may compare equal to the address of a symbol.
8570 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008571 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008572 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8573 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008574 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008575 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008576 // distinct addresses. In clang, the result of such a comparison is
8577 // unspecified, so it is not a constant expression. However, we do know
8578 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008579 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8580 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008581 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008582 // We can't tell whether weak symbols will end up pointing to the same
8583 // object.
8584 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008585 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008586 // We can't compare the address of the start of one object with the
8587 // past-the-end address of another object, per C++ DR1652.
8588 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8589 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8590 (RHSValue.Base && RHSValue.Offset.isZero() &&
8591 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8592 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008593 // We can't tell whether an object is at the same address as another
8594 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008595 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8596 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008597 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008598 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008599 // (Note that clang defaults to -fmerge-all-constants, which can
8600 // lead to inconsistent results for comparisons involving the address
8601 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008602 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008603 }
Eli Friedman64004332009-03-23 04:38:34 +00008604
Richard Smith1b470412012-02-01 08:10:20 +00008605 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8606 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8607
Richard Smith84f6dcf2012-02-02 01:16:57 +00008608 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8609 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8610
John McCalle3027922010-08-25 11:45:40 +00008611 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008612 // C++11 [expr.add]p6:
8613 // Unless both pointers point to elements of the same array object, or
8614 // one past the last element of the array object, the behavior is
8615 // undefined.
8616 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8617 !AreElementsOfSameArray(getType(LHSValue.Base),
8618 LHSDesignator, RHSDesignator))
8619 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8620
Chris Lattner882bdf22010-04-20 17:13:14 +00008621 QualType Type = E->getLHS()->getType();
8622 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008623
Richard Smithd62306a2011-11-10 06:34:14 +00008624 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008625 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008626 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008627
Richard Smith84c6b3d2013-09-10 21:34:14 +00008628 // As an extension, a type may have zero size (empty struct or union in
8629 // C, array of zero length). Pointer subtraction in such cases has
8630 // undefined behavior, so is not constant.
8631 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008632 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008633 << ElementType;
8634 return false;
8635 }
8636
Richard Smith1b470412012-02-01 08:10:20 +00008637 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8638 // and produce incorrect results when it overflows. Such behavior
8639 // appears to be non-conforming, but is common, so perhaps we should
8640 // assume the standard intended for such cases to be undefined behavior
8641 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008642
Richard Smith1b470412012-02-01 08:10:20 +00008643 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8644 // overflow in the final conversion to ptrdiff_t.
8645 APSInt LHS(
8646 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8647 APSInt RHS(
8648 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8649 APSInt ElemSize(
8650 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8651 APSInt TrueResult = (LHS - RHS) / ElemSize;
8652 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8653
Richard Smith0c6124b2015-12-03 01:36:22 +00008654 if (Result.extend(65) != TrueResult &&
8655 !HandleOverflow(Info, E, TrueResult, E->getType()))
8656 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008657 return Success(Result, E);
8658 }
Richard Smithde21b242012-01-31 06:41:30 +00008659
8660 // C++11 [expr.rel]p3:
8661 // Pointers to void (after pointer conversions) can be compared, with a
8662 // result defined as follows: If both pointers represent the same
8663 // address or are both the null pointer value, the result is true if the
8664 // operator is <= or >= and false otherwise; otherwise the result is
8665 // unspecified.
8666 // We interpret this as applying to pointers to *cv* void.
8667 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008668 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008669 CCEDiag(E, diag::note_constexpr_void_comparison);
8670
Richard Smith84f6dcf2012-02-02 01:16:57 +00008671 // C++11 [expr.rel]p2:
8672 // - If two pointers point to non-static data members of the same object,
8673 // or to subobjects or array elements fo such members, recursively, the
8674 // pointer to the later declared member compares greater provided the
8675 // two members have the same access control and provided their class is
8676 // not a union.
8677 // [...]
8678 // - Otherwise pointer comparisons are unspecified.
8679 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8680 E->isRelationalOp()) {
8681 bool WasArrayIndex;
8682 unsigned Mismatch =
8683 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8684 RHSDesignator, WasArrayIndex);
8685 // At the point where the designators diverge, the comparison has a
8686 // specified value if:
8687 // - we are comparing array indices
8688 // - we are comparing fields of a union, or fields with the same access
8689 // Otherwise, the result is unspecified and thus the comparison is not a
8690 // constant expression.
8691 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8692 Mismatch < RHSDesignator.Entries.size()) {
8693 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8694 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8695 if (!LF && !RF)
8696 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8697 else if (!LF)
8698 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8699 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8700 << RF->getParent() << RF;
8701 else if (!RF)
8702 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8703 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8704 << LF->getParent() << LF;
8705 else if (!LF->getParent()->isUnion() &&
8706 LF->getAccess() != RF->getAccess())
8707 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8708 << LF << LF->getAccess() << RF << RF->getAccess()
8709 << LF->getParent();
8710 }
8711 }
8712
Eli Friedman6c31cb42012-04-16 04:30:08 +00008713 // The comparison here must be unsigned, and performed with the same
8714 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008715 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8716 uint64_t CompareLHS = LHSOffset.getQuantity();
8717 uint64_t CompareRHS = RHSOffset.getQuantity();
8718 assert(PtrSize <= 64 && "Unexpected pointer width");
8719 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8720 CompareLHS &= Mask;
8721 CompareRHS &= Mask;
8722
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008723 // If there is a base and this is a relational operator, we can only
8724 // compare pointers within the object in question; otherwise, the result
8725 // depends on where the object is located in memory.
8726 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8727 QualType BaseTy = getType(LHSValue.Base);
8728 if (BaseTy->isIncompleteType())
8729 return Error(E);
8730 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8731 uint64_t OffsetLimit = Size.getQuantity();
8732 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8733 return Error(E);
8734 }
8735
Richard Smith8b3497e2011-10-31 01:37:14 +00008736 switch (E->getOpcode()) {
8737 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008738 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8739 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8740 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8741 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8742 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8743 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008744 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008745 }
8746 }
Richard Smith7bb00672012-02-01 01:42:44 +00008747
8748 if (LHSTy->isMemberPointerType()) {
8749 assert(E->isEqualityOp() && "unexpected member pointer operation");
8750 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8751
8752 MemberPtr LHSValue, RHSValue;
8753
8754 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008755 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008756 return false;
8757
8758 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8759 return false;
8760
8761 // C++11 [expr.eq]p2:
8762 // If both operands are null, they compare equal. Otherwise if only one is
8763 // null, they compare unequal.
8764 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8765 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8766 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8767 }
8768
8769 // Otherwise if either is a pointer to a virtual member function, the
8770 // result is unspecified.
8771 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8772 if (MD->isVirtual())
8773 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8774 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8775 if (MD->isVirtual())
8776 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8777
8778 // Otherwise they compare equal if and only if they would refer to the
8779 // same member of the same most derived object or the same subobject if
8780 // they were dereferenced with a hypothetical object of the associated
8781 // class type.
8782 bool Equal = LHSValue == RHSValue;
8783 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8784 }
8785
Richard Smithab44d9b2012-02-14 22:35:28 +00008786 if (LHSTy->isNullPtrType()) {
8787 assert(E->isComparisonOp() && "unexpected nullptr operation");
8788 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8789 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8790 // are compared, the result is true of the operator is <=, >= or ==, and
8791 // false otherwise.
8792 BinaryOperator::Opcode Opcode = E->getOpcode();
8793 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8794 }
8795
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008796 assert((!LHSTy->isIntegralOrEnumerationType() ||
8797 !RHSTy->isIntegralOrEnumerationType()) &&
8798 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8799 // We can't continue from here for non-integral types.
8800 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008801}
8802
Peter Collingbournee190dee2011-03-11 19:24:49 +00008803/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8804/// a result as the expression's type.
8805bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8806 const UnaryExprOrTypeTraitExpr *E) {
8807 switch(E->getKind()) {
8808 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008809 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008810 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008811 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008812 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008813 }
Eli Friedman64004332009-03-23 04:38:34 +00008814
Peter Collingbournee190dee2011-03-11 19:24:49 +00008815 case UETT_VecStep: {
8816 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008817
Peter Collingbournee190dee2011-03-11 19:24:49 +00008818 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008819 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008820
Peter Collingbournee190dee2011-03-11 19:24:49 +00008821 // The vec_step built-in functions that take a 3-component
8822 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8823 if (n == 3)
8824 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008825
Peter Collingbournee190dee2011-03-11 19:24:49 +00008826 return Success(n, E);
8827 } else
8828 return Success(1, E);
8829 }
8830
8831 case UETT_SizeOf: {
8832 QualType SrcTy = E->getTypeOfArgument();
8833 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8834 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008835 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8836 SrcTy = Ref->getPointeeType();
8837
Richard Smithd62306a2011-11-10 06:34:14 +00008838 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008839 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008840 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008841 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008842 }
Alexey Bataev00396512015-07-02 03:40:19 +00008843 case UETT_OpenMPRequiredSimdAlign:
8844 assert(E->isArgumentType());
8845 return Success(
8846 Info.Ctx.toCharUnitsFromBits(
8847 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8848 .getQuantity(),
8849 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008850 }
8851
8852 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008853}
8854
Peter Collingbournee9200682011-05-13 03:29:01 +00008855bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008856 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008857 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008858 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008859 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008860 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008861 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008862 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008863 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008864 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008865 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008866 APSInt IdxResult;
8867 if (!EvaluateInteger(Idx, IdxResult, Info))
8868 return false;
8869 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8870 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008871 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008872 CurrentType = AT->getElementType();
8873 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8874 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008875 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008876 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008877
James Y Knight7281c352015-12-29 22:31:18 +00008878 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008879 FieldDecl *MemberDecl = ON.getField();
8880 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008881 if (!RT)
8882 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008883 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008884 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008885 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008886 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008887 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008888 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008889 CurrentType = MemberDecl->getType().getNonReferenceType();
8890 break;
8891 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008892
James Y Knight7281c352015-12-29 22:31:18 +00008893 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008894 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008895
James Y Knight7281c352015-12-29 22:31:18 +00008896 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008897 CXXBaseSpecifier *BaseSpec = ON.getBase();
8898 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008899 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008900
8901 // Find the layout of the class whose base we are looking into.
8902 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008903 if (!RT)
8904 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008905 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008906 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008907 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8908
8909 // Find the base class itself.
8910 CurrentType = BaseSpec->getType();
8911 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8912 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008913 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008914
Douglas Gregord1702062010-04-29 00:18:15 +00008915 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008916 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008917 break;
8918 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008919 }
8920 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008921 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008922}
8923
Chris Lattnere13042c2008-07-11 19:10:17 +00008924bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008925 switch (E->getOpcode()) {
8926 default:
8927 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8928 // See C99 6.6p3.
8929 return Error(E);
8930 case UO_Extension:
8931 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8932 // If so, we could clear the diagnostic ID.
8933 return Visit(E->getSubExpr());
8934 case UO_Plus:
8935 // The result is just the value.
8936 return Visit(E->getSubExpr());
8937 case UO_Minus: {
8938 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008939 return false;
8940 if (!Result.isInt()) return Error(E);
8941 const APSInt &Value = Result.getInt();
8942 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8943 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8944 E->getType()))
8945 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008946 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008947 }
8948 case UO_Not: {
8949 if (!Visit(E->getSubExpr()))
8950 return false;
8951 if (!Result.isInt()) return Error(E);
8952 return Success(~Result.getInt(), E);
8953 }
8954 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008955 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008956 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008957 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008958 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008959 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008960 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008961}
Mike Stump11289f42009-09-09 15:08:12 +00008962
Chris Lattner477c4be2008-07-12 01:15:53 +00008963/// HandleCast - This is used to evaluate implicit or explicit casts where the
8964/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008965bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8966 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008967 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008968 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008969
Eli Friedmanc757de22011-03-25 00:43:55 +00008970 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008971 case CK_BaseToDerived:
8972 case CK_DerivedToBase:
8973 case CK_UncheckedDerivedToBase:
8974 case CK_Dynamic:
8975 case CK_ToUnion:
8976 case CK_ArrayToPointerDecay:
8977 case CK_FunctionToPointerDecay:
8978 case CK_NullToPointer:
8979 case CK_NullToMemberPointer:
8980 case CK_BaseToDerivedMemberPointer:
8981 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008982 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008983 case CK_ConstructorConversion:
8984 case CK_IntegralToPointer:
8985 case CK_ToVoid:
8986 case CK_VectorSplat:
8987 case CK_IntegralToFloating:
8988 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008989 case CK_CPointerToObjCPointerCast:
8990 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008991 case CK_AnyPointerToBlockPointerCast:
8992 case CK_ObjCObjectLValueCast:
8993 case CK_FloatingRealToComplex:
8994 case CK_FloatingComplexToReal:
8995 case CK_FloatingComplexCast:
8996 case CK_FloatingComplexToIntegralComplex:
8997 case CK_IntegralRealToComplex:
8998 case CK_IntegralComplexCast:
8999 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009000 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009001 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009002 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009003 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009004 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009005 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009006 llvm_unreachable("invalid cast kind for integral value");
9007
Eli Friedman9faf2f92011-03-25 19:07:11 +00009008 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009009 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009010 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009011 case CK_ARCProduceObject:
9012 case CK_ARCConsumeObject:
9013 case CK_ARCReclaimReturnedObject:
9014 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009015 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009016 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009017
Richard Smith4ef685b2012-01-17 21:17:26 +00009018 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009019 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009020 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009021 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009022 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009023
9024 case CK_MemberPointerToBoolean:
9025 case CK_PointerToBoolean:
9026 case CK_IntegralToBoolean:
9027 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009028 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009029 case CK_FloatingComplexToBoolean:
9030 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009031 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009032 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009033 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009034 uint64_t IntResult = BoolResult;
9035 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9036 IntResult = (uint64_t)-1;
9037 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009038 }
9039
Eli Friedmanc757de22011-03-25 00:43:55 +00009040 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009041 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009042 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009043
Eli Friedman742421e2009-02-20 01:15:07 +00009044 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009045 // Allow casts of address-of-label differences if they are no-ops
9046 // or narrowing. (The narrowing case isn't actually guaranteed to
9047 // be constant-evaluatable except in some narrow cases which are hard
9048 // to detect here. We let it through on the assumption the user knows
9049 // what they are doing.)
9050 if (Result.isAddrLabelDiff())
9051 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009052 // Only allow casts of lvalues if they are lossless.
9053 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9054 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009055
Richard Smith911e1422012-01-30 22:27:01 +00009056 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9057 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009058 }
Mike Stump11289f42009-09-09 15:08:12 +00009059
Eli Friedmanc757de22011-03-25 00:43:55 +00009060 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009061 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9062
John McCall45d55e42010-05-07 21:00:08 +00009063 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009064 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009065 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009066
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009067 if (LV.getLValueBase()) {
9068 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009069 // FIXME: Allow a larger integer size than the pointer size, and allow
9070 // narrowing back down to pointer width in subsequent integral casts.
9071 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009072 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009073 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009074
Richard Smithcf74da72011-11-16 07:18:12 +00009075 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009076 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009077 return true;
9078 }
9079
Yaxun Liu402804b2016-12-15 08:09:08 +00009080 uint64_t V;
9081 if (LV.isNullPointer())
9082 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9083 else
9084 V = LV.getLValueOffset().getQuantity();
9085
9086 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009087 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009088 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009089
Eli Friedmanc757de22011-03-25 00:43:55 +00009090 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009091 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009092 if (!EvaluateComplex(SubExpr, C, Info))
9093 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009094 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009095 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009096
Eli Friedmanc757de22011-03-25 00:43:55 +00009097 case CK_FloatingToIntegral: {
9098 APFloat F(0.0);
9099 if (!EvaluateFloat(SubExpr, F, Info))
9100 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009101
Richard Smith357362d2011-12-13 06:39:58 +00009102 APSInt Value;
9103 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9104 return false;
9105 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009106 }
9107 }
Mike Stump11289f42009-09-09 15:08:12 +00009108
Eli Friedmanc757de22011-03-25 00:43:55 +00009109 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009110}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009111
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009112bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9113 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009114 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009115 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9116 return false;
9117 if (!LV.isComplexInt())
9118 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009119 return Success(LV.getComplexIntReal(), E);
9120 }
9121
9122 return Visit(E->getSubExpr());
9123}
9124
Eli Friedman4e7a2412009-02-27 04:45:43 +00009125bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009126 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009127 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009128 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9129 return false;
9130 if (!LV.isComplexInt())
9131 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009132 return Success(LV.getComplexIntImag(), E);
9133 }
9134
Richard Smith4a678122011-10-24 18:44:57 +00009135 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009136 return Success(0, E);
9137}
9138
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009139bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9140 return Success(E->getPackLength(), E);
9141}
9142
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009143bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9144 return Success(E->getValue(), E);
9145}
9146
Chris Lattner05706e882008-07-11 18:11:29 +00009147//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009148// Float Evaluation
9149//===----------------------------------------------------------------------===//
9150
9151namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009152class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009153 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009154 APFloat &Result;
9155public:
9156 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009157 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009158
Richard Smith2e312c82012-03-03 22:46:17 +00009159 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009160 Result = V.getFloat();
9161 return true;
9162 }
Eli Friedman24c01542008-08-22 00:06:13 +00009163
Richard Smithfddd3842011-12-30 21:15:51 +00009164 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009165 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9166 return true;
9167 }
9168
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009169 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009170
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009171 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009172 bool VisitBinaryOperator(const BinaryOperator *E);
9173 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009174 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009175
John McCallb1fb0d32010-05-07 22:08:54 +00009176 bool VisitUnaryReal(const UnaryOperator *E);
9177 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009178
Richard Smithfddd3842011-12-30 21:15:51 +00009179 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009180};
9181} // end anonymous namespace
9182
9183static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009184 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009185 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009186}
9187
Jay Foad39c79802011-01-12 09:06:06 +00009188static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009189 QualType ResultTy,
9190 const Expr *Arg,
9191 bool SNaN,
9192 llvm::APFloat &Result) {
9193 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9194 if (!S) return false;
9195
9196 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9197
9198 llvm::APInt fill;
9199
9200 // Treat empty strings as if they were zero.
9201 if (S->getString().empty())
9202 fill = llvm::APInt(32, 0);
9203 else if (S->getString().getAsInteger(0, fill))
9204 return false;
9205
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009206 if (Context.getTargetInfo().isNan2008()) {
9207 if (SNaN)
9208 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9209 else
9210 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9211 } else {
9212 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9213 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9214 // a different encoding to what became a standard in 2008, and for pre-
9215 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9216 // sNaN. This is now known as "legacy NaN" encoding.
9217 if (SNaN)
9218 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9219 else
9220 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9221 }
9222
John McCall16291492010-02-28 13:00:19 +00009223 return true;
9224}
9225
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009226bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009227 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009228 default:
9229 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9230
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009231 case Builtin::BI__builtin_huge_val:
9232 case Builtin::BI__builtin_huge_valf:
9233 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009234 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009235 case Builtin::BI__builtin_inf:
9236 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009237 case Builtin::BI__builtin_infl:
9238 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009239 const llvm::fltSemantics &Sem =
9240 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009241 Result = llvm::APFloat::getInf(Sem);
9242 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009243 }
Mike Stump11289f42009-09-09 15:08:12 +00009244
John McCall16291492010-02-28 13:00:19 +00009245 case Builtin::BI__builtin_nans:
9246 case Builtin::BI__builtin_nansf:
9247 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009248 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009249 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9250 true, Result))
9251 return Error(E);
9252 return true;
John McCall16291492010-02-28 13:00:19 +00009253
Chris Lattner0b7282e2008-10-06 06:31:58 +00009254 case Builtin::BI__builtin_nan:
9255 case Builtin::BI__builtin_nanf:
9256 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009257 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009258 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009259 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009260 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9261 false, Result))
9262 return Error(E);
9263 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009264
9265 case Builtin::BI__builtin_fabs:
9266 case Builtin::BI__builtin_fabsf:
9267 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009268 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009269 if (!EvaluateFloat(E->getArg(0), Result, Info))
9270 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009271
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009272 if (Result.isNegative())
9273 Result.changeSign();
9274 return true;
9275
Richard Smith8889a3d2013-06-13 06:26:32 +00009276 // FIXME: Builtin::BI__builtin_powi
9277 // FIXME: Builtin::BI__builtin_powif
9278 // FIXME: Builtin::BI__builtin_powil
9279
Mike Stump11289f42009-09-09 15:08:12 +00009280 case Builtin::BI__builtin_copysign:
9281 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009282 case Builtin::BI__builtin_copysignl:
9283 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009284 APFloat RHS(0.);
9285 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9286 !EvaluateFloat(E->getArg(1), RHS, Info))
9287 return false;
9288 Result.copySign(RHS);
9289 return true;
9290 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009291 }
9292}
9293
John McCallb1fb0d32010-05-07 22:08:54 +00009294bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009295 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9296 ComplexValue CV;
9297 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9298 return false;
9299 Result = CV.FloatReal;
9300 return true;
9301 }
9302
9303 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009304}
9305
9306bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009307 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9308 ComplexValue CV;
9309 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9310 return false;
9311 Result = CV.FloatImag;
9312 return true;
9313 }
9314
Richard Smith4a678122011-10-24 18:44:57 +00009315 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009316 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9317 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009318 return true;
9319}
9320
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009321bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009322 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009323 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009324 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009325 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009326 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009327 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9328 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009329 Result.changeSign();
9330 return true;
9331 }
9332}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009333
Eli Friedman24c01542008-08-22 00:06:13 +00009334bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009335 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9336 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009337
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009338 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009339 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009340 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009341 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009342 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9343 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009344}
9345
9346bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9347 Result = E->getValue();
9348 return true;
9349}
9350
Peter Collingbournee9200682011-05-13 03:29:01 +00009351bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9352 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009353
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009354 switch (E->getCastKind()) {
9355 default:
Richard Smith11562c52011-10-28 17:51:58 +00009356 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009357
9358 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009359 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009360 return EvaluateInteger(SubExpr, IntResult, Info) &&
9361 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9362 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009363 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009364
9365 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009366 if (!Visit(SubExpr))
9367 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009368 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9369 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009370 }
John McCalld7646252010-11-14 08:17:51 +00009371
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009372 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009373 ComplexValue V;
9374 if (!EvaluateComplex(SubExpr, V, Info))
9375 return false;
9376 Result = V.getComplexFloatReal();
9377 return true;
9378 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009379 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009380}
9381
Eli Friedman24c01542008-08-22 00:06:13 +00009382//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009383// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009384//===----------------------------------------------------------------------===//
9385
9386namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009387class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009388 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009389 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009390
Anders Carlsson537969c2008-11-16 20:27:53 +00009391public:
John McCall93d91dc2010-05-07 17:22:02 +00009392 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009393 : ExprEvaluatorBaseTy(info), Result(Result) {}
9394
Richard Smith2e312c82012-03-03 22:46:17 +00009395 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009396 Result.setFrom(V);
9397 return true;
9398 }
Mike Stump11289f42009-09-09 15:08:12 +00009399
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009400 bool ZeroInitialization(const Expr *E);
9401
Anders Carlsson537969c2008-11-16 20:27:53 +00009402 //===--------------------------------------------------------------------===//
9403 // Visitor Methods
9404 //===--------------------------------------------------------------------===//
9405
Peter Collingbournee9200682011-05-13 03:29:01 +00009406 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009407 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009408 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009409 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009410 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009411};
9412} // end anonymous namespace
9413
John McCall93d91dc2010-05-07 17:22:02 +00009414static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9415 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009416 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009417 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009418}
9419
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009420bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009421 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009422 if (ElemTy->isRealFloatingType()) {
9423 Result.makeComplexFloat();
9424 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9425 Result.FloatReal = Zero;
9426 Result.FloatImag = Zero;
9427 } else {
9428 Result.makeComplexInt();
9429 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9430 Result.IntReal = Zero;
9431 Result.IntImag = Zero;
9432 }
9433 return true;
9434}
9435
Peter Collingbournee9200682011-05-13 03:29:01 +00009436bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9437 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009438
9439 if (SubExpr->getType()->isRealFloatingType()) {
9440 Result.makeComplexFloat();
9441 APFloat &Imag = Result.FloatImag;
9442 if (!EvaluateFloat(SubExpr, Imag, Info))
9443 return false;
9444
9445 Result.FloatReal = APFloat(Imag.getSemantics());
9446 return true;
9447 } else {
9448 assert(SubExpr->getType()->isIntegerType() &&
9449 "Unexpected imaginary literal.");
9450
9451 Result.makeComplexInt();
9452 APSInt &Imag = Result.IntImag;
9453 if (!EvaluateInteger(SubExpr, Imag, Info))
9454 return false;
9455
9456 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9457 return true;
9458 }
9459}
9460
Peter Collingbournee9200682011-05-13 03:29:01 +00009461bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009462
John McCallfcef3cf2010-12-14 17:51:41 +00009463 switch (E->getCastKind()) {
9464 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009465 case CK_BaseToDerived:
9466 case CK_DerivedToBase:
9467 case CK_UncheckedDerivedToBase:
9468 case CK_Dynamic:
9469 case CK_ToUnion:
9470 case CK_ArrayToPointerDecay:
9471 case CK_FunctionToPointerDecay:
9472 case CK_NullToPointer:
9473 case CK_NullToMemberPointer:
9474 case CK_BaseToDerivedMemberPointer:
9475 case CK_DerivedToBaseMemberPointer:
9476 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009477 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009478 case CK_ConstructorConversion:
9479 case CK_IntegralToPointer:
9480 case CK_PointerToIntegral:
9481 case CK_PointerToBoolean:
9482 case CK_ToVoid:
9483 case CK_VectorSplat:
9484 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009485 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009486 case CK_IntegralToBoolean:
9487 case CK_IntegralToFloating:
9488 case CK_FloatingToIntegral:
9489 case CK_FloatingToBoolean:
9490 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009491 case CK_CPointerToObjCPointerCast:
9492 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009493 case CK_AnyPointerToBlockPointerCast:
9494 case CK_ObjCObjectLValueCast:
9495 case CK_FloatingComplexToReal:
9496 case CK_FloatingComplexToBoolean:
9497 case CK_IntegralComplexToReal:
9498 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009499 case CK_ARCProduceObject:
9500 case CK_ARCConsumeObject:
9501 case CK_ARCReclaimReturnedObject:
9502 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009503 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009504 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009505 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009506 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009507 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009508 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009509 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009510 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009511
John McCallfcef3cf2010-12-14 17:51:41 +00009512 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009513 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009514 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009515 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009516
9517 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009518 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009519 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009520 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009521
9522 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009523 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009524 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009525 return false;
9526
John McCallfcef3cf2010-12-14 17:51:41 +00009527 Result.makeComplexFloat();
9528 Result.FloatImag = APFloat(Real.getSemantics());
9529 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009530 }
9531
John McCallfcef3cf2010-12-14 17:51:41 +00009532 case CK_FloatingComplexCast: {
9533 if (!Visit(E->getSubExpr()))
9534 return false;
9535
9536 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9537 QualType From
9538 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9539
Richard Smith357362d2011-12-13 06:39:58 +00009540 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9541 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009542 }
9543
9544 case CK_FloatingComplexToIntegralComplex: {
9545 if (!Visit(E->getSubExpr()))
9546 return false;
9547
9548 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9549 QualType From
9550 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9551 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009552 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9553 To, Result.IntReal) &&
9554 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9555 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009556 }
9557
9558 case CK_IntegralRealToComplex: {
9559 APSInt &Real = Result.IntReal;
9560 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9561 return false;
9562
9563 Result.makeComplexInt();
9564 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9565 return true;
9566 }
9567
9568 case CK_IntegralComplexCast: {
9569 if (!Visit(E->getSubExpr()))
9570 return false;
9571
9572 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9573 QualType From
9574 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9575
Richard Smith911e1422012-01-30 22:27:01 +00009576 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9577 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009578 return true;
9579 }
9580
9581 case CK_IntegralComplexToFloatingComplex: {
9582 if (!Visit(E->getSubExpr()))
9583 return false;
9584
Ted Kremenek28831752012-08-23 20:46:57 +00009585 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009586 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009587 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009588 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009589 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9590 To, Result.FloatReal) &&
9591 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9592 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009593 }
9594 }
9595
9596 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009597}
9598
John McCall93d91dc2010-05-07 17:22:02 +00009599bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009600 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009601 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9602
Chandler Carrutha216cad2014-10-11 00:57:18 +00009603 // Track whether the LHS or RHS is real at the type system level. When this is
9604 // the case we can simplify our evaluation strategy.
9605 bool LHSReal = false, RHSReal = false;
9606
9607 bool LHSOK;
9608 if (E->getLHS()->getType()->isRealFloatingType()) {
9609 LHSReal = true;
9610 APFloat &Real = Result.FloatReal;
9611 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9612 if (LHSOK) {
9613 Result.makeComplexFloat();
9614 Result.FloatImag = APFloat(Real.getSemantics());
9615 }
9616 } else {
9617 LHSOK = Visit(E->getLHS());
9618 }
George Burgess IVa145e252016-05-25 22:38:36 +00009619 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009620 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009621
John McCall93d91dc2010-05-07 17:22:02 +00009622 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009623 if (E->getRHS()->getType()->isRealFloatingType()) {
9624 RHSReal = true;
9625 APFloat &Real = RHS.FloatReal;
9626 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9627 return false;
9628 RHS.makeComplexFloat();
9629 RHS.FloatImag = APFloat(Real.getSemantics());
9630 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009631 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009632
Chandler Carrutha216cad2014-10-11 00:57:18 +00009633 assert(!(LHSReal && RHSReal) &&
9634 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009635 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009636 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009637 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009638 if (Result.isComplexFloat()) {
9639 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9640 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009641 if (LHSReal)
9642 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9643 else if (!RHSReal)
9644 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9645 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009646 } else {
9647 Result.getComplexIntReal() += RHS.getComplexIntReal();
9648 Result.getComplexIntImag() += RHS.getComplexIntImag();
9649 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009650 break;
John McCalle3027922010-08-25 11:45:40 +00009651 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009652 if (Result.isComplexFloat()) {
9653 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9654 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009655 if (LHSReal) {
9656 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9657 Result.getComplexFloatImag().changeSign();
9658 } else if (!RHSReal) {
9659 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9660 APFloat::rmNearestTiesToEven);
9661 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009662 } else {
9663 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9664 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9665 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009666 break;
John McCalle3027922010-08-25 11:45:40 +00009667 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009668 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009669 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009670 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009671 // following naming scheme:
9672 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009673 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009674 APFloat &A = LHS.getComplexFloatReal();
9675 APFloat &B = LHS.getComplexFloatImag();
9676 APFloat &C = RHS.getComplexFloatReal();
9677 APFloat &D = RHS.getComplexFloatImag();
9678 APFloat &ResR = Result.getComplexFloatReal();
9679 APFloat &ResI = Result.getComplexFloatImag();
9680 if (LHSReal) {
9681 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9682 ResR = A * C;
9683 ResI = A * D;
9684 } else if (RHSReal) {
9685 ResR = C * A;
9686 ResI = C * B;
9687 } else {
9688 // In the fully general case, we need to handle NaNs and infinities
9689 // robustly.
9690 APFloat AC = A * C;
9691 APFloat BD = B * D;
9692 APFloat AD = A * D;
9693 APFloat BC = B * C;
9694 ResR = AC - BD;
9695 ResI = AD + BC;
9696 if (ResR.isNaN() && ResI.isNaN()) {
9697 bool Recalc = false;
9698 if (A.isInfinity() || B.isInfinity()) {
9699 A = APFloat::copySign(
9700 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9701 B = APFloat::copySign(
9702 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9703 if (C.isNaN())
9704 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9705 if (D.isNaN())
9706 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9707 Recalc = true;
9708 }
9709 if (C.isInfinity() || D.isInfinity()) {
9710 C = APFloat::copySign(
9711 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9712 D = APFloat::copySign(
9713 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9714 if (A.isNaN())
9715 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9716 if (B.isNaN())
9717 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9718 Recalc = true;
9719 }
9720 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9721 AD.isInfinity() || BC.isInfinity())) {
9722 if (A.isNaN())
9723 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9724 if (B.isNaN())
9725 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9726 if (C.isNaN())
9727 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9728 if (D.isNaN())
9729 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9730 Recalc = true;
9731 }
9732 if (Recalc) {
9733 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9734 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9735 }
9736 }
9737 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009738 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009739 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009740 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009741 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9742 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009743 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009744 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9745 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9746 }
9747 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009748 case BO_Div:
9749 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009750 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009751 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009752 // following naming scheme:
9753 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009754 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009755 APFloat &A = LHS.getComplexFloatReal();
9756 APFloat &B = LHS.getComplexFloatImag();
9757 APFloat &C = RHS.getComplexFloatReal();
9758 APFloat &D = RHS.getComplexFloatImag();
9759 APFloat &ResR = Result.getComplexFloatReal();
9760 APFloat &ResI = Result.getComplexFloatImag();
9761 if (RHSReal) {
9762 ResR = A / C;
9763 ResI = B / C;
9764 } else {
9765 if (LHSReal) {
9766 // No real optimizations we can do here, stub out with zero.
9767 B = APFloat::getZero(A.getSemantics());
9768 }
9769 int DenomLogB = 0;
9770 APFloat MaxCD = maxnum(abs(C), abs(D));
9771 if (MaxCD.isFinite()) {
9772 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009773 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9774 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009775 }
9776 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009777 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9778 APFloat::rmNearestTiesToEven);
9779 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9780 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009781 if (ResR.isNaN() && ResI.isNaN()) {
9782 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9783 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9784 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9785 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9786 D.isFinite()) {
9787 A = APFloat::copySign(
9788 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9789 B = APFloat::copySign(
9790 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9791 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9792 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9793 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9794 C = APFloat::copySign(
9795 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9796 D = APFloat::copySign(
9797 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9798 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9799 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9800 }
9801 }
9802 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009803 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009804 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9805 return Error(E, diag::note_expr_divide_by_zero);
9806
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009807 ComplexValue LHS = Result;
9808 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9809 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9810 Result.getComplexIntReal() =
9811 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9812 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9813 Result.getComplexIntImag() =
9814 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9815 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9816 }
9817 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009818 }
9819
John McCall93d91dc2010-05-07 17:22:02 +00009820 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009821}
9822
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009823bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9824 // Get the operand value into 'Result'.
9825 if (!Visit(E->getSubExpr()))
9826 return false;
9827
9828 switch (E->getOpcode()) {
9829 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009830 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009831 case UO_Extension:
9832 return true;
9833 case UO_Plus:
9834 // The result is always just the subexpr.
9835 return true;
9836 case UO_Minus:
9837 if (Result.isComplexFloat()) {
9838 Result.getComplexFloatReal().changeSign();
9839 Result.getComplexFloatImag().changeSign();
9840 }
9841 else {
9842 Result.getComplexIntReal() = -Result.getComplexIntReal();
9843 Result.getComplexIntImag() = -Result.getComplexIntImag();
9844 }
9845 return true;
9846 case UO_Not:
9847 if (Result.isComplexFloat())
9848 Result.getComplexFloatImag().changeSign();
9849 else
9850 Result.getComplexIntImag() = -Result.getComplexIntImag();
9851 return true;
9852 }
9853}
9854
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009855bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9856 if (E->getNumInits() == 2) {
9857 if (E->getType()->isComplexType()) {
9858 Result.makeComplexFloat();
9859 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9860 return false;
9861 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9862 return false;
9863 } else {
9864 Result.makeComplexInt();
9865 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9866 return false;
9867 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9868 return false;
9869 }
9870 return true;
9871 }
9872 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9873}
9874
Anders Carlsson537969c2008-11-16 20:27:53 +00009875//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009876// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9877// implicit conversion.
9878//===----------------------------------------------------------------------===//
9879
9880namespace {
9881class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009882 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009883 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009884 APValue &Result;
9885public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009886 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9887 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009888
9889 bool Success(const APValue &V, const Expr *E) {
9890 Result = V;
9891 return true;
9892 }
9893
9894 bool ZeroInitialization(const Expr *E) {
9895 ImplicitValueInitExpr VIE(
9896 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009897 // For atomic-qualified class (and array) types in C++, initialize the
9898 // _Atomic-wrapped subobject directly, in-place.
9899 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9900 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009901 }
9902
9903 bool VisitCastExpr(const CastExpr *E) {
9904 switch (E->getCastKind()) {
9905 default:
9906 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9907 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009908 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9909 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009910 }
9911 }
9912};
9913} // end anonymous namespace
9914
Richard Smith64cb9ca2017-02-22 22:09:50 +00009915static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9916 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009917 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009918 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009919}
9920
9921//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009922// Void expression evaluation, primarily for a cast to void on the LHS of a
9923// comma operator
9924//===----------------------------------------------------------------------===//
9925
9926namespace {
9927class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009928 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009929public:
9930 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9931
Richard Smith2e312c82012-03-03 22:46:17 +00009932 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009933
Richard Smith7cd577b2017-08-17 19:35:50 +00009934 bool ZeroInitialization(const Expr *E) { return true; }
9935
Richard Smith42d3af92011-12-07 00:43:50 +00009936 bool VisitCastExpr(const CastExpr *E) {
9937 switch (E->getCastKind()) {
9938 default:
9939 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9940 case CK_ToVoid:
9941 VisitIgnoredValue(E->getSubExpr());
9942 return true;
9943 }
9944 }
Hal Finkela8443c32014-07-17 14:49:58 +00009945
9946 bool VisitCallExpr(const CallExpr *E) {
9947 switch (E->getBuiltinCallee()) {
9948 default:
9949 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9950 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009951 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009952 // The argument is not evaluated!
9953 return true;
9954 }
9955 }
Richard Smith42d3af92011-12-07 00:43:50 +00009956};
9957} // end anonymous namespace
9958
9959static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9960 assert(E->isRValue() && E->getType()->isVoidType());
9961 return VoidExprEvaluator(Info).Visit(E);
9962}
9963
9964//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009965// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009966//===----------------------------------------------------------------------===//
9967
Richard Smith2e312c82012-03-03 22:46:17 +00009968static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009969 // In C, function designators are not lvalues, but we evaluate them as if they
9970 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009971 QualType T = E->getType();
9972 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009973 LValue LV;
9974 if (!EvaluateLValue(E, LV, Info))
9975 return false;
9976 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009977 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009978 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009979 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009980 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009981 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009982 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009983 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009984 LValue LV;
9985 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009986 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009987 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009988 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009989 llvm::APFloat F(0.0);
9990 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009991 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009992 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009993 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009994 ComplexValue C;
9995 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009996 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009997 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009998 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009999 MemberPtr P;
10000 if (!EvaluateMemberPointer(E, P, Info))
10001 return false;
10002 P.moveInto(Result);
10003 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010004 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010005 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010006 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010007 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10008 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010009 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010010 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010011 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010012 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010013 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010014 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10015 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010016 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010017 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010018 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010019 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010020 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010021 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010022 if (!EvaluateVoid(E, Info))
10023 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010024 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010025 QualType Unqual = T.getAtomicUnqualifiedType();
10026 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10027 LValue LV;
10028 LV.set(E, Info.CurrentCall->Index);
10029 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10030 if (!EvaluateAtomic(E, &LV, Value, Info))
10031 return false;
10032 } else {
10033 if (!EvaluateAtomic(E, nullptr, Result, Info))
10034 return false;
10035 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010036 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010037 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010038 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010039 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010040 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010041 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010042 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010043
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010044 return true;
10045}
10046
Richard Smithb228a862012-02-15 02:18:13 +000010047/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10048/// cases, the in-place evaluation is essential, since later initializers for
10049/// an object can indirectly refer to subobjects which were initialized earlier.
10050static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010051 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010052 assert(!E->isValueDependent());
10053
Richard Smith7525ff62013-05-09 07:14:00 +000010054 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010055 return false;
10056
10057 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010058 // Evaluate arrays and record types in-place, so that later initializers can
10059 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010060 QualType T = E->getType();
10061 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010062 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010063 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010064 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010065 else if (T->isAtomicType()) {
10066 QualType Unqual = T.getAtomicUnqualifiedType();
10067 if (Unqual->isArrayType() || Unqual->isRecordType())
10068 return EvaluateAtomic(E, &This, Result, Info);
10069 }
Richard Smithed5165f2011-11-04 05:33:44 +000010070 }
10071
10072 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010073 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010074}
10075
Richard Smithf57d8cb2011-12-09 22:58:01 +000010076/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10077/// lvalue-to-rvalue cast if it is an lvalue.
10078static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010079 if (E->getType().isNull())
10080 return false;
10081
Nick Lewyckyc190f962017-05-02 01:06:16 +000010082 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010083 return false;
10084
Richard Smith2e312c82012-03-03 22:46:17 +000010085 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010086 return false;
10087
10088 if (E->isGLValue()) {
10089 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010090 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010091 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010092 return false;
10093 }
10094
Richard Smith2e312c82012-03-03 22:46:17 +000010095 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010096 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010097}
Richard Smith11562c52011-10-28 17:51:58 +000010098
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010099static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010100 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010101 // Fast-path evaluations of integer literals, since we sometimes see files
10102 // containing vast quantities of these.
10103 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10104 Result.Val = APValue(APSInt(L->getValue(),
10105 L->getType()->isUnsignedIntegerType()));
10106 IsConst = true;
10107 return true;
10108 }
James Dennett0492ef02014-03-14 17:44:10 +000010109
10110 // This case should be rare, but we need to check it before we check on
10111 // the type below.
10112 if (Exp->getType().isNull()) {
10113 IsConst = false;
10114 return true;
10115 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010116
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010117 // FIXME: Evaluating values of large array and record types can cause
10118 // performance problems. Only do so in C++11 for now.
10119 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10120 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010121 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010122 IsConst = false;
10123 return true;
10124 }
10125 return false;
10126}
10127
10128
Richard Smith7b553f12011-10-29 00:50:52 +000010129/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010130/// any crazy technique (that has nothing to do with language standards) that
10131/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010132/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10133/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010134bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010135 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010136 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010137 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010138
Richard Smith6d4c6582013-11-05 22:18:15 +000010139 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010140 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010141}
10142
Jay Foad39c79802011-01-12 09:06:06 +000010143bool Expr::EvaluateAsBooleanCondition(bool &Result,
10144 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010145 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010146 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010147 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010148}
10149
Richard Smithce8eca52015-12-08 03:21:47 +000010150static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10151 Expr::SideEffectsKind SEK) {
10152 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10153 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10154}
10155
Richard Smith5fab0c92011-12-28 19:48:30 +000010156bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10157 SideEffectsKind AllowSideEffects) const {
10158 if (!getType()->isIntegralOrEnumerationType())
10159 return false;
10160
Richard Smith11562c52011-10-28 17:51:58 +000010161 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010162 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010163 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010164 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010165
Richard Smith11562c52011-10-28 17:51:58 +000010166 Result = ExprResult.Val.getInt();
10167 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010168}
10169
Richard Trieube234c32016-04-21 21:04:55 +000010170bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10171 SideEffectsKind AllowSideEffects) const {
10172 if (!getType()->isRealFloatingType())
10173 return false;
10174
10175 EvalResult ExprResult;
10176 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10177 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10178 return false;
10179
10180 Result = ExprResult.Val.getFloat();
10181 return true;
10182}
10183
Jay Foad39c79802011-01-12 09:06:06 +000010184bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010185 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010186
John McCall45d55e42010-05-07 21:00:08 +000010187 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010188 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10189 !CheckLValueConstantExpression(Info, getExprLoc(),
10190 Ctx.getLValueReferenceType(getType()), LV))
10191 return false;
10192
Richard Smith2e312c82012-03-03 22:46:17 +000010193 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010194 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010195}
10196
Richard Smithd0b4dd62011-12-19 06:19:21 +000010197bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10198 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010199 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010200 // FIXME: Evaluating initializers for large array and record types can cause
10201 // performance problems. Only do so in C++11 for now.
10202 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010203 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010204 return false;
10205
Richard Smithd0b4dd62011-12-19 06:19:21 +000010206 Expr::EvalStatus EStatus;
10207 EStatus.Diag = &Notes;
10208
Richard Smith0c6124b2015-12-03 01:36:22 +000010209 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10210 ? EvalInfo::EM_ConstantExpression
10211 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010212 InitInfo.setEvaluatingDecl(VD, Value);
10213
10214 LValue LVal;
10215 LVal.set(VD);
10216
Richard Smithfddd3842011-12-30 21:15:51 +000010217 // C++11 [basic.start.init]p2:
10218 // Variables with static storage duration or thread storage duration shall be
10219 // zero-initialized before any other initialization takes place.
10220 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010221 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010222 !VD->getType()->isReferenceType()) {
10223 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010224 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010225 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010226 return false;
10227 }
10228
Richard Smith7525ff62013-05-09 07:14:00 +000010229 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10230 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010231 EStatus.HasSideEffects)
10232 return false;
10233
10234 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10235 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010236}
10237
Richard Smith7b553f12011-10-29 00:50:52 +000010238/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10239/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010240bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010241 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010242 return EvaluateAsRValue(Result, Ctx) &&
10243 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010244}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010245
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010246APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010247 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010248 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010249 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010250 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010251 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010252 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010253 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010254
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010255 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010256}
John McCall864e3962010-05-07 05:32:02 +000010257
Richard Smithe9ff7702013-11-05 22:23:30 +000010258void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010259 bool IsConst;
10260 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010261 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010262 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010263 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10264 }
10265}
10266
Richard Smithe6c01442013-06-05 00:46:14 +000010267bool Expr::EvalResult::isGlobalLValue() const {
10268 assert(Val.isLValue());
10269 return IsGlobalLValue(Val.getLValueBase());
10270}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010271
10272
John McCall864e3962010-05-07 05:32:02 +000010273/// isIntegerConstantExpr - this recursive routine will test if an expression is
10274/// an integer constant expression.
10275
10276/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10277/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010278
10279// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010280// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10281// and a (possibly null) SourceLocation indicating the location of the problem.
10282//
John McCall864e3962010-05-07 05:32:02 +000010283// Note that to reduce code duplication, this helper does no evaluation
10284// itself; the caller checks whether the expression is evaluatable, and
10285// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010286// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010287
Dan Gohman28ade552010-07-26 21:25:24 +000010288namespace {
10289
Richard Smith9e575da2012-12-28 13:25:52 +000010290enum ICEKind {
10291 /// This expression is an ICE.
10292 IK_ICE,
10293 /// This expression is not an ICE, but if it isn't evaluated, it's
10294 /// a legal subexpression for an ICE. This return value is used to handle
10295 /// the comma operator in C99 mode, and non-constant subexpressions.
10296 IK_ICEIfUnevaluated,
10297 /// This expression is not an ICE, and is not a legal subexpression for one.
10298 IK_NotICE
10299};
10300
John McCall864e3962010-05-07 05:32:02 +000010301struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010302 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010303 SourceLocation Loc;
10304
Richard Smith9e575da2012-12-28 13:25:52 +000010305 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010306};
10307
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010308}
Dan Gohman28ade552010-07-26 21:25:24 +000010309
Richard Smith9e575da2012-12-28 13:25:52 +000010310static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10311
10312static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010313
Craig Toppera31a8822013-08-22 07:09:37 +000010314static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010315 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010316 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010317 !EVResult.Val.isInt())
10318 return ICEDiag(IK_NotICE, E->getLocStart());
10319
John McCall864e3962010-05-07 05:32:02 +000010320 return NoDiag();
10321}
10322
Craig Toppera31a8822013-08-22 07:09:37 +000010323static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010324 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010325 if (!E->getType()->isIntegralOrEnumerationType())
10326 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010327
10328 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010329#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010330#define STMT(Node, Base) case Expr::Node##Class:
10331#define EXPR(Node, Base)
10332#include "clang/AST/StmtNodes.inc"
10333 case Expr::PredefinedExprClass:
10334 case Expr::FloatingLiteralClass:
10335 case Expr::ImaginaryLiteralClass:
10336 case Expr::StringLiteralClass:
10337 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010338 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010339 case Expr::MemberExprClass:
10340 case Expr::CompoundAssignOperatorClass:
10341 case Expr::CompoundLiteralExprClass:
10342 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010343 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010344 case Expr::ArrayInitLoopExprClass:
10345 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010346 case Expr::NoInitExprClass:
10347 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010348 case Expr::ImplicitValueInitExprClass:
10349 case Expr::ParenListExprClass:
10350 case Expr::VAArgExprClass:
10351 case Expr::AddrLabelExprClass:
10352 case Expr::StmtExprClass:
10353 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010354 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010355 case Expr::CXXDynamicCastExprClass:
10356 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010357 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010358 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010359 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010360 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010361 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010362 case Expr::CXXThisExprClass:
10363 case Expr::CXXThrowExprClass:
10364 case Expr::CXXNewExprClass:
10365 case Expr::CXXDeleteExprClass:
10366 case Expr::CXXPseudoDestructorExprClass:
10367 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010368 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010369 case Expr::DependentScopeDeclRefExprClass:
10370 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010371 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010372 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010373 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010374 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010375 case Expr::CXXTemporaryObjectExprClass:
10376 case Expr::CXXUnresolvedConstructExprClass:
10377 case Expr::CXXDependentScopeMemberExprClass:
10378 case Expr::UnresolvedMemberExprClass:
10379 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010380 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010381 case Expr::ObjCArrayLiteralClass:
10382 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010383 case Expr::ObjCEncodeExprClass:
10384 case Expr::ObjCMessageExprClass:
10385 case Expr::ObjCSelectorExprClass:
10386 case Expr::ObjCProtocolExprClass:
10387 case Expr::ObjCIvarRefExprClass:
10388 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010389 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010390 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010391 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010392 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010393 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010394 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010395 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010396 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010397 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010398 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010399 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010400 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010401 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010402 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010403 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010404 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010405 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010406 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010407 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010408 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010409 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010410 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010411
Richard Smithf137f932014-01-25 20:50:08 +000010412 case Expr::InitListExprClass: {
10413 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10414 // form "T x = { a };" is equivalent to "T x = a;".
10415 // Unless we're initializing a reference, T is a scalar as it is known to be
10416 // of integral or enumeration type.
10417 if (E->isRValue())
10418 if (cast<InitListExpr>(E)->getNumInits() == 1)
10419 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10420 return ICEDiag(IK_NotICE, E->getLocStart());
10421 }
10422
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010423 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010424 case Expr::GNUNullExprClass:
10425 // GCC considers the GNU __null value to be an integral constant expression.
10426 return NoDiag();
10427
John McCall7c454bb2011-07-15 05:09:51 +000010428 case Expr::SubstNonTypeTemplateParmExprClass:
10429 return
10430 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10431
John McCall864e3962010-05-07 05:32:02 +000010432 case Expr::ParenExprClass:
10433 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010434 case Expr::GenericSelectionExprClass:
10435 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010436 case Expr::IntegerLiteralClass:
10437 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010438 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010439 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010440 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010441 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010442 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010443 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010444 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010445 return NoDiag();
10446 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010447 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010448 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10449 // constant expressions, but they can never be ICEs because an ICE cannot
10450 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010451 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010452 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010453 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010454 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010455 }
Richard Smith6365c912012-02-24 22:12:32 +000010456 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010457 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10458 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010459 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010460 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010461 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010462 // Parameter variables are never constants. Without this check,
10463 // getAnyInitializer() can find a default argument, which leads
10464 // to chaos.
10465 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010466 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010467
10468 // C++ 7.1.5.1p2
10469 // A variable of non-volatile const-qualified integral or enumeration
10470 // type initialized by an ICE can be used in ICEs.
10471 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010472 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010473 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010474
Richard Smithd0b4dd62011-12-19 06:19:21 +000010475 const VarDecl *VD;
10476 // Look for a declaration of this variable that has an initializer, and
10477 // check whether it is an ICE.
10478 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10479 return NoDiag();
10480 else
Richard Smith9e575da2012-12-28 13:25:52 +000010481 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010482 }
10483 }
Richard Smith9e575da2012-12-28 13:25:52 +000010484 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010485 }
John McCall864e3962010-05-07 05:32:02 +000010486 case Expr::UnaryOperatorClass: {
10487 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10488 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010489 case UO_PostInc:
10490 case UO_PostDec:
10491 case UO_PreInc:
10492 case UO_PreDec:
10493 case UO_AddrOf:
10494 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010495 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010496 // C99 6.6/3 allows increment and decrement within unevaluated
10497 // subexpressions of constant expressions, but they can never be ICEs
10498 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010499 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010500 case UO_Extension:
10501 case UO_LNot:
10502 case UO_Plus:
10503 case UO_Minus:
10504 case UO_Not:
10505 case UO_Real:
10506 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010507 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010508 }
Richard Smith9e575da2012-12-28 13:25:52 +000010509
John McCall864e3962010-05-07 05:32:02 +000010510 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010511 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010512 }
10513 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010514 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10515 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10516 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10517 // compliance: we should warn earlier for offsetof expressions with
10518 // array subscripts that aren't ICEs, and if the array subscripts
10519 // are ICEs, the value of the offsetof must be an integer constant.
10520 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010521 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010522 case Expr::UnaryExprOrTypeTraitExprClass: {
10523 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10524 if ((Exp->getKind() == UETT_SizeOf) &&
10525 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010526 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010527 return NoDiag();
10528 }
10529 case Expr::BinaryOperatorClass: {
10530 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10531 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010532 case BO_PtrMemD:
10533 case BO_PtrMemI:
10534 case BO_Assign:
10535 case BO_MulAssign:
10536 case BO_DivAssign:
10537 case BO_RemAssign:
10538 case BO_AddAssign:
10539 case BO_SubAssign:
10540 case BO_ShlAssign:
10541 case BO_ShrAssign:
10542 case BO_AndAssign:
10543 case BO_XorAssign:
10544 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010545 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010546 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10547 // constant expressions, but they can never be ICEs because an ICE cannot
10548 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010549 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010550
John McCalle3027922010-08-25 11:45:40 +000010551 case BO_Mul:
10552 case BO_Div:
10553 case BO_Rem:
10554 case BO_Add:
10555 case BO_Sub:
10556 case BO_Shl:
10557 case BO_Shr:
10558 case BO_LT:
10559 case BO_GT:
10560 case BO_LE:
10561 case BO_GE:
10562 case BO_EQ:
10563 case BO_NE:
10564 case BO_And:
10565 case BO_Xor:
10566 case BO_Or:
10567 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010568 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10569 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010570 if (Exp->getOpcode() == BO_Div ||
10571 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010572 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010573 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010574 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010575 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010576 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010577 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010578 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010579 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010580 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010581 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010582 }
10583 }
10584 }
John McCalle3027922010-08-25 11:45:40 +000010585 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010586 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010587 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10588 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010589 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10590 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010591 } else {
10592 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010593 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010594 }
10595 }
Richard Smith9e575da2012-12-28 13:25:52 +000010596 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010597 }
John McCalle3027922010-08-25 11:45:40 +000010598 case BO_LAnd:
10599 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010600 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10601 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010602 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010603 // Rare case where the RHS has a comma "side-effect"; we need
10604 // to actually check the condition to see whether the side
10605 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010606 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010607 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010608 return RHSResult;
10609 return NoDiag();
10610 }
10611
Richard Smith9e575da2012-12-28 13:25:52 +000010612 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010613 }
10614 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010615 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010616 }
10617 case Expr::ImplicitCastExprClass:
10618 case Expr::CStyleCastExprClass:
10619 case Expr::CXXFunctionalCastExprClass:
10620 case Expr::CXXStaticCastExprClass:
10621 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010622 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010623 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010624 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010625 if (isa<ExplicitCastExpr>(E)) {
10626 if (const FloatingLiteral *FL
10627 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10628 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10629 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10630 APSInt IgnoredVal(DestWidth, !DestSigned);
10631 bool Ignored;
10632 // If the value does not fit in the destination type, the behavior is
10633 // undefined, so we are not required to treat it as a constant
10634 // expression.
10635 if (FL->getValue().convertToInteger(IgnoredVal,
10636 llvm::APFloat::rmTowardZero,
10637 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010638 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010639 return NoDiag();
10640 }
10641 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010642 switch (cast<CastExpr>(E)->getCastKind()) {
10643 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010644 case CK_AtomicToNonAtomic:
10645 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010646 case CK_NoOp:
10647 case CK_IntegralToBoolean:
10648 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010649 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010650 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010651 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010652 }
John McCall864e3962010-05-07 05:32:02 +000010653 }
John McCallc07a0c72011-02-17 10:25:35 +000010654 case Expr::BinaryConditionalOperatorClass: {
10655 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10656 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010657 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010658 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010659 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10660 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10661 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010662 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010663 return FalseResult;
10664 }
John McCall864e3962010-05-07 05:32:02 +000010665 case Expr::ConditionalOperatorClass: {
10666 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10667 // If the condition (ignoring parens) is a __builtin_constant_p call,
10668 // then only the true side is actually considered in an integer constant
10669 // expression, and it is fully evaluated. This is an important GNU
10670 // extension. See GCC PR38377 for discussion.
10671 if (const CallExpr *CallCE
10672 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010673 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010674 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010675 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010676 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010677 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010678
Richard Smithf57d8cb2011-12-09 22:58:01 +000010679 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10680 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010681
Richard Smith9e575da2012-12-28 13:25:52 +000010682 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010683 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010684 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010685 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010686 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010687 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010688 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010689 return NoDiag();
10690 // Rare case where the diagnostics depend on which side is evaluated
10691 // Note that if we get here, CondResult is 0, and at least one of
10692 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010693 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010694 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010695 return TrueResult;
10696 }
10697 case Expr::CXXDefaultArgExprClass:
10698 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010699 case Expr::CXXDefaultInitExprClass:
10700 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010701 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010702 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010703 }
10704 }
10705
David Blaikiee4d798f2012-01-20 21:50:17 +000010706 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010707}
10708
Richard Smithf57d8cb2011-12-09 22:58:01 +000010709/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010710static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010711 const Expr *E,
10712 llvm::APSInt *Value,
10713 SourceLocation *Loc) {
10714 if (!E->getType()->isIntegralOrEnumerationType()) {
10715 if (Loc) *Loc = E->getExprLoc();
10716 return false;
10717 }
10718
Richard Smith66e05fe2012-01-18 05:21:49 +000010719 APValue Result;
10720 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010721 return false;
10722
Richard Smith98710fc2014-11-13 23:03:19 +000010723 if (!Result.isInt()) {
10724 if (Loc) *Loc = E->getExprLoc();
10725 return false;
10726 }
10727
Richard Smith66e05fe2012-01-18 05:21:49 +000010728 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010729 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010730}
10731
Craig Toppera31a8822013-08-22 07:09:37 +000010732bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10733 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010734 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010735 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010736
Richard Smith9e575da2012-12-28 13:25:52 +000010737 ICEDiag D = CheckICE(this, Ctx);
10738 if (D.Kind != IK_ICE) {
10739 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010740 return false;
10741 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010742 return true;
10743}
10744
Craig Toppera31a8822013-08-22 07:09:37 +000010745bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010746 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010747 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010748 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10749
10750 if (!isIntegerConstantExpr(Ctx, Loc))
10751 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010752 // The only possible side-effects here are due to UB discovered in the
10753 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10754 // required to treat the expression as an ICE, so we produce the folded
10755 // value.
10756 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010757 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010758 return true;
10759}
Richard Smith66e05fe2012-01-18 05:21:49 +000010760
Craig Toppera31a8822013-08-22 07:09:37 +000010761bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010762 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010763}
10764
Craig Toppera31a8822013-08-22 07:09:37 +000010765bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010766 SourceLocation *Loc) const {
10767 // We support this checking in C++98 mode in order to diagnose compatibility
10768 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010769 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010770
Richard Smith98a0a492012-02-14 21:38:30 +000010771 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010772 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010773 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010774 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010775 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010776
10777 APValue Scratch;
10778 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10779
10780 if (!Diags.empty()) {
10781 IsConstExpr = false;
10782 if (Loc) *Loc = Diags[0].first;
10783 } else if (!IsConstExpr) {
10784 // FIXME: This shouldn't happen.
10785 if (Loc) *Loc = getExprLoc();
10786 }
10787
10788 return IsConstExpr;
10789}
Richard Smith253c2a32012-01-27 01:14:48 +000010790
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010791bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10792 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010793 ArrayRef<const Expr*> Args,
10794 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010795 Expr::EvalStatus Status;
10796 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10797
George Burgess IV177399e2017-01-09 04:12:14 +000010798 LValue ThisVal;
10799 const LValue *ThisPtr = nullptr;
10800 if (This) {
10801#ifndef NDEBUG
10802 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10803 assert(MD && "Don't provide `this` for non-methods.");
10804 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10805#endif
10806 if (EvaluateObjectArgument(Info, This, ThisVal))
10807 ThisPtr = &ThisVal;
10808 if (Info.EvalStatus.HasSideEffects)
10809 return false;
10810 }
10811
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010812 ArgVector ArgValues(Args.size());
10813 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10814 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010815 if ((*I)->isValueDependent() ||
10816 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010817 // If evaluation fails, throw away the argument entirely.
10818 ArgValues[I - Args.begin()] = APValue();
10819 if (Info.EvalStatus.HasSideEffects)
10820 return false;
10821 }
10822
10823 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010824 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010825 ArgValues.data());
10826 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10827}
10828
Richard Smith253c2a32012-01-27 01:14:48 +000010829bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010830 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010831 PartialDiagnosticAt> &Diags) {
10832 // FIXME: It would be useful to check constexpr function templates, but at the
10833 // moment the constant expression evaluator cannot cope with the non-rigorous
10834 // ASTs which we build for dependent expressions.
10835 if (FD->isDependentContext())
10836 return true;
10837
10838 Expr::EvalStatus Status;
10839 Status.Diag = &Diags;
10840
Richard Smith6d4c6582013-11-05 22:18:15 +000010841 EvalInfo Info(FD->getASTContext(), Status,
10842 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010843
10844 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010845 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010846
Richard Smith7525ff62013-05-09 07:14:00 +000010847 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010848 // is a temporary being used as the 'this' pointer.
10849 LValue This;
10850 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010851 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010852
Richard Smith253c2a32012-01-27 01:14:48 +000010853 ArrayRef<const Expr*> Args;
10854
Richard Smith2e312c82012-03-03 22:46:17 +000010855 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010856 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10857 // Evaluate the call as a constant initializer, to allow the construction
10858 // of objects of non-literal types.
10859 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010860 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10861 } else {
10862 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010863 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010864 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010865 }
Richard Smith253c2a32012-01-27 01:14:48 +000010866
10867 return Diags.empty();
10868}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010869
10870bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10871 const FunctionDecl *FD,
10872 SmallVectorImpl<
10873 PartialDiagnosticAt> &Diags) {
10874 Expr::EvalStatus Status;
10875 Status.Diag = &Diags;
10876
10877 EvalInfo Info(FD->getASTContext(), Status,
10878 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10879
10880 // Fabricate a call stack frame to give the arguments a plausible cover story.
10881 ArrayRef<const Expr*> Args;
10882 ArgVector ArgValues(0);
10883 bool Success = EvaluateArgs(Args, ArgValues, Info);
10884 (void)Success;
10885 assert(Success &&
10886 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010887 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010888
10889 APValue ResultScratch;
10890 Evaluate(ResultScratch, Info, E);
10891 return Diags.empty();
10892}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010893
10894bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10895 unsigned Type) const {
10896 if (!getType()->isPointerType())
10897 return false;
10898
10899 Expr::EvalStatus Status;
10900 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010901 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010902}