blob: ddc48de2c6731e8c9d977bfd7abda8620f48a1c0 [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
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
George Burgess IVe3763372016-12-22 02:50:20 +0000112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
131
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
134 return nullptr;
135 }
136
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142 }
143
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000148 static unsigned
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000156 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000157 Type = getType(Base);
158
Richard Smith80815602011-11-07 05:07:52 +0000159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
George Burgess IVe3763372016-12-22 02:50:20 +0000162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
170 ArraySize = 2;
171 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
175 ArraySize = 0;
176 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000177 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 } else {
Richard Smith80815602011-11-07 05:07:52 +0000179 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000180 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000181 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000182 }
Richard Smith80815602011-11-07 05:07:52 +0000183 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000184 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000185 }
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000190 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 };
192
Richard Smith96e0c102011-11-04 02:25:55 +0000193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000198 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000199
Richard Smitha8105bc2012-01-06 16:39:00 +0000200 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000201 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000202
George Burgess IVe3763372016-12-22 02:50:20 +0000203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
205
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000207 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000208
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 /// The length of the path to the most-derived object of which this is a
210 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000211 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000212
George Burgess IVa51c4072015-10-16 01:49:01 +0000213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000217 ///
218 /// If the current array is an unsized array, the value of this is
219 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 uint64_t MostDerivedArraySize;
221
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000224
Richard Smith80815602011-11-07 05:07:52 +0000225 typedef APValue::LValuePathEntry PathEntry;
226
Richard Smith96e0c102011-11-04 02:25:55 +0000227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
229
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000231
Richard Smitha8105bc2012-01-06 16:39:00 +0000232 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000233 : Invalid(false), IsOnePastTheEnd(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000237
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000243 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 if (V.getLValueBase()) {
248 bool IsArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
George Burgess IVa51c4072015-10-16 01:49:01 +0000252 MostDerivedIsArrayElement = IsArray;
253 }
Richard Smith80815602011-11-07 05:07:52 +0000254 }
255 }
256
Richard Smith96e0c102011-11-04 02:25:55 +0000257 void setInvalid() {
258 Invalid = true;
259 Entries.clear();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261
George Burgess IVe3763372016-12-22 02:50:20 +0000262 /// Determine whether the most derived subobject is an array without a
263 /// known bound.
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267 }
268
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
274 }
275
Richard Smitha8105bc2012-01-06 16:39:00 +0000276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000278 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 if (IsOnePastTheEnd)
280 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283 return true;
284 return false;
285 }
286
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
289 if (Invalid)
290 return false;
291 return !isOnePastTheEnd();
292 }
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000299 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000300 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000301 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000302
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000305 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000308 }
George Burgess IVe3763372016-12-22 02:50:20 +0000309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
312 PathEntry Entry;
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
315
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
320 // used.
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
323 }
Richard Smith96e0c102011-11-04 02:25:55 +0000324 /// Update this designator to refer to the given base or member of this
325 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000327 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000330 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000331
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000335 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
338 }
Richard Smith96e0c102011-11-04 02:25:55 +0000339 }
Richard Smith66c96992012-02-18 22:04:06 +0000340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
342 PathEntry Entry;
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
345
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000349 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
352 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, APSInt N);
Richard Smith96e0c102011-11-04 02:25:55 +0000354 /// Add N to the address of this subobject.
Richard Smithd6cc1982017-01-31 02:23:02 +0000355 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
356 if (Invalid || !N) return;
357 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
George Burgess IVe3763372016-12-22 02:50:20 +0000358 if (isMostDerivedAnUnsizedArray()) {
359 // Can't verify -- trust that the user is doing the right thing (or if
360 // not, trust that the caller will catch the bad behavior).
Richard Smithd6cc1982017-01-31 02:23:02 +0000361 // FIXME: Should we reject if this overflows, at least?
362 Entries.back().ArrayIndex += TruncatedN;
George Burgess IVe3763372016-12-22 02:50:20 +0000363 return;
364 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000365
Richard Smitha8105bc2012-01-06 16:39:00 +0000366 // [expr.add]p4: For the purposes of these operators, a pointer to a
367 // nonarray object behaves the same as a pointer to the first element of
368 // an array of length one with the type of the object as its element type.
Richard Smithd6cc1982017-01-31 02:23:02 +0000369 bool IsArray = MostDerivedPathLength == Entries.size() &&
370 MostDerivedIsArrayElement;
371 uint64_t ArrayIndex =
372 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
373 uint64_t ArraySize =
374 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
375
376 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
377 // Calculate the actual index in a wide enough type, so we can include
378 // it in the note.
379 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
380 (llvm::APInt&)N += ArrayIndex;
381 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
382 diagnosePointerArithmetic(Info, E, N);
Richard Smith96e0c102011-11-04 02:25:55 +0000383 setInvalid();
Richard Smithd6cc1982017-01-31 02:23:02 +0000384 return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000385 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000386
387 ArrayIndex += TruncatedN;
388 assert(ArrayIndex <= ArraySize &&
389 "bounds check succeeded for out-of-bounds index");
390
391 if (IsArray)
392 Entries.back().ArrayIndex = ArrayIndex;
393 else
394 IsOnePastTheEnd = (ArrayIndex != 0);
Richard Smith96e0c102011-11-04 02:25:55 +0000395 }
396 };
397
Richard Smith254a73d2011-10-28 22:34:42 +0000398 /// A stack frame in the constexpr call stack.
399 struct CallStackFrame {
400 EvalInfo &Info;
401
402 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000403 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000404
Richard Smithf6f003a2011-12-16 19:06:07 +0000405 /// Callee - The function which was called.
406 const FunctionDecl *Callee;
407
Richard Smithd62306a2011-11-10 06:34:14 +0000408 /// This - The binding for the this pointer in this call, if any.
409 const LValue *This;
410
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000411 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000412 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000413 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000414
Eli Friedman4830ec82012-06-25 21:21:08 +0000415 // Note that we intentionally use std::map here so that references to
416 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000417 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 typedef MapTy::const_iterator temp_iterator;
419 /// Temporaries - Temporary lvalues materialized within this stack frame.
420 MapTy Temporaries;
421
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000422 /// CallLoc - The location of the call expression for this call.
423 SourceLocation CallLoc;
424
425 /// Index - The call index of this call.
426 unsigned Index;
427
Faisal Vali051e3a22017-02-16 04:12:21 +0000428 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
429 // on the overall stack usage of deeply-recursing constexpr evaluataions.
430 // (We should cache this map rather than recomputing it repeatedly.)
431 // But let's try this and see how it goes; we can look into caching the map
432 // as a later change.
433
434 /// LambdaCaptureFields - Mapping from captured variables/this to
435 /// corresponding data members in the closure class.
436 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
437 FieldDecl *LambdaThisCaptureField;
438
Richard Smithf6f003a2011-12-16 19:06:07 +0000439 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
440 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000441 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000442 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000443
444 APValue *getTemporary(const void *Key) {
445 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000446 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000447 }
448 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000449 };
450
Richard Smith852c9db2013-04-20 22:23:05 +0000451 /// Temporarily override 'this'.
452 class ThisOverrideRAII {
453 public:
454 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
455 : Frame(Frame), OldThis(Frame.This) {
456 if (Enable)
457 Frame.This = NewThis;
458 }
459 ~ThisOverrideRAII() {
460 Frame.This = OldThis;
461 }
462 private:
463 CallStackFrame &Frame;
464 const LValue *OldThis;
465 };
466
Richard Smith92b1ce02011-12-12 09:28:41 +0000467 /// A partial diagnostic which we might know in advance that we are not going
468 /// to emit.
469 class OptionalDiagnostic {
470 PartialDiagnostic *Diag;
471
472 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000473 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
474 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000475
476 template<typename T>
477 OptionalDiagnostic &operator<<(const T &v) {
478 if (Diag)
479 *Diag << v;
480 return *this;
481 }
Richard Smithfe800032012-01-31 04:08:20 +0000482
483 OptionalDiagnostic &operator<<(const APSInt &I) {
484 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000485 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000486 I.toString(Buffer);
487 *Diag << StringRef(Buffer.data(), Buffer.size());
488 }
489 return *this;
490 }
491
492 OptionalDiagnostic &operator<<(const APFloat &F) {
493 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000494 // FIXME: Force the precision of the source value down so we don't
495 // print digits which are usually useless (we don't really care here if
496 // we truncate a digit by accident in edge cases). Ideally,
497 // APFloat::toString would automatically print the shortest
498 // representation which rounds to the correct value, but it's a bit
499 // tricky to implement.
500 unsigned precision =
501 llvm::APFloat::semanticsPrecision(F.getSemantics());
502 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000503 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000504 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000505 *Diag << StringRef(Buffer.data(), Buffer.size());
506 }
507 return *this;
508 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000509 };
510
Richard Smith08d6a2c2013-07-24 07:11:57 +0000511 /// A cleanup, and a flag indicating whether it is lifetime-extended.
512 class Cleanup {
513 llvm::PointerIntPair<APValue*, 1, bool> Value;
514
515 public:
516 Cleanup(APValue *Val, bool IsLifetimeExtended)
517 : Value(Val, IsLifetimeExtended) {}
518
519 bool isLifetimeExtended() const { return Value.getInt(); }
520 void endLifetime() {
521 *Value.getPointer() = APValue();
522 }
523 };
524
Richard Smithb228a862012-02-15 02:18:13 +0000525 /// EvalInfo - This is a private struct used by the evaluator to capture
526 /// information about a subexpression as it is folded. It retains information
527 /// about the AST context, but also maintains information about the folded
528 /// expression.
529 ///
530 /// If an expression could be evaluated, it is still possible it is not a C
531 /// "integer constant expression" or constant expression. If not, this struct
532 /// captures information about how and why not.
533 ///
534 /// One bit of information passed *into* the request for constant folding
535 /// indicates whether the subexpression is "evaluated" or not according to C
536 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
537 /// evaluate the expression regardless of what the RHS is, but C only allows
538 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000539 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000540 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000541
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000542 /// EvalStatus - Contains information about the evaluation.
543 Expr::EvalStatus &EvalStatus;
544
545 /// CurrentCall - The top of the constexpr call stack.
546 CallStackFrame *CurrentCall;
547
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000548 /// CallStackDepth - The number of calls in the call stack right now.
549 unsigned CallStackDepth;
550
Richard Smithb228a862012-02-15 02:18:13 +0000551 /// NextCallIndex - The next call index to assign.
552 unsigned NextCallIndex;
553
Richard Smitha3d3bd22013-05-08 02:12:03 +0000554 /// StepsLeft - The remaining number of evaluation steps we're permitted
555 /// to perform. This is essentially a limit for the number of statements
556 /// we will evaluate.
557 unsigned StepsLeft;
558
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000559 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000560 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000561 CallStackFrame BottomFrame;
562
Richard Smith08d6a2c2013-07-24 07:11:57 +0000563 /// A stack of values whose lifetimes end at the end of some surrounding
564 /// evaluation frame.
565 llvm::SmallVector<Cleanup, 16> CleanupStack;
566
Richard Smithd62306a2011-11-10 06:34:14 +0000567 /// EvaluatingDecl - This is the declaration whose initializer is being
568 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000569 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000570
571 /// EvaluatingDeclValue - This is the value being constructed for the
572 /// declaration whose initializer is being evaluated, if any.
573 APValue *EvaluatingDeclValue;
574
Richard Smith410306b2016-12-12 02:53:20 +0000575 /// The current array initialization index, if we're performing array
576 /// initialization.
577 uint64_t ArrayInitIndex = -1;
578
Richard Smith357362d2011-12-13 06:39:58 +0000579 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
580 /// notes attached to it will also be stored, otherwise they will not be.
581 bool HasActiveDiagnostic;
582
Richard Smith0c6124b2015-12-03 01:36:22 +0000583 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
584 /// fold (not just why it's not strictly a constant expression)?
585 bool HasFoldFailureDiagnostic;
586
George Burgess IV8c892b52016-05-25 22:31:54 +0000587 /// \brief Whether or not we're currently speculatively evaluating.
588 bool IsSpeculativelyEvaluating;
589
Richard Smith6d4c6582013-11-05 22:18:15 +0000590 enum EvaluationMode {
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression.
593 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000594
Richard Smith6d4c6582013-11-05 22:18:15 +0000595 /// Evaluate as a potential constant expression. Keep going if we hit a
596 /// construct that we can't evaluate yet (because we don't yet know the
597 /// value of something) but stop if we hit something that could never be
598 /// a constant expression.
599 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000600
Richard Smith6d4c6582013-11-05 22:18:15 +0000601 /// Fold the expression to a constant. Stop if we hit a side-effect that
602 /// we can't model.
603 EM_ConstantFold,
604
605 /// Evaluate the expression looking for integer overflow and similar
606 /// issues. Don't worry about side-effects, and try to visit all
607 /// subexpressions.
608 EM_EvaluateForOverflow,
609
610 /// Evaluate in any way we know how. Don't worry about side-effects that
611 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000612 EM_IgnoreSideEffects,
613
614 /// Evaluate as a constant expression. Stop if we find that the expression
615 /// is not a constant expression. Some expressions can be retried in the
616 /// optimizer if we don't constant fold them here, but in an unevaluated
617 /// context we try to fold them immediately since the optimizer never
618 /// gets a chance to look at it.
619 EM_ConstantExpressionUnevaluated,
620
621 /// Evaluate as a potential constant expression. Keep going if we hit a
622 /// construct that we can't evaluate yet (because we don't yet know the
623 /// value of something) but stop if we hit something that could never be
624 /// a constant expression. Some expressions can be retried in the
625 /// optimizer if we don't constant fold them here, but in an unevaluated
626 /// context we try to fold them immediately since the optimizer never
627 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000628 EM_PotentialConstantExpressionUnevaluated,
629
George Burgess IVf9013bf2017-02-10 22:52:29 +0000630 /// Evaluate as a constant expression. In certain scenarios, if:
631 /// - we find a MemberExpr with a base that can't be evaluated, or
632 /// - we find a variable initialized with a call to a function that has
633 /// the alloc_size attribute on it
634 /// then we may consider evaluation to have succeeded.
635 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000636 /// In either case, the LValue returned shall have an invalid base; in the
637 /// former, the base will be the invalid MemberExpr, in the latter, the
638 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
639 /// said CallExpr.
640 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 } EvalMode;
642
643 /// Are we checking whether the expression is a potential constant
644 /// expression?
645 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000646 return EvalMode == EM_PotentialConstantExpression ||
647 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000648 }
649
650 /// Are we checking an expression for overflow?
651 // FIXME: We should check for any kind of undefined or suspicious behavior
652 // in such constructs, not just overflow.
653 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
654
655 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000656 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000657 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000658 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
660 EvaluatingDecl((const ValueDecl *)nullptr),
661 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000662 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
663 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664
Richard Smith7525ff62013-05-09 07:14:00 +0000665 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
666 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000667 EvaluatingDeclValue = &Value;
668 }
669
David Blaikiebbafb8a2012-03-11 07:00:24 +0000670 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000671
Richard Smith357362d2011-12-13 06:39:58 +0000672 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000673 // Don't perform any constexpr calls (other than the call we're checking)
674 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000675 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000676 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000677 if (NextCallIndex == 0) {
678 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000679 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000680 return false;
681 }
Richard Smith357362d2011-12-13 06:39:58 +0000682 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
683 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000684 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000685 << getLangOpts().ConstexprCallDepth;
686 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000687 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000688
Richard Smithb228a862012-02-15 02:18:13 +0000689 CallStackFrame *getCallFrame(unsigned CallIndex) {
690 assert(CallIndex && "no call index in getCallFrame");
691 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
692 // be null in this loop.
693 CallStackFrame *Frame = CurrentCall;
694 while (Frame->Index > CallIndex)
695 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000696 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000697 }
698
Richard Smitha3d3bd22013-05-08 02:12:03 +0000699 bool nextStep(const Stmt *S) {
700 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000701 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000702 return false;
703 }
704 --StepsLeft;
705 return true;
706 }
707
Richard Smith357362d2011-12-13 06:39:58 +0000708 private:
709 /// Add a diagnostic to the diagnostics list.
710 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
711 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
712 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
713 return EvalStatus.Diag->back().second;
714 }
715
Richard Smithf6f003a2011-12-16 19:06:07 +0000716 /// Add notes containing a call stack to the current point of evaluation.
717 void addCallStack(unsigned Limit);
718
Faisal Valie690b7a2016-07-02 22:34:24 +0000719 private:
720 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
721 unsigned ExtraNotes, bool IsCCEDiag) {
722
Richard Smith92b1ce02011-12-12 09:28:41 +0000723 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 // If we have a prior diagnostic, it will be noting that the expression
725 // isn't a constant expression. This diagnostic is more important,
726 // unless we require this evaluation to produce a constant expression.
727 //
728 // FIXME: We might want to show both diagnostics to the user in
729 // EM_ConstantFold mode.
730 if (!EvalStatus.Diag->empty()) {
731 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000732 case EM_ConstantFold:
733 case EM_IgnoreSideEffects:
734 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000735 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000736 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000737 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000738 case EM_ConstantExpression:
739 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000740 case EM_ConstantExpressionUnevaluated:
741 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000742 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000743 HasActiveDiagnostic = false;
744 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000745 }
746 }
747
Richard Smithf6f003a2011-12-16 19:06:07 +0000748 unsigned CallStackNotes = CallStackDepth - 1;
749 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
750 if (Limit)
751 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000753 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000754
Richard Smith357362d2011-12-13 06:39:58 +0000755 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000756 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000757 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000758 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
759 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000760 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000761 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000762 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000763 }
Richard Smith357362d2011-12-13 06:39:58 +0000764 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000765 return OptionalDiagnostic();
766 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000767 public:
768 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
769 OptionalDiagnostic
770 FFDiag(SourceLocation Loc,
771 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
772 unsigned ExtraNotes = 0) {
773 return Diag(Loc, DiagId, ExtraNotes, false);
774 }
775
776 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000778 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000779 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000780 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 HasActiveDiagnostic = false;
782 return OptionalDiagnostic();
783 }
784
Richard Smith92b1ce02011-12-12 09:28:41 +0000785 /// Diagnose that the evaluation does not produce a C++11 core constant
786 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000787 ///
788 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
789 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000790 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000791 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000792 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000793 // Don't override a previous diagnostic. Don't bother collecting
794 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000795 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000796 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000797 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000798 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000799 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000800 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000801 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
802 = diag::note_invalid_subexpr_in_const_expr,
803 unsigned ExtraNotes = 0) {
804 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
805 }
Richard Smith357362d2011-12-13 06:39:58 +0000806 /// Add a note to a prior diagnostic.
807 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
808 if (!HasActiveDiagnostic)
809 return OptionalDiagnostic();
810 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000811 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000812
813 /// Add a stack of notes to a prior diagnostic.
814 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
815 if (HasActiveDiagnostic) {
816 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
817 Diags.begin(), Diags.end());
818 }
819 }
Richard Smith253c2a32012-01-27 01:14:48 +0000820
Richard Smith6d4c6582013-11-05 22:18:15 +0000821 /// Should we continue evaluation after encountering a side-effect that we
822 /// couldn't model?
823 bool keepEvaluatingAfterSideEffect() {
824 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000825 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000826 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000827 case EM_EvaluateForOverflow:
828 case EM_IgnoreSideEffects:
829 return true;
830
Richard Smith6d4c6582013-11-05 22:18:15 +0000831 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000832 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000834 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000835 return false;
836 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000837 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000838 }
839
840 /// Note that we have had a side-effect, and determine whether we should
841 /// keep evaluating.
842 bool noteSideEffect() {
843 EvalStatus.HasSideEffects = true;
844 return keepEvaluatingAfterSideEffect();
845 }
846
Richard Smithce8eca52015-12-08 03:21:47 +0000847 /// Should we continue evaluation after encountering undefined behavior?
848 bool keepEvaluatingAfterUndefinedBehavior() {
849 switch (EvalMode) {
850 case EM_EvaluateForOverflow:
851 case EM_IgnoreSideEffects:
852 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000853 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000854 return true;
855
856 case EM_PotentialConstantExpression:
857 case EM_PotentialConstantExpressionUnevaluated:
858 case EM_ConstantExpression:
859 case EM_ConstantExpressionUnevaluated:
860 return false;
861 }
862 llvm_unreachable("Missed EvalMode case");
863 }
864
865 /// Note that we hit something that was technically undefined behavior, but
866 /// that we can evaluate past it (such as signed overflow or floating-point
867 /// division by zero.)
868 bool noteUndefinedBehavior() {
869 EvalStatus.HasUndefinedBehavior = true;
870 return keepEvaluatingAfterUndefinedBehavior();
871 }
872
Richard Smith253c2a32012-01-27 01:14:48 +0000873 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000875 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000876 if (!StepsLeft)
877 return false;
878
879 switch (EvalMode) {
880 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000881 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000882 case EM_EvaluateForOverflow:
883 return true;
884
885 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000886 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 case EM_ConstantFold:
888 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000889 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000890 return false;
891 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000892 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000893 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000894
George Burgess IV8c892b52016-05-25 22:31:54 +0000895 /// Notes that we failed to evaluate an expression that other expressions
896 /// directly depend on, and determine if we should keep evaluating. This
897 /// should only be called if we actually intend to keep evaluating.
898 ///
899 /// Call noteSideEffect() instead if we may be able to ignore the value that
900 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
901 ///
902 /// (Foo(), 1) // use noteSideEffect
903 /// (Foo() || true) // use noteSideEffect
904 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000905 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000906 // Failure when evaluating some expression often means there is some
907 // subexpression whose evaluation was skipped. Therefore, (because we
908 // don't track whether we skipped an expression when unwinding after an
909 // evaluation failure) every evaluation failure that bubbles up from a
910 // subexpression implies that a side-effect has potentially happened. We
911 // skip setting the HasSideEffects flag to true until we decide to
912 // continue evaluating after that point, which happens here.
913 bool KeepGoing = keepEvaluatingAfterFailure();
914 EvalStatus.HasSideEffects |= KeepGoing;
915 return KeepGoing;
916 }
917
Richard Smith410306b2016-12-12 02:53:20 +0000918 class ArrayInitLoopIndex {
919 EvalInfo &Info;
920 uint64_t OuterIndex;
921
922 public:
923 ArrayInitLoopIndex(EvalInfo &Info)
924 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
925 Info.ArrayInitIndex = 0;
926 }
927 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
928
929 operator uint64_t&() { return Info.ArrayInitIndex; }
930 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000931 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000932
933 /// Object used to treat all foldable expressions as constant expressions.
934 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000936 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 bool HadNoPriorDiags;
938 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000939
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 explicit FoldConstant(EvalInfo &Info, bool Enabled)
941 : Info(Info),
942 Enabled(Enabled),
943 HadNoPriorDiags(Info.EvalStatus.Diag &&
944 Info.EvalStatus.Diag->empty() &&
945 !Info.EvalStatus.HasSideEffects),
946 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000947 if (Enabled &&
948 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
949 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000950 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000951 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000952 void keepDiagnostics() { Enabled = false; }
953 ~FoldConstant() {
954 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000955 !Info.EvalStatus.HasSideEffects)
956 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000957 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000958 }
959 };
Richard Smith17100ba2012-02-16 02:46:34 +0000960
George Burgess IV3a03fab2015-09-04 21:28:13 +0000961 /// RAII object used to treat the current evaluation as the correct pointer
962 /// offset fold for the current EvalMode
963 struct FoldOffsetRAII {
964 EvalInfo &Info;
965 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000966 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000967 : Info(Info), OldMode(Info.EvalMode) {
968 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000969 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000970 }
971
972 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
973 };
974
George Burgess IV8c892b52016-05-25 22:31:54 +0000975 /// RAII object used to optionally suppress diagnostics and side-effects from
976 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000977 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 /// Pair of EvalInfo, and a bit that stores whether or not we were
979 /// speculatively evaluating when we created this RAII.
980 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000981 Expr::EvalStatus Old;
982
George Burgess IV8c892b52016-05-25 22:31:54 +0000983 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
984 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
985 Old = Other.Old;
986 Other.InfoAndOldSpecEval.setPointer(nullptr);
987 }
988
989 void maybeRestoreState() {
990 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
991 if (!Info)
992 return;
993
994 Info->EvalStatus = Old;
995 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
996 }
997
Richard Smith17100ba2012-02-16 02:46:34 +0000998 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000999 SpeculativeEvaluationRAII() = default;
1000
1001 SpeculativeEvaluationRAII(
1002 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1003 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1004 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +00001005 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001006 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001007 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001008
1009 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1010 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1011 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001012 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001013
1014 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1015 maybeRestoreState();
1016 moveFromAndCancel(std::move(Other));
1017 return *this;
1018 }
1019
1020 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001021 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001022
1023 /// RAII object wrapping a full-expression or block scope, and handling
1024 /// the ending of the lifetime of temporaries created within it.
1025 template<bool IsFullExpression>
1026 class ScopeRAII {
1027 EvalInfo &Info;
1028 unsigned OldStackSize;
1029 public:
1030 ScopeRAII(EvalInfo &Info)
1031 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1032 ~ScopeRAII() {
1033 // Body moved to a static method to encourage the compiler to inline away
1034 // instances of this class.
1035 cleanup(Info, OldStackSize);
1036 }
1037 private:
1038 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1039 unsigned NewEnd = OldStackSize;
1040 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1041 I != N; ++I) {
1042 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1043 // Full-expression cleanup of a lifetime-extended temporary: nothing
1044 // to do, just move this cleanup to the right place in the stack.
1045 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1046 ++NewEnd;
1047 } else {
1048 // End the lifetime of the object.
1049 Info.CleanupStack[I].endLifetime();
1050 }
1051 }
1052 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1053 Info.CleanupStack.end());
1054 }
1055 };
1056 typedef ScopeRAII<false> BlockScopeRAII;
1057 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001058}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001059
Richard Smitha8105bc2012-01-06 16:39:00 +00001060bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1061 CheckSubobjectKind CSK) {
1062 if (Invalid)
1063 return false;
1064 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001066 << CSK;
1067 setInvalid();
1068 return false;
1069 }
1070 return true;
1071}
1072
1073void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Richard Smithd6cc1982017-01-31 02:23:02 +00001074 const Expr *E, APSInt N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001075 // If we're complaining, we must be able to statically determine the size of
1076 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001077 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001078 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001079 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001080 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001081 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001082 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001083 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 setInvalid();
1085}
1086
Richard Smithf6f003a2011-12-16 19:06:07 +00001087CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1088 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001089 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001090 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1091 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001092 Info.CurrentCall = this;
1093 ++Info.CallStackDepth;
1094}
1095
1096CallStackFrame::~CallStackFrame() {
1097 assert(Info.CurrentCall == this && "calls retired out of order");
1098 --Info.CallStackDepth;
1099 Info.CurrentCall = Caller;
1100}
1101
Richard Smith08d6a2c2013-07-24 07:11:57 +00001102APValue &CallStackFrame::createTemporary(const void *Key,
1103 bool IsLifetimeExtended) {
1104 APValue &Result = Temporaries[Key];
1105 assert(Result.isUninit() && "temporary created multiple times");
1106 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1107 return Result;
1108}
1109
Richard Smith84401042013-06-03 05:03:02 +00001110static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001111
1112void EvalInfo::addCallStack(unsigned Limit) {
1113 // Determine which calls to skip, if any.
1114 unsigned ActiveCalls = CallStackDepth - 1;
1115 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1116 if (Limit && Limit < ActiveCalls) {
1117 SkipStart = Limit / 2 + Limit % 2;
1118 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001119 }
1120
Richard Smithf6f003a2011-12-16 19:06:07 +00001121 // Walk the call stack and add the diagnostics.
1122 unsigned CallIdx = 0;
1123 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1124 Frame = Frame->Caller, ++CallIdx) {
1125 // Skip this call?
1126 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1127 if (CallIdx == SkipStart) {
1128 // Note that we're skipping calls.
1129 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1130 << unsigned(ActiveCalls - Limit);
1131 }
1132 continue;
1133 }
1134
Richard Smith5179eb72016-06-28 19:03:57 +00001135 // Use a different note for an inheriting constructor, because from the
1136 // user's perspective it's not really a function at all.
1137 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1138 if (CD->isInheritingConstructor()) {
1139 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1140 << CD->getParent();
1141 continue;
1142 }
1143 }
1144
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001145 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001146 llvm::raw_svector_ostream Out(Buffer);
1147 describeCall(Frame, Out);
1148 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1149 }
1150}
1151
1152namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001153 struct ComplexValue {
1154 private:
1155 bool IsInt;
1156
1157 public:
1158 APSInt IntReal, IntImag;
1159 APFloat FloatReal, FloatImag;
1160
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001161 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001162
1163 void makeComplexFloat() { IsInt = false; }
1164 bool isComplexFloat() const { return !IsInt; }
1165 APFloat &getComplexFloatReal() { return FloatReal; }
1166 APFloat &getComplexFloatImag() { return FloatImag; }
1167
1168 void makeComplexInt() { IsInt = true; }
1169 bool isComplexInt() const { return IsInt; }
1170 APSInt &getComplexIntReal() { return IntReal; }
1171 APSInt &getComplexIntImag() { return IntImag; }
1172
Richard Smith2e312c82012-03-03 22:46:17 +00001173 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001174 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001175 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001176 else
Richard Smith2e312c82012-03-03 22:46:17 +00001177 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001178 }
Richard Smith2e312c82012-03-03 22:46:17 +00001179 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001180 assert(v.isComplexFloat() || v.isComplexInt());
1181 if (v.isComplexFloat()) {
1182 makeComplexFloat();
1183 FloatReal = v.getComplexFloatReal();
1184 FloatImag = v.getComplexFloatImag();
1185 } else {
1186 makeComplexInt();
1187 IntReal = v.getComplexIntReal();
1188 IntImag = v.getComplexIntImag();
1189 }
1190 }
John McCall93d91dc2010-05-07 17:22:02 +00001191 };
John McCall45d55e42010-05-07 21:00:08 +00001192
1193 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001194 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001195 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001196 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001197 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001198 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001199 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001200
Richard Smithce40ad62011-11-12 22:28:03 +00001201 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001202 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001203 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001204 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001205 SubobjectDesignator &getLValueDesignator() { return Designator; }
1206 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001207 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001208
Richard Smith2e312c82012-03-03 22:46:17 +00001209 void moveInto(APValue &V) const {
1210 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001211 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1212 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001213 else {
1214 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1215 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1216 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001217 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001218 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001219 }
John McCall45d55e42010-05-07 21:00:08 +00001220 }
Richard Smith2e312c82012-03-03 22:46:17 +00001221 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001222 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001223 Base = V.getLValueBase();
1224 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001225 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001226 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001227 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001228 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001229 }
1230
Yaxun Liu402804b2016-12-15 08:09:08 +00001231 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1232 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001233#ifndef NDEBUG
1234 // We only allow a few types of invalid bases. Enforce that here.
1235 if (BInvalid) {
1236 const auto *E = B.get<const Expr *>();
1237 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1238 "Unexpected type of invalid base");
1239 }
1240#endif
1241
Richard Smithce40ad62011-11-12 22:28:03 +00001242 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001243 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001244 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001245 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001246 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001247 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001248 }
1249
George Burgess IV3a03fab2015-09-04 21:28:13 +00001250 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1251 set(B, I, true);
1252 }
1253
Richard Smitha8105bc2012-01-06 16:39:00 +00001254 // Check that this LValue is not based on a null pointer. If it is, produce
1255 // a diagnostic and mark the designator as invalid.
1256 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1257 CheckSubobjectKind CSK) {
1258 if (Designator.Invalid)
1259 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001260 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001261 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001262 << CSK;
1263 Designator.setInvalid();
1264 return false;
1265 }
1266 return true;
1267 }
1268
1269 // Check this LValue refers to an object. If not, set the designator to be
1270 // invalid and emit a diagnostic.
1271 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001272 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001273 Designator.checkSubobject(Info, E, CSK);
1274 }
1275
1276 void addDecl(EvalInfo &Info, const Expr *E,
1277 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001278 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1279 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001280 }
George Burgess IVe3763372016-12-22 02:50:20 +00001281 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1282 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1283 assert(isBaseAnAllocSizeCall(Base) &&
1284 "Only alloc_size bases can have unsized arrays");
1285 Designator.FirstEntryIsAnUnsizedArray = true;
1286 Designator.addUnsizedArrayUnchecked(ElemTy);
1287 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001288 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001289 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1290 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 }
Richard Smith66c96992012-02-18 22:04:06 +00001292 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001293 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1294 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001295 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001296 void clearIsNullPointer() {
1297 IsNullPtr = false;
1298 }
Richard Smithd6cc1982017-01-31 02:23:02 +00001299 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
Yaxun Liu402804b2016-12-15 08:09:08 +00001300 CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001301 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1302 // but we're not required to diagnose it and it's valid in C++.)
1303 if (!Index)
1304 return;
1305
1306 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1307 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1308 // offsets.
1309 uint64_t Offset64 = Offset.getQuantity();
1310 uint64_t ElemSize64 = ElementSize.getQuantity();
1311 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1312 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1313
1314 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001315 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001316 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001317 }
1318 void adjustOffset(CharUnits N) {
1319 Offset += N;
1320 if (N.getQuantity())
1321 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001322 }
John McCall45d55e42010-05-07 21:00:08 +00001323 };
Richard Smith027bf112011-11-17 22:56:20 +00001324
1325 struct MemberPtr {
1326 MemberPtr() {}
1327 explicit MemberPtr(const ValueDecl *Decl) :
1328 DeclAndIsDerivedMember(Decl, false), Path() {}
1329
1330 /// The member or (direct or indirect) field referred to by this member
1331 /// pointer, or 0 if this is a null member pointer.
1332 const ValueDecl *getDecl() const {
1333 return DeclAndIsDerivedMember.getPointer();
1334 }
1335 /// Is this actually a member of some type derived from the relevant class?
1336 bool isDerivedMember() const {
1337 return DeclAndIsDerivedMember.getInt();
1338 }
1339 /// Get the class which the declaration actually lives in.
1340 const CXXRecordDecl *getContainingRecord() const {
1341 return cast<CXXRecordDecl>(
1342 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1343 }
1344
Richard Smith2e312c82012-03-03 22:46:17 +00001345 void moveInto(APValue &V) const {
1346 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001347 }
Richard Smith2e312c82012-03-03 22:46:17 +00001348 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001349 assert(V.isMemberPointer());
1350 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1351 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1352 Path.clear();
1353 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1354 Path.insert(Path.end(), P.begin(), P.end());
1355 }
1356
1357 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1358 /// whether the member is a member of some class derived from the class type
1359 /// of the member pointer.
1360 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1361 /// Path - The path of base/derived classes from the member declaration's
1362 /// class (exclusive) to the class type of the member pointer (inclusive).
1363 SmallVector<const CXXRecordDecl*, 4> Path;
1364
1365 /// Perform a cast towards the class of the Decl (either up or down the
1366 /// hierarchy).
1367 bool castBack(const CXXRecordDecl *Class) {
1368 assert(!Path.empty());
1369 const CXXRecordDecl *Expected;
1370 if (Path.size() >= 2)
1371 Expected = Path[Path.size() - 2];
1372 else
1373 Expected = getContainingRecord();
1374 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1375 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1376 // if B does not contain the original member and is not a base or
1377 // derived class of the class containing the original member, the result
1378 // of the cast is undefined.
1379 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1380 // (D::*). We consider that to be a language defect.
1381 return false;
1382 }
1383 Path.pop_back();
1384 return true;
1385 }
1386 /// Perform a base-to-derived member pointer cast.
1387 bool castToDerived(const CXXRecordDecl *Derived) {
1388 if (!getDecl())
1389 return true;
1390 if (!isDerivedMember()) {
1391 Path.push_back(Derived);
1392 return true;
1393 }
1394 if (!castBack(Derived))
1395 return false;
1396 if (Path.empty())
1397 DeclAndIsDerivedMember.setInt(false);
1398 return true;
1399 }
1400 /// Perform a derived-to-base member pointer cast.
1401 bool castToBase(const CXXRecordDecl *Base) {
1402 if (!getDecl())
1403 return true;
1404 if (Path.empty())
1405 DeclAndIsDerivedMember.setInt(true);
1406 if (isDerivedMember()) {
1407 Path.push_back(Base);
1408 return true;
1409 }
1410 return castBack(Base);
1411 }
1412 };
Richard Smith357362d2011-12-13 06:39:58 +00001413
Richard Smith7bb00672012-02-01 01:42:44 +00001414 /// Compare two member pointers, which are assumed to be of the same type.
1415 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1416 if (!LHS.getDecl() || !RHS.getDecl())
1417 return !LHS.getDecl() && !RHS.getDecl();
1418 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1419 return false;
1420 return LHS.Path == RHS.Path;
1421 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001422}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001423
Richard Smith2e312c82012-03-03 22:46:17 +00001424static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001425static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1426 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001427 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001428static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1429 bool InvalidBaseOK = false);
1430static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1431 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001432static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1433 EvalInfo &Info);
1434static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001435static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001436static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001437 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001438static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001439static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001440static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1441 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001442static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001443
1444//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001445// Misc utilities
1446//===----------------------------------------------------------------------===//
1447
Richard Smithd6cc1982017-01-31 02:23:02 +00001448/// Negate an APSInt in place, converting it to a signed form if necessary, and
1449/// preserving its value (by extending by up to one bit as needed).
1450static void negateAsSigned(APSInt &Int) {
1451 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1452 Int = Int.extend(Int.getBitWidth() + 1);
1453 Int.setIsSigned(true);
1454 }
1455 Int = -Int;
1456}
1457
Richard Smith84401042013-06-03 05:03:02 +00001458/// Produce a string describing the given constexpr call.
1459static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1460 unsigned ArgIndex = 0;
1461 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1462 !isa<CXXConstructorDecl>(Frame->Callee) &&
1463 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1464
1465 if (!IsMemberCall)
1466 Out << *Frame->Callee << '(';
1467
1468 if (Frame->This && IsMemberCall) {
1469 APValue Val;
1470 Frame->This->moveInto(Val);
1471 Val.printPretty(Out, Frame->Info.Ctx,
1472 Frame->This->Designator.MostDerivedType);
1473 // FIXME: Add parens around Val if needed.
1474 Out << "->" << *Frame->Callee << '(';
1475 IsMemberCall = false;
1476 }
1477
1478 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1479 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1480 if (ArgIndex > (unsigned)IsMemberCall)
1481 Out << ", ";
1482
1483 const ParmVarDecl *Param = *I;
1484 const APValue &Arg = Frame->Arguments[ArgIndex];
1485 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1486
1487 if (ArgIndex == 0 && IsMemberCall)
1488 Out << "->" << *Frame->Callee << '(';
1489 }
1490
1491 Out << ')';
1492}
1493
Richard Smithd9f663b2013-04-22 15:31:51 +00001494/// Evaluate an expression to see if it had side-effects, and discard its
1495/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001496/// \return \c true if the caller should keep evaluating.
1497static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001498 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001499 if (!Evaluate(Scratch, Info, E))
1500 // We don't need the value, but we might have skipped a side effect here.
1501 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001502 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001503}
1504
Richard Smithd62306a2011-11-10 06:34:14 +00001505/// Should this call expression be treated as a string literal?
1506static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001507 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001508 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1509 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1510}
1511
Richard Smithce40ad62011-11-12 22:28:03 +00001512static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001513 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1514 // constant expression of pointer type that evaluates to...
1515
1516 // ... a null pointer value, or a prvalue core constant expression of type
1517 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001518 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001519
Richard Smithce40ad62011-11-12 22:28:03 +00001520 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1521 // ... the address of an object with static storage duration,
1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1523 return VD->hasGlobalStorage();
1524 // ... the address of a function,
1525 return isa<FunctionDecl>(D);
1526 }
1527
1528 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001529 switch (E->getStmtClass()) {
1530 default:
1531 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001532 case Expr::CompoundLiteralExprClass: {
1533 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1534 return CLE->isFileScope() && CLE->isLValue();
1535 }
Richard Smithe6c01442013-06-05 00:46:14 +00001536 case Expr::MaterializeTemporaryExprClass:
1537 // A materialized temporary might have been lifetime-extended to static
1538 // storage duration.
1539 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001540 // A string literal has static storage duration.
1541 case Expr::StringLiteralClass:
1542 case Expr::PredefinedExprClass:
1543 case Expr::ObjCStringLiteralClass:
1544 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001545 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001546 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001547 return true;
1548 case Expr::CallExprClass:
1549 return IsStringLiteralCall(cast<CallExpr>(E));
1550 // For GCC compatibility, &&label has static storage duration.
1551 case Expr::AddrLabelExprClass:
1552 return true;
1553 // A Block literal expression may be used as the initialization value for
1554 // Block variables at global or local static scope.
1555 case Expr::BlockExprClass:
1556 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001557 case Expr::ImplicitValueInitExprClass:
1558 // FIXME:
1559 // We can never form an lvalue with an implicit value initialization as its
1560 // base through expression evaluation, so these only appear in one case: the
1561 // implicit variable declaration we invent when checking whether a constexpr
1562 // constructor can produce a constant expression. We must assume that such
1563 // an expression might be a global lvalue.
1564 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001565 }
John McCall95007602010-05-10 23:27:23 +00001566}
1567
Richard Smithb228a862012-02-15 02:18:13 +00001568static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1569 assert(Base && "no location for a null lvalue");
1570 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1571 if (VD)
1572 Info.Note(VD->getLocation(), diag::note_declared_at);
1573 else
Ted Kremenek28831752012-08-23 20:46:57 +00001574 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001575 diag::note_constexpr_temporary_here);
1576}
1577
Richard Smith80815602011-11-07 05:07:52 +00001578/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001579/// value for an address or reference constant expression. Return true if we
1580/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001581static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1582 QualType Type, const LValue &LVal) {
1583 bool IsReferenceType = Type->isReferenceType();
1584
Richard Smith357362d2011-12-13 06:39:58 +00001585 APValue::LValueBase Base = LVal.getLValueBase();
1586 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1587
Richard Smith0dea49e2012-02-18 04:58:18 +00001588 // Check that the object is a global. Note that the fake 'this' object we
1589 // manufacture when checking potential constant expressions is conservatively
1590 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001591 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001592 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001593 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001594 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001595 << IsReferenceType << !Designator.Entries.empty()
1596 << !!VD << VD;
1597 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001598 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001599 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001600 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001601 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001602 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001603 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001604 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001605 LVal.getLValueCallIndex() == 0) &&
1606 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001607
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001608 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1609 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001610 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001611 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001612 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001613
Hans Wennborg82dd8772014-06-25 22:19:48 +00001614 // A dllimport variable never acts like a constant.
1615 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001616 return false;
1617 }
1618 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1619 // __declspec(dllimport) must be handled very carefully:
1620 // We must never initialize an expression with the thunk in C++.
1621 // Doing otherwise would allow the same id-expression to yield
1622 // different addresses for the same function in different translation
1623 // units. However, this means that we must dynamically initialize the
1624 // expression with the contents of the import address table at runtime.
1625 //
1626 // The C language has no notion of ODR; furthermore, it has no notion of
1627 // dynamic initialization. This means that we are permitted to
1628 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001629 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001630 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001631 }
1632 }
1633
Richard Smitha8105bc2012-01-06 16:39:00 +00001634 // Allow address constant expressions to be past-the-end pointers. This is
1635 // an extension: the standard requires them to point to an object.
1636 if (!IsReferenceType)
1637 return true;
1638
1639 // A reference constant expression must refer to an object.
1640 if (!Base) {
1641 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001642 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001643 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001644 }
1645
Richard Smith357362d2011-12-13 06:39:58 +00001646 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001647 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001648 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001649 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001650 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001651 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001652 }
1653
Richard Smith80815602011-11-07 05:07:52 +00001654 return true;
1655}
1656
Richard Smithfddd3842011-12-30 21:15:51 +00001657/// Check that this core constant expression is of literal type, and if not,
1658/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001659static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001660 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001661 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001662 return true;
1663
Richard Smith7525ff62013-05-09 07:14:00 +00001664 // C++1y: A constant initializer for an object o [...] may also invoke
1665 // constexpr constructors for o and its subobjects even if those objects
1666 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001667 //
1668 // C++11 missed this detail for aggregates, so classes like this:
1669 // struct foo_t { union { int i; volatile int j; } u; };
1670 // are not (obviously) initializable like so:
1671 // __attribute__((__require_constant_initialization__))
1672 // static const foo_t x = {{0}};
1673 // because "i" is a subobject with non-literal initialization (due to the
1674 // volatile member of the union). See:
1675 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1676 // Therefore, we use the C++1y behavior.
1677 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001678 return true;
1679
Richard Smithfddd3842011-12-30 21:15:51 +00001680 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001681 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001682 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001683 << E->getType();
1684 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001685 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001686 return false;
1687}
1688
Richard Smith0b0a0b62011-10-29 20:57:55 +00001689/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001690/// constant expression. If not, report an appropriate diagnostic. Does not
1691/// check that the expression is of literal type.
1692static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1693 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001694 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001695 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001696 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001697 return false;
1698 }
1699
Richard Smith77be48a2014-07-31 06:31:19 +00001700 // We allow _Atomic(T) to be initialized from anything that T can be
1701 // initialized from.
1702 if (const AtomicType *AT = Type->getAs<AtomicType>())
1703 Type = AT->getValueType();
1704
Richard Smithb228a862012-02-15 02:18:13 +00001705 // Core issue 1454: For a literal constant expression of array or class type,
1706 // each subobject of its value shall have been initialized by a constant
1707 // expression.
1708 if (Value.isArray()) {
1709 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1710 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1711 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1712 Value.getArrayInitializedElt(I)))
1713 return false;
1714 }
1715 if (!Value.hasArrayFiller())
1716 return true;
1717 return CheckConstantExpression(Info, DiagLoc, EltTy,
1718 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001719 }
Richard Smithb228a862012-02-15 02:18:13 +00001720 if (Value.isUnion() && Value.getUnionField()) {
1721 return CheckConstantExpression(Info, DiagLoc,
1722 Value.getUnionField()->getType(),
1723 Value.getUnionValue());
1724 }
1725 if (Value.isStruct()) {
1726 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1727 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1728 unsigned BaseIndex = 0;
1729 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1730 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1731 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1732 Value.getStructBase(BaseIndex)))
1733 return false;
1734 }
1735 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001736 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001737 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1738 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001739 return false;
1740 }
1741 }
1742
1743 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001744 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001745 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001746 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1747 }
1748
1749 // Everything else is fine.
1750 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001751}
1752
Benjamin Kramer8407df72015-03-09 16:47:52 +00001753static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001754 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001755}
1756
1757static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001758 if (Value.CallIndex)
1759 return false;
1760 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1761 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001762}
1763
Richard Smithcecf1842011-11-01 21:06:14 +00001764static bool IsWeakLValue(const LValue &Value) {
1765 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001766 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001767}
1768
David Majnemerb5116032014-12-09 23:32:34 +00001769static bool isZeroSized(const LValue &Value) {
1770 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001771 if (Decl && isa<VarDecl>(Decl)) {
1772 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001773 if (Ty->isArrayType())
1774 return Ty->isIncompleteType() ||
1775 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001776 }
1777 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001778}
1779
Richard Smith2e312c82012-03-03 22:46:17 +00001780static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001781 // A null base expression indicates a null pointer. These are always
1782 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001783 if (!Value.getLValueBase()) {
1784 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001785 return true;
1786 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001787
Richard Smith027bf112011-11-17 22:56:20 +00001788 // We have a non-null base. These are generally known to be true, but if it's
1789 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001790 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001791 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001792 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001793}
1794
Richard Smith2e312c82012-03-03 22:46:17 +00001795static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001796 switch (Val.getKind()) {
1797 case APValue::Uninitialized:
1798 return false;
1799 case APValue::Int:
1800 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001801 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001802 case APValue::Float:
1803 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001804 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001805 case APValue::ComplexInt:
1806 Result = Val.getComplexIntReal().getBoolValue() ||
1807 Val.getComplexIntImag().getBoolValue();
1808 return true;
1809 case APValue::ComplexFloat:
1810 Result = !Val.getComplexFloatReal().isZero() ||
1811 !Val.getComplexFloatImag().isZero();
1812 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001813 case APValue::LValue:
1814 return EvalPointerValueAsBool(Val, Result);
1815 case APValue::MemberPointer:
1816 Result = Val.getMemberPointerDecl();
1817 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001818 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001819 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001820 case APValue::Struct:
1821 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001822 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001823 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001824 }
1825
Richard Smith11562c52011-10-28 17:51:58 +00001826 llvm_unreachable("unknown APValue kind");
1827}
1828
1829static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1830 EvalInfo &Info) {
1831 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001832 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001833 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001834 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001835 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001836}
1837
Richard Smith357362d2011-12-13 06:39:58 +00001838template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001839static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001840 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001841 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001842 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001843 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001844}
1845
1846static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1847 QualType SrcType, const APFloat &Value,
1848 QualType DestType, APSInt &Result) {
1849 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001850 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001851 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001852
Richard Smith357362d2011-12-13 06:39:58 +00001853 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001854 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001855 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1856 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001857 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001858 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001859}
1860
Richard Smith357362d2011-12-13 06:39:58 +00001861static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1862 QualType SrcType, QualType DestType,
1863 APFloat &Result) {
1864 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001865 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001866 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1867 APFloat::rmNearestTiesToEven, &ignored)
1868 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001869 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001870 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001871}
1872
Richard Smith911e1422012-01-30 22:27:01 +00001873static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1874 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001875 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001876 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001877 APSInt Result = Value;
1878 // Figure out if this is a truncate, extend or noop cast.
1879 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001880 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001881 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001882 return Result;
1883}
1884
Richard Smith357362d2011-12-13 06:39:58 +00001885static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1886 QualType SrcType, const APSInt &Value,
1887 QualType DestType, APFloat &Result) {
1888 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1889 if (Result.convertFromAPInt(Value, Value.isSigned(),
1890 APFloat::rmNearestTiesToEven)
1891 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001892 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001893 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001894}
1895
Richard Smith49ca8aa2013-08-06 07:09:20 +00001896static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1897 APValue &Value, const FieldDecl *FD) {
1898 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1899
1900 if (!Value.isInt()) {
1901 // Trying to store a pointer-cast-to-integer into a bitfield.
1902 // FIXME: In this case, we should provide the diagnostic for casting
1903 // a pointer to an integer.
1904 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001905 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001906 return false;
1907 }
1908
1909 APSInt &Int = Value.getInt();
1910 unsigned OldBitWidth = Int.getBitWidth();
1911 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1912 if (NewBitWidth < OldBitWidth)
1913 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1914 return true;
1915}
1916
Eli Friedman803acb32011-12-22 03:51:45 +00001917static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1918 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001919 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001920 if (!Evaluate(SVal, Info, E))
1921 return false;
1922 if (SVal.isInt()) {
1923 Res = SVal.getInt();
1924 return true;
1925 }
1926 if (SVal.isFloat()) {
1927 Res = SVal.getFloat().bitcastToAPInt();
1928 return true;
1929 }
1930 if (SVal.isVector()) {
1931 QualType VecTy = E->getType();
1932 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1933 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1934 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1935 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1936 Res = llvm::APInt::getNullValue(VecSize);
1937 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1938 APValue &Elt = SVal.getVectorElt(i);
1939 llvm::APInt EltAsInt;
1940 if (Elt.isInt()) {
1941 EltAsInt = Elt.getInt();
1942 } else if (Elt.isFloat()) {
1943 EltAsInt = Elt.getFloat().bitcastToAPInt();
1944 } else {
1945 // Don't try to handle vectors of anything other than int or float
1946 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001947 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001948 return false;
1949 }
1950 unsigned BaseEltSize = EltAsInt.getBitWidth();
1951 if (BigEndian)
1952 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1953 else
1954 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1955 }
1956 return true;
1957 }
1958 // Give up if the input isn't an int, float, or vector. For example, we
1959 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001960 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001961 return false;
1962}
1963
Richard Smith43e77732013-05-07 04:50:00 +00001964/// Perform the given integer operation, which is known to need at most BitWidth
1965/// bits, and check for overflow in the original type (if that type was not an
1966/// unsigned type).
1967template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001968static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1969 const APSInt &LHS, const APSInt &RHS,
1970 unsigned BitWidth, Operation Op,
1971 APSInt &Result) {
1972 if (LHS.isUnsigned()) {
1973 Result = Op(LHS, RHS);
1974 return true;
1975 }
Richard Smith43e77732013-05-07 04:50:00 +00001976
1977 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001978 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001979 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001980 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001981 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001982 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001983 << Result.toString(10) << E->getType();
1984 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001985 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001986 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001987 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001988}
1989
1990/// Perform the given binary integer operation.
1991static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1992 BinaryOperatorKind Opcode, APSInt RHS,
1993 APSInt &Result) {
1994 switch (Opcode) {
1995 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001996 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001997 return false;
1998 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001999 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2000 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002001 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002002 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2003 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002004 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002005 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2006 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002007 case BO_And: Result = LHS & RHS; return true;
2008 case BO_Xor: Result = LHS ^ RHS; return true;
2009 case BO_Or: Result = LHS | RHS; return true;
2010 case BO_Div:
2011 case BO_Rem:
2012 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002013 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002014 return false;
2015 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002016 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2017 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2018 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002019 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2020 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002021 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2022 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002023 return true;
2024 case BO_Shl: {
2025 if (Info.getLangOpts().OpenCL)
2026 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2027 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2028 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2029 RHS.isUnsigned());
2030 else if (RHS.isSigned() && RHS.isNegative()) {
2031 // During constant-folding, a negative shift is an opposite shift. Such
2032 // a shift is not a constant expression.
2033 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2034 RHS = -RHS;
2035 goto shift_right;
2036 }
2037 shift_left:
2038 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2039 // the shifted type.
2040 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2041 if (SA != RHS) {
2042 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2043 << RHS << E->getType() << LHS.getBitWidth();
2044 } else if (LHS.isSigned()) {
2045 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2046 // operand, and must not overflow the corresponding unsigned type.
2047 if (LHS.isNegative())
2048 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2049 else if (LHS.countLeadingZeros() < SA)
2050 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2051 }
2052 Result = LHS << SA;
2053 return true;
2054 }
2055 case BO_Shr: {
2056 if (Info.getLangOpts().OpenCL)
2057 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2058 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2059 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2060 RHS.isUnsigned());
2061 else if (RHS.isSigned() && RHS.isNegative()) {
2062 // During constant-folding, a negative shift is an opposite shift. Such a
2063 // shift is not a constant expression.
2064 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2065 RHS = -RHS;
2066 goto shift_left;
2067 }
2068 shift_right:
2069 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2070 // shifted type.
2071 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2072 if (SA != RHS)
2073 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2074 << RHS << E->getType() << LHS.getBitWidth();
2075 Result = LHS >> SA;
2076 return true;
2077 }
2078
2079 case BO_LT: Result = LHS < RHS; return true;
2080 case BO_GT: Result = LHS > RHS; return true;
2081 case BO_LE: Result = LHS <= RHS; return true;
2082 case BO_GE: Result = LHS >= RHS; return true;
2083 case BO_EQ: Result = LHS == RHS; return true;
2084 case BO_NE: Result = LHS != RHS; return true;
2085 }
2086}
2087
Richard Smith861b5b52013-05-07 23:34:45 +00002088/// Perform the given binary floating-point operation, in-place, on LHS.
2089static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2090 APFloat &LHS, BinaryOperatorKind Opcode,
2091 const APFloat &RHS) {
2092 switch (Opcode) {
2093 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002094 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002095 return false;
2096 case BO_Mul:
2097 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2098 break;
2099 case BO_Add:
2100 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2101 break;
2102 case BO_Sub:
2103 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2104 break;
2105 case BO_Div:
2106 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2107 break;
2108 }
2109
Richard Smith0c6124b2015-12-03 01:36:22 +00002110 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002111 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002112 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002113 }
Richard Smith861b5b52013-05-07 23:34:45 +00002114 return true;
2115}
2116
Richard Smitha8105bc2012-01-06 16:39:00 +00002117/// Cast an lvalue referring to a base subobject to a derived class, by
2118/// truncating the lvalue's path to the given length.
2119static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2120 const RecordDecl *TruncatedType,
2121 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002122 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002123
2124 // Check we actually point to a derived class object.
2125 if (TruncatedElements == D.Entries.size())
2126 return true;
2127 assert(TruncatedElements >= D.MostDerivedPathLength &&
2128 "not casting to a derived class");
2129 if (!Result.checkSubobject(Info, E, CSK_Derived))
2130 return false;
2131
2132 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002133 const RecordDecl *RD = TruncatedType;
2134 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002135 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002136 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2137 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002138 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002139 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002140 else
Richard Smithd62306a2011-11-10 06:34:14 +00002141 Result.Offset -= Layout.getBaseClassOffset(Base);
2142 RD = Base;
2143 }
Richard Smith027bf112011-11-17 22:56:20 +00002144 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002145 return true;
2146}
2147
John McCalld7bca762012-05-01 00:38:49 +00002148static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002149 const CXXRecordDecl *Derived,
2150 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002151 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002152 if (!RL) {
2153 if (Derived->isInvalidDecl()) return false;
2154 RL = &Info.Ctx.getASTRecordLayout(Derived);
2155 }
2156
Richard Smithd62306a2011-11-10 06:34:14 +00002157 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002158 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002159 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002160}
2161
Richard Smitha8105bc2012-01-06 16:39:00 +00002162static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002163 const CXXRecordDecl *DerivedDecl,
2164 const CXXBaseSpecifier *Base) {
2165 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2166
John McCalld7bca762012-05-01 00:38:49 +00002167 if (!Base->isVirtual())
2168 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002169
Richard Smitha8105bc2012-01-06 16:39:00 +00002170 SubobjectDesignator &D = Obj.Designator;
2171 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002172 return false;
2173
Richard Smitha8105bc2012-01-06 16:39:00 +00002174 // Extract most-derived object and corresponding type.
2175 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2176 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2177 return false;
2178
2179 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002180 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002181 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2182 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002183 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002184 return true;
2185}
2186
Richard Smith84401042013-06-03 05:03:02 +00002187static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2188 QualType Type, LValue &Result) {
2189 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2190 PathE = E->path_end();
2191 PathI != PathE; ++PathI) {
2192 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2193 *PathI))
2194 return false;
2195 Type = (*PathI)->getType();
2196 }
2197 return true;
2198}
2199
Richard Smithd62306a2011-11-10 06:34:14 +00002200/// Update LVal to refer to the given field, which must be a member of the type
2201/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002202static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002203 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002204 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002205 if (!RL) {
2206 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002207 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002208 }
Richard Smithd62306a2011-11-10 06:34:14 +00002209
2210 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002211 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002212 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002213 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002214}
2215
Richard Smith1b78b3d2012-01-25 22:15:11 +00002216/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002217static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002218 LValue &LVal,
2219 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002220 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002221 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002222 return false;
2223 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002224}
2225
Richard Smithd62306a2011-11-10 06:34:14 +00002226/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002227static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2228 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002229 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2230 // extension.
2231 if (Type->isVoidType() || Type->isFunctionType()) {
2232 Size = CharUnits::One();
2233 return true;
2234 }
2235
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002236 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002237 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002238 return false;
2239 }
2240
Richard Smithd62306a2011-11-10 06:34:14 +00002241 if (!Type->isConstantSizeType()) {
2242 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002243 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002244 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002245 return false;
2246 }
2247
2248 Size = Info.Ctx.getTypeSizeInChars(Type);
2249 return true;
2250}
2251
2252/// Update a pointer value to model pointer arithmetic.
2253/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002254/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002255/// \param LVal - The pointer value to be updated.
2256/// \param EltTy - The pointee type represented by LVal.
2257/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002258static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2259 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002260 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002261 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002262 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002263 return false;
2264
Yaxun Liu402804b2016-12-15 08:09:08 +00002265 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002266 return true;
2267}
2268
Richard Smithd6cc1982017-01-31 02:23:02 +00002269static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2270 LValue &LVal, QualType EltTy,
2271 int64_t Adjustment) {
2272 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2273 APSInt::get(Adjustment));
2274}
2275
Richard Smith66c96992012-02-18 22:04:06 +00002276/// Update an lvalue to refer to a component of a complex number.
2277/// \param Info - Information about the ongoing evaluation.
2278/// \param LVal - The lvalue to be updated.
2279/// \param EltTy - The complex number's component type.
2280/// \param Imag - False for the real component, true for the imaginary.
2281static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2282 LValue &LVal, QualType EltTy,
2283 bool Imag) {
2284 if (Imag) {
2285 CharUnits SizeOfComponent;
2286 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2287 return false;
2288 LVal.Offset += SizeOfComponent;
2289 }
2290 LVal.addComplex(Info, E, EltTy, Imag);
2291 return true;
2292}
2293
Faisal Vali051e3a22017-02-16 04:12:21 +00002294static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2295 QualType Type, const LValue &LVal,
2296 APValue &RVal);
2297
Richard Smith27908702011-10-24 17:54:18 +00002298/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002299///
2300/// \param Info Information about the ongoing evaluation.
2301/// \param E An expression to be used when printing diagnostics.
2302/// \param VD The variable whose initializer should be obtained.
2303/// \param Frame The frame in which the variable was created. Must be null
2304/// if this variable is not local to the evaluation.
2305/// \param Result Filled in with a pointer to the value of the variable.
2306static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2307 const VarDecl *VD, CallStackFrame *Frame,
2308 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002309
Richard Smith254a73d2011-10-28 22:34:42 +00002310 // If this is a parameter to an active constexpr function call, perform
2311 // argument substitution.
2312 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002313 // Assume arguments of a potential constant expression are unknown
2314 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002315 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002316 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002317 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002319 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002320 }
Richard Smith3229b742013-05-05 21:17:10 +00002321 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002322 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002323 }
Richard Smith27908702011-10-24 17:54:18 +00002324
Richard Smithd9f663b2013-04-22 15:31:51 +00002325 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002326 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002327 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002328 if (!Result) {
2329 // Assume variables referenced within a lambda's call operator that were
2330 // not declared within the call operator are captures and during checking
2331 // of a potential constant expression, assume they are unknown constant
2332 // expressions.
2333 assert(isLambdaCallOperator(Frame->Callee) &&
2334 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2335 "missing value for local variable");
2336 if (Info.checkingPotentialConstantExpression())
2337 return false;
2338 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002339 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002340 diag::note_unimplemented_constexpr_lambda_feature_ast)
2341 << "captures not currently allowed";
2342 return false;
2343 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002344 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002345 }
2346
Richard Smithd0b4dd62011-12-19 06:19:21 +00002347 // Dig out the initializer, and use the declaration which it's attached to.
2348 const Expr *Init = VD->getAnyInitializer(VD);
2349 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002350 // If we're checking a potential constant expression, the variable could be
2351 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002352 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002353 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002354 return false;
2355 }
2356
Richard Smithd62306a2011-11-10 06:34:14 +00002357 // If we're currently evaluating the initializer of this declaration, use that
2358 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002359 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002360 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002361 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002362 }
2363
Richard Smithcecf1842011-11-01 21:06:14 +00002364 // Never evaluate the initializer of a weak variable. We can't be sure that
2365 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002366 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002367 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002368 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002369 }
Richard Smithcecf1842011-11-01 21:06:14 +00002370
Richard Smithd0b4dd62011-12-19 06:19:21 +00002371 // Check that we can fold the initializer. In C++, we will have already done
2372 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002373 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002374 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002375 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002376 Notes.size() + 1) << VD;
2377 Info.Note(VD->getLocation(), diag::note_declared_at);
2378 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002379 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002380 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002381 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002382 Notes.size() + 1) << VD;
2383 Info.Note(VD->getLocation(), diag::note_declared_at);
2384 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002385 }
Richard Smith27908702011-10-24 17:54:18 +00002386
Richard Smith3229b742013-05-05 21:17:10 +00002387 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002388 return true;
Richard Smith27908702011-10-24 17:54:18 +00002389}
2390
Richard Smith11562c52011-10-28 17:51:58 +00002391static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002392 Qualifiers Quals = T.getQualifiers();
2393 return Quals.hasConst() && !Quals.hasVolatile();
2394}
2395
Richard Smithe97cbd72011-11-11 04:05:33 +00002396/// Get the base index of the given base class within an APValue representing
2397/// the given derived class.
2398static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2399 const CXXRecordDecl *Base) {
2400 Base = Base->getCanonicalDecl();
2401 unsigned Index = 0;
2402 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2403 E = Derived->bases_end(); I != E; ++I, ++Index) {
2404 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2405 return Index;
2406 }
2407
2408 llvm_unreachable("base class missing from derived class's bases list");
2409}
2410
Richard Smith3da88fa2013-04-26 14:36:30 +00002411/// Extract the value of a character from a string literal.
2412static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2413 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002414 // FIXME: Support MakeStringConstant
2415 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2416 std::string Str;
2417 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2418 assert(Index <= Str.size() && "Index too large");
2419 return APSInt::getUnsigned(Str.c_str()[Index]);
2420 }
2421
Alexey Bataevec474782014-10-09 08:45:04 +00002422 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2423 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002424 const StringLiteral *S = cast<StringLiteral>(Lit);
2425 const ConstantArrayType *CAT =
2426 Info.Ctx.getAsConstantArrayType(S->getType());
2427 assert(CAT && "string literal isn't an array");
2428 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002429 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002430
2431 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002432 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002433 if (Index < S->getLength())
2434 Value = S->getCodeUnit(Index);
2435 return Value;
2436}
2437
Richard Smith3da88fa2013-04-26 14:36:30 +00002438// Expand a string literal into an array of characters.
2439static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2440 APValue &Result) {
2441 const StringLiteral *S = cast<StringLiteral>(Lit);
2442 const ConstantArrayType *CAT =
2443 Info.Ctx.getAsConstantArrayType(S->getType());
2444 assert(CAT && "string literal isn't an array");
2445 QualType CharType = CAT->getElementType();
2446 assert(CharType->isIntegerType() && "unexpected character type");
2447
2448 unsigned Elts = CAT->getSize().getZExtValue();
2449 Result = APValue(APValue::UninitArray(),
2450 std::min(S->getLength(), Elts), Elts);
2451 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2452 CharType->isUnsignedIntegerType());
2453 if (Result.hasArrayFiller())
2454 Result.getArrayFiller() = APValue(Value);
2455 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2456 Value = S->getCodeUnit(I);
2457 Result.getArrayInitializedElt(I) = APValue(Value);
2458 }
2459}
2460
2461// Expand an array so that it has more than Index filled elements.
2462static void expandArray(APValue &Array, unsigned Index) {
2463 unsigned Size = Array.getArraySize();
2464 assert(Index < Size);
2465
2466 // Always at least double the number of elements for which we store a value.
2467 unsigned OldElts = Array.getArrayInitializedElts();
2468 unsigned NewElts = std::max(Index+1, OldElts * 2);
2469 NewElts = std::min(Size, std::max(NewElts, 8u));
2470
2471 // Copy the data across.
2472 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2473 for (unsigned I = 0; I != OldElts; ++I)
2474 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2475 for (unsigned I = OldElts; I != NewElts; ++I)
2476 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2477 if (NewValue.hasArrayFiller())
2478 NewValue.getArrayFiller() = Array.getArrayFiller();
2479 Array.swap(NewValue);
2480}
2481
Richard Smithb01fe402014-09-16 01:24:02 +00002482/// Determine whether a type would actually be read by an lvalue-to-rvalue
2483/// conversion. If it's of class type, we may assume that the copy operation
2484/// is trivial. Note that this is never true for a union type with fields
2485/// (because the copy always "reads" the active member) and always true for
2486/// a non-class type.
2487static bool isReadByLvalueToRvalueConversion(QualType T) {
2488 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2489 if (!RD || (RD->isUnion() && !RD->field_empty()))
2490 return true;
2491 if (RD->isEmpty())
2492 return false;
2493
2494 for (auto *Field : RD->fields())
2495 if (isReadByLvalueToRvalueConversion(Field->getType()))
2496 return true;
2497
2498 for (auto &BaseSpec : RD->bases())
2499 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2500 return true;
2501
2502 return false;
2503}
2504
2505/// Diagnose an attempt to read from any unreadable field within the specified
2506/// type, which might be a class type.
2507static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2508 QualType T) {
2509 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2510 if (!RD)
2511 return false;
2512
2513 if (!RD->hasMutableFields())
2514 return false;
2515
2516 for (auto *Field : RD->fields()) {
2517 // If we're actually going to read this field in some way, then it can't
2518 // be mutable. If we're in a union, then assigning to a mutable field
2519 // (even an empty one) can change the active member, so that's not OK.
2520 // FIXME: Add core issue number for the union case.
2521 if (Field->isMutable() &&
2522 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002523 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002524 Info.Note(Field->getLocation(), diag::note_declared_at);
2525 return true;
2526 }
2527
2528 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2529 return true;
2530 }
2531
2532 for (auto &BaseSpec : RD->bases())
2533 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2534 return true;
2535
2536 // All mutable fields were empty, and thus not actually read.
2537 return false;
2538}
2539
Richard Smith861b5b52013-05-07 23:34:45 +00002540/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002541enum AccessKinds {
2542 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002543 AK_Assign,
2544 AK_Increment,
2545 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002546};
2547
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002548namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002549/// A handle to a complete object (an object that is not a subobject of
2550/// another object).
2551struct CompleteObject {
2552 /// The value of the complete object.
2553 APValue *Value;
2554 /// The type of the complete object.
2555 QualType Type;
2556
Craig Topper36250ad2014-05-12 05:36:57 +00002557 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002558 CompleteObject(APValue *Value, QualType Type)
2559 : Value(Value), Type(Type) {
2560 assert(Value && "missing value for complete object");
2561 }
2562
Aaron Ballman67347662015-02-15 22:00:28 +00002563 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002564};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002565} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002566
Richard Smith3da88fa2013-04-26 14:36:30 +00002567/// Find the designated sub-object of an rvalue.
2568template<typename SubobjectHandler>
2569typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002570findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002571 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002572 if (Sub.Invalid)
2573 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002574 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002575 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002576 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002577 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002578 << handler.AccessKind;
2579 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002581 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002582 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002583
Richard Smith3229b742013-05-05 21:17:10 +00002584 APValue *O = Obj.Value;
2585 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002586 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002587
Richard Smithd62306a2011-11-10 06:34:14 +00002588 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002589 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2590 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002591 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002592 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002593 return handler.failed();
2594 }
2595
Richard Smith49ca8aa2013-08-06 07:09:20 +00002596 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002597 // If we are reading an object of class type, there may still be more
2598 // things we need to check: if there are any mutable subobjects, we
2599 // cannot perform this read. (This only happens when performing a trivial
2600 // copy or assignment.)
2601 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2602 diagnoseUnreadableFields(Info, E, ObjType))
2603 return handler.failed();
2604
Richard Smith49ca8aa2013-08-06 07:09:20 +00002605 if (!handler.found(*O, ObjType))
2606 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002607
Richard Smith49ca8aa2013-08-06 07:09:20 +00002608 // If we modified a bit-field, truncate it to the right width.
2609 if (handler.AccessKind != AK_Read &&
2610 LastField && LastField->isBitField() &&
2611 !truncateBitfieldValue(Info, E, *O, LastField))
2612 return false;
2613
2614 return true;
2615 }
2616
Craig Topper36250ad2014-05-12 05:36:57 +00002617 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002618 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002619 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002620 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002621 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002622 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002623 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002624 // Note, it should not be possible to form a pointer with a valid
2625 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002627 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002628 << handler.AccessKind;
2629 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002630 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002631 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002632 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002633
2634 ObjType = CAT->getElementType();
2635
Richard Smith14a94132012-02-17 03:35:37 +00002636 // An array object is represented as either an Array APValue or as an
2637 // LValue which refers to a string literal.
2638 if (O->isLValue()) {
2639 assert(I == N - 1 && "extracting subobject of character?");
2640 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002641 if (handler.AccessKind != AK_Read)
2642 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2643 *O);
2644 else
2645 return handler.foundString(*O, ObjType, Index);
2646 }
2647
2648 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002649 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002650 else if (handler.AccessKind != AK_Read) {
2651 expandArray(*O, Index);
2652 O = &O->getArrayInitializedElt(Index);
2653 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002654 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002655 } else if (ObjType->isAnyComplexType()) {
2656 // Next subobject is a complex number.
2657 uint64_t Index = Sub.Entries[I].ArrayIndex;
2658 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002659 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002660 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 << handler.AccessKind;
2662 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002663 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002665 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002666
2667 bool WasConstQualified = ObjType.isConstQualified();
2668 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2669 if (WasConstQualified)
2670 ObjType.addConst();
2671
Richard Smith66c96992012-02-18 22:04:06 +00002672 assert(I == N - 1 && "extracting subobject of scalar?");
2673 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 return handler.found(Index ? O->getComplexIntImag()
2675 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002676 } else {
2677 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002678 return handler.found(Index ? O->getComplexFloatImag()
2679 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002680 }
Richard Smithd62306a2011-11-10 06:34:14 +00002681 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002682 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002683 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002684 << Field;
2685 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002686 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002687 }
2688
Richard Smithd62306a2011-11-10 06:34:14 +00002689 // Next subobject is a class, struct or union field.
2690 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2691 if (RD->isUnion()) {
2692 const FieldDecl *UnionField = O->getUnionField();
2693 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002694 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002695 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002696 << handler.AccessKind << Field << !UnionField << UnionField;
2697 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002698 }
Richard Smithd62306a2011-11-10 06:34:14 +00002699 O = &O->getUnionValue();
2700 } else
2701 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002702
2703 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002704 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002705 if (WasConstQualified && !Field->isMutable())
2706 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002707
2708 if (ObjType.isVolatileQualified()) {
2709 if (Info.getLangOpts().CPlusPlus) {
2710 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002711 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002712 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002713 Info.Note(Field->getLocation(), diag::note_declared_at);
2714 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002715 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002716 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002717 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002718 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002719
2720 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002721 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002722 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002723 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2724 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2725 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002726
2727 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002728 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002729 if (WasConstQualified)
2730 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002731 }
2732 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002733}
2734
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002735namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002736struct ExtractSubobjectHandler {
2737 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002738 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002739
2740 static const AccessKinds AccessKind = AK_Read;
2741
2742 typedef bool result_type;
2743 bool failed() { return false; }
2744 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002745 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002746 return true;
2747 }
2748 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002749 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002750 return true;
2751 }
2752 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002753 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 return true;
2755 }
2756 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002757 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002758 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2759 return true;
2760 }
2761};
Richard Smith3229b742013-05-05 21:17:10 +00002762} // end anonymous namespace
2763
Richard Smith3da88fa2013-04-26 14:36:30 +00002764const AccessKinds ExtractSubobjectHandler::AccessKind;
2765
2766/// Extract the designated sub-object of an rvalue.
2767static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002768 const CompleteObject &Obj,
2769 const SubobjectDesignator &Sub,
2770 APValue &Result) {
2771 ExtractSubobjectHandler Handler = { Info, Result };
2772 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002773}
2774
Richard Smith3229b742013-05-05 21:17:10 +00002775namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002776struct ModifySubobjectHandler {
2777 EvalInfo &Info;
2778 APValue &NewVal;
2779 const Expr *E;
2780
2781 typedef bool result_type;
2782 static const AccessKinds AccessKind = AK_Assign;
2783
2784 bool checkConst(QualType QT) {
2785 // Assigning to a const object has undefined behavior.
2786 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002787 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002788 return false;
2789 }
2790 return true;
2791 }
2792
2793 bool failed() { return false; }
2794 bool found(APValue &Subobj, QualType SubobjType) {
2795 if (!checkConst(SubobjType))
2796 return false;
2797 // We've been given ownership of NewVal, so just swap it in.
2798 Subobj.swap(NewVal);
2799 return true;
2800 }
2801 bool found(APSInt &Value, QualType SubobjType) {
2802 if (!checkConst(SubobjType))
2803 return false;
2804 if (!NewVal.isInt()) {
2805 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002806 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002807 return false;
2808 }
2809 Value = NewVal.getInt();
2810 return true;
2811 }
2812 bool found(APFloat &Value, QualType SubobjType) {
2813 if (!checkConst(SubobjType))
2814 return false;
2815 Value = NewVal.getFloat();
2816 return true;
2817 }
2818 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2819 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2820 }
2821};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002822} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002823
Richard Smith3229b742013-05-05 21:17:10 +00002824const AccessKinds ModifySubobjectHandler::AccessKind;
2825
Richard Smith3da88fa2013-04-26 14:36:30 +00002826/// Update the designated sub-object of an rvalue to the given value.
2827static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002828 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 const SubobjectDesignator &Sub,
2830 APValue &NewVal) {
2831 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002832 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002833}
2834
Richard Smith84f6dcf2012-02-02 01:16:57 +00002835/// Find the position where two subobject designators diverge, or equivalently
2836/// the length of the common initial subsequence.
2837static unsigned FindDesignatorMismatch(QualType ObjType,
2838 const SubobjectDesignator &A,
2839 const SubobjectDesignator &B,
2840 bool &WasArrayIndex) {
2841 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2842 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002843 if (!ObjType.isNull() &&
2844 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002845 // Next subobject is an array element.
2846 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2847 WasArrayIndex = true;
2848 return I;
2849 }
Richard Smith66c96992012-02-18 22:04:06 +00002850 if (ObjType->isAnyComplexType())
2851 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2852 else
2853 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002854 } else {
2855 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2856 WasArrayIndex = false;
2857 return I;
2858 }
2859 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2860 // Next subobject is a field.
2861 ObjType = FD->getType();
2862 else
2863 // Next subobject is a base class.
2864 ObjType = QualType();
2865 }
2866 }
2867 WasArrayIndex = false;
2868 return I;
2869}
2870
2871/// Determine whether the given subobject designators refer to elements of the
2872/// same array object.
2873static bool AreElementsOfSameArray(QualType ObjType,
2874 const SubobjectDesignator &A,
2875 const SubobjectDesignator &B) {
2876 if (A.Entries.size() != B.Entries.size())
2877 return false;
2878
George Burgess IVa51c4072015-10-16 01:49:01 +00002879 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002880 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2881 // A is a subobject of the array element.
2882 return false;
2883
2884 // If A (and B) designates an array element, the last entry will be the array
2885 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2886 // of length 1' case, and the entire path must match.
2887 bool WasArrayIndex;
2888 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2889 return CommonLength >= A.Entries.size() - IsArray;
2890}
2891
Richard Smith3229b742013-05-05 21:17:10 +00002892/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002893static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2894 AccessKinds AK, const LValue &LVal,
2895 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002896 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002897 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002898 return CompleteObject();
2899 }
2900
Craig Topper36250ad2014-05-12 05:36:57 +00002901 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002902 if (LVal.CallIndex) {
2903 Frame = Info.getCallFrame(LVal.CallIndex);
2904 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002905 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002906 << AK << LVal.Base.is<const ValueDecl*>();
2907 NoteLValueLocation(Info, LVal.Base);
2908 return CompleteObject();
2909 }
Richard Smith3229b742013-05-05 21:17:10 +00002910 }
2911
2912 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2913 // is not a constant expression (even if the object is non-volatile). We also
2914 // apply this rule to C++98, in order to conform to the expected 'volatile'
2915 // semantics.
2916 if (LValType.isVolatileQualified()) {
2917 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002918 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002919 << AK << LValType;
2920 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002921 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002922 return CompleteObject();
2923 }
2924
2925 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002926 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002927 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002928
2929 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2930 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2931 // In C++11, constexpr, non-volatile variables initialized with constant
2932 // expressions are constant expressions too. Inside constexpr functions,
2933 // parameters are constant expressions even if they're non-const.
2934 // In C++1y, objects local to a constant expression (those with a Frame) are
2935 // both readable and writable inside constant expressions.
2936 // In C, such things can also be folded, although they are not ICEs.
2937 const VarDecl *VD = dyn_cast<VarDecl>(D);
2938 if (VD) {
2939 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2940 VD = VDef;
2941 }
2942 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002943 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002944 return CompleteObject();
2945 }
2946
2947 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002948 if (BaseType.isVolatileQualified()) {
2949 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002950 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002951 << AK << 1 << VD;
2952 Info.Note(VD->getLocation(), diag::note_declared_at);
2953 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002954 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002955 }
2956 return CompleteObject();
2957 }
2958
2959 // Unless we're looking at a local variable or argument in a constexpr call,
2960 // the variable we're reading must be const.
2961 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002962 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002963 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2964 // OK, we can read and modify an object if we're in the process of
2965 // evaluating its initializer, because its lifetime began in this
2966 // evaluation.
2967 } else if (AK != AK_Read) {
2968 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002969 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002970 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002971 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002972 // OK, we can read this variable.
2973 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002974 // In OpenCL if a variable is in constant address space it is a const value.
2975 if (!(BaseType.isConstQualified() ||
2976 (Info.getLangOpts().OpenCL &&
2977 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002978 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002979 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002980 Info.Note(VD->getLocation(), diag::note_declared_at);
2981 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002982 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002983 }
2984 return CompleteObject();
2985 }
2986 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2987 // We support folding of const floating-point types, in order to make
2988 // static const data members of such types (supported as an extension)
2989 // more useful.
2990 if (Info.getLangOpts().CPlusPlus11) {
2991 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2992 Info.Note(VD->getLocation(), diag::note_declared_at);
2993 } else {
2994 Info.CCEDiag(E);
2995 }
George Burgess IVb5316982016-12-27 05:33:20 +00002996 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2997 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2998 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002999 } else {
3000 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003001 if (Info.checkingPotentialConstantExpression() &&
3002 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3003 // The definition of this variable could be constexpr. We can't
3004 // access it right now, but may be able to in future.
3005 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003006 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003007 Info.Note(VD->getLocation(), diag::note_declared_at);
3008 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003009 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003010 }
3011 return CompleteObject();
3012 }
3013 }
3014
3015 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3016 return CompleteObject();
3017 } else {
3018 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3019
3020 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003021 if (const MaterializeTemporaryExpr *MTE =
3022 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3023 assert(MTE->getStorageDuration() == SD_Static &&
3024 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003025
Richard Smithe6c01442013-06-05 00:46:14 +00003026 // Per C++1y [expr.const]p2:
3027 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3028 // - a [...] glvalue of integral or enumeration type that refers to
3029 // a non-volatile const object [...]
3030 // [...]
3031 // - a [...] glvalue of literal type that refers to a non-volatile
3032 // object whose lifetime began within the evaluation of e.
3033 //
3034 // C++11 misses the 'began within the evaluation of e' check and
3035 // instead allows all temporaries, including things like:
3036 // int &&r = 1;
3037 // int x = ++r;
3038 // constexpr int k = r;
3039 // Therefore we use the C++1y rules in C++11 too.
3040 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3041 const ValueDecl *ED = MTE->getExtendingDecl();
3042 if (!(BaseType.isConstQualified() &&
3043 BaseType->isIntegralOrEnumerationType()) &&
3044 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003045 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003046 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3047 return CompleteObject();
3048 }
3049
3050 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3051 assert(BaseVal && "got reference to unevaluated temporary");
3052 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003053 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003054 return CompleteObject();
3055 }
3056 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003057 BaseVal = Frame->getTemporary(Base);
3058 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003059 }
Richard Smith3229b742013-05-05 21:17:10 +00003060
3061 // Volatile temporary objects cannot be accessed in constant expressions.
3062 if (BaseType.isVolatileQualified()) {
3063 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003065 << AK << 0;
3066 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3067 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003068 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003069 }
3070 return CompleteObject();
3071 }
3072 }
3073
Richard Smith7525ff62013-05-09 07:14:00 +00003074 // During the construction of an object, it is not yet 'const'.
3075 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3076 // and this doesn't do quite the right thing for const subobjects of the
3077 // object under construction.
3078 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3079 BaseType = Info.Ctx.getCanonicalType(BaseType);
3080 BaseType.removeLocalConst();
3081 }
3082
Richard Smith6d4c6582013-11-05 22:18:15 +00003083 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003084 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003085 //
3086 // FIXME: Not all local state is mutable. Allow local constant subobjects
3087 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003088 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3089 Info.EvalStatus.HasSideEffects) ||
3090 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003091 return CompleteObject();
3092
3093 return CompleteObject(BaseVal, BaseType);
3094}
3095
Richard Smith243ef902013-05-05 23:31:59 +00003096/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3097/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3098/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003099///
3100/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003101/// \param Conv - The expression for which we are performing the conversion.
3102/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003103/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3104/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003105/// \param LVal - The glvalue on which we are attempting to perform this action.
3106/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003107static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003108 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003109 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003110 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003111 return false;
3112
Richard Smith3229b742013-05-05 21:17:10 +00003113 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003114 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003115 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003116 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3117 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3118 // initializer until now for such expressions. Such an expression can't be
3119 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003120 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003121 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003122 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003123 }
Richard Smith3229b742013-05-05 21:17:10 +00003124 APValue Lit;
3125 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3126 return false;
3127 CompleteObject LitObj(&Lit, Base->getType());
3128 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003129 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003130 // We represent a string literal array as an lvalue pointing at the
3131 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003132 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003133 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3134 CompleteObject StrObj(&Str, Base->getType());
3135 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003136 }
Richard Smith11562c52011-10-28 17:51:58 +00003137 }
3138
Richard Smith3229b742013-05-05 21:17:10 +00003139 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3140 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003141}
3142
3143/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003144static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003145 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003146 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003147 return false;
3148
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003149 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003151 return false;
3152 }
3153
Richard Smith3229b742013-05-05 21:17:10 +00003154 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3155 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003156}
3157
Richard Smith243ef902013-05-05 23:31:59 +00003158static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3159 return T->isSignedIntegerType() &&
3160 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3161}
3162
3163namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003164struct CompoundAssignSubobjectHandler {
3165 EvalInfo &Info;
3166 const Expr *E;
3167 QualType PromotedLHSType;
3168 BinaryOperatorKind Opcode;
3169 const APValue &RHS;
3170
3171 static const AccessKinds AccessKind = AK_Assign;
3172
3173 typedef bool result_type;
3174
3175 bool checkConst(QualType QT) {
3176 // Assigning to a const object has undefined behavior.
3177 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003178 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003179 return false;
3180 }
3181 return true;
3182 }
3183
3184 bool failed() { return false; }
3185 bool found(APValue &Subobj, QualType SubobjType) {
3186 switch (Subobj.getKind()) {
3187 case APValue::Int:
3188 return found(Subobj.getInt(), SubobjType);
3189 case APValue::Float:
3190 return found(Subobj.getFloat(), SubobjType);
3191 case APValue::ComplexInt:
3192 case APValue::ComplexFloat:
3193 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003194 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003195 return false;
3196 case APValue::LValue:
3197 return foundPointer(Subobj, SubobjType);
3198 default:
3199 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003200 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003201 return false;
3202 }
3203 }
3204 bool found(APSInt &Value, QualType SubobjType) {
3205 if (!checkConst(SubobjType))
3206 return false;
3207
3208 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3209 // We don't support compound assignment on integer-cast-to-pointer
3210 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003211 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003212 return false;
3213 }
3214
3215 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3216 SubobjType, Value);
3217 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3218 return false;
3219 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3220 return true;
3221 }
3222 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003223 return checkConst(SubobjType) &&
3224 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3225 Value) &&
3226 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3227 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003228 }
3229 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3230 if (!checkConst(SubobjType))
3231 return false;
3232
3233 QualType PointeeType;
3234 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3235 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003236
3237 if (PointeeType.isNull() || !RHS.isInt() ||
3238 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003239 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003240 return false;
3241 }
3242
Richard Smithd6cc1982017-01-31 02:23:02 +00003243 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003244 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003245 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003246
3247 LValue LVal;
3248 LVal.setFrom(Info.Ctx, Subobj);
3249 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3250 return false;
3251 LVal.moveInto(Subobj);
3252 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003253 }
3254 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3255 llvm_unreachable("shouldn't encounter string elements here");
3256 }
3257};
3258} // end anonymous namespace
3259
3260const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3261
3262/// Perform a compound assignment of LVal <op>= RVal.
3263static bool handleCompoundAssignment(
3264 EvalInfo &Info, const Expr *E,
3265 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3266 BinaryOperatorKind Opcode, const APValue &RVal) {
3267 if (LVal.Designator.Invalid)
3268 return false;
3269
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003270 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003271 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003272 return false;
3273 }
3274
3275 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3276 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3277 RVal };
3278 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3279}
3280
3281namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003282struct IncDecSubobjectHandler {
3283 EvalInfo &Info;
3284 const Expr *E;
3285 AccessKinds AccessKind;
3286 APValue *Old;
3287
3288 typedef bool result_type;
3289
3290 bool checkConst(QualType QT) {
3291 // Assigning to a const object has undefined behavior.
3292 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003293 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003294 return false;
3295 }
3296 return true;
3297 }
3298
3299 bool failed() { return false; }
3300 bool found(APValue &Subobj, QualType SubobjType) {
3301 // Stash the old value. Also clear Old, so we don't clobber it later
3302 // if we're post-incrementing a complex.
3303 if (Old) {
3304 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003305 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003306 }
3307
3308 switch (Subobj.getKind()) {
3309 case APValue::Int:
3310 return found(Subobj.getInt(), SubobjType);
3311 case APValue::Float:
3312 return found(Subobj.getFloat(), SubobjType);
3313 case APValue::ComplexInt:
3314 return found(Subobj.getComplexIntReal(),
3315 SubobjType->castAs<ComplexType>()->getElementType()
3316 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3317 case APValue::ComplexFloat:
3318 return found(Subobj.getComplexFloatReal(),
3319 SubobjType->castAs<ComplexType>()->getElementType()
3320 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3321 case APValue::LValue:
3322 return foundPointer(Subobj, SubobjType);
3323 default:
3324 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003325 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003326 return false;
3327 }
3328 }
3329 bool found(APSInt &Value, QualType SubobjType) {
3330 if (!checkConst(SubobjType))
3331 return false;
3332
3333 if (!SubobjType->isIntegerType()) {
3334 // We don't support increment / decrement on integer-cast-to-pointer
3335 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003336 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003337 return false;
3338 }
3339
3340 if (Old) *Old = APValue(Value);
3341
3342 // bool arithmetic promotes to int, and the conversion back to bool
3343 // doesn't reduce mod 2^n, so special-case it.
3344 if (SubobjType->isBooleanType()) {
3345 if (AccessKind == AK_Increment)
3346 Value = 1;
3347 else
3348 Value = !Value;
3349 return true;
3350 }
3351
3352 bool WasNegative = Value.isNegative();
3353 if (AccessKind == AK_Increment) {
3354 ++Value;
3355
3356 if (!WasNegative && Value.isNegative() &&
3357 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3358 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003359 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003360 }
3361 } else {
3362 --Value;
3363
3364 if (WasNegative && !Value.isNegative() &&
3365 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3366 unsigned BitWidth = Value.getBitWidth();
3367 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3368 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003369 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003370 }
3371 }
3372 return true;
3373 }
3374 bool found(APFloat &Value, QualType SubobjType) {
3375 if (!checkConst(SubobjType))
3376 return false;
3377
3378 if (Old) *Old = APValue(Value);
3379
3380 APFloat One(Value.getSemantics(), 1);
3381 if (AccessKind == AK_Increment)
3382 Value.add(One, APFloat::rmNearestTiesToEven);
3383 else
3384 Value.subtract(One, APFloat::rmNearestTiesToEven);
3385 return true;
3386 }
3387 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3388 if (!checkConst(SubobjType))
3389 return false;
3390
3391 QualType PointeeType;
3392 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3393 PointeeType = PT->getPointeeType();
3394 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003395 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003396 return false;
3397 }
3398
3399 LValue LVal;
3400 LVal.setFrom(Info.Ctx, Subobj);
3401 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3402 AccessKind == AK_Increment ? 1 : -1))
3403 return false;
3404 LVal.moveInto(Subobj);
3405 return true;
3406 }
3407 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3408 llvm_unreachable("shouldn't encounter string elements here");
3409 }
3410};
3411} // end anonymous namespace
3412
3413/// Perform an increment or decrement on LVal.
3414static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3415 QualType LValType, bool IsIncrement, APValue *Old) {
3416 if (LVal.Designator.Invalid)
3417 return false;
3418
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003419 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003420 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003421 return false;
3422 }
3423
3424 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3425 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3426 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3427 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3428}
3429
Richard Smithe97cbd72011-11-11 04:05:33 +00003430/// Build an lvalue for the object argument of a member function call.
3431static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3432 LValue &This) {
3433 if (Object->getType()->isPointerType())
3434 return EvaluatePointer(Object, This, Info);
3435
3436 if (Object->isGLValue())
3437 return EvaluateLValue(Object, This, Info);
3438
Richard Smithd9f663b2013-04-22 15:31:51 +00003439 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003440 return EvaluateTemporary(Object, This, Info);
3441
Faisal Valie690b7a2016-07-02 22:34:24 +00003442 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003443 return false;
3444}
3445
3446/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3447/// lvalue referring to the result.
3448///
3449/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003450/// \param LV - An lvalue referring to the base of the member pointer.
3451/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003452/// \param IncludeMember - Specifies whether the member itself is included in
3453/// the resulting LValue subobject designator. This is not possible when
3454/// creating a bound member function.
3455/// \return The field or method declaration to which the member pointer refers,
3456/// or 0 if evaluation fails.
3457static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003458 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003459 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003460 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003461 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003462 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003463 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003464 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003465
3466 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3467 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003468 if (!MemPtr.getDecl()) {
3469 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003470 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003471 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003472 }
Richard Smith253c2a32012-01-27 01:14:48 +00003473
Richard Smith027bf112011-11-17 22:56:20 +00003474 if (MemPtr.isDerivedMember()) {
3475 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003476 // The end of the derived-to-base path for the base object must match the
3477 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003478 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003479 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003480 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003481 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003482 }
Richard Smith027bf112011-11-17 22:56:20 +00003483 unsigned PathLengthToMember =
3484 LV.Designator.Entries.size() - MemPtr.Path.size();
3485 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3486 const CXXRecordDecl *LVDecl = getAsBaseClass(
3487 LV.Designator.Entries[PathLengthToMember + I]);
3488 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003489 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003490 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003491 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003492 }
Richard Smith027bf112011-11-17 22:56:20 +00003493 }
3494
3495 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003496 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003497 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003498 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003499 } else if (!MemPtr.Path.empty()) {
3500 // Extend the LValue path with the member pointer's path.
3501 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3502 MemPtr.Path.size() + IncludeMember);
3503
3504 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003505 if (const PointerType *PT = LVType->getAs<PointerType>())
3506 LVType = PT->getPointeeType();
3507 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3508 assert(RD && "member pointer access on non-class-type expression");
3509 // The first class in the path is that of the lvalue.
3510 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3511 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003512 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003513 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003514 RD = Base;
3515 }
3516 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003517 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3518 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003519 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003520 }
3521
3522 // Add the member. Note that we cannot build bound member functions here.
3523 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003524 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003525 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003526 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003527 } else if (const IndirectFieldDecl *IFD =
3528 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003529 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003530 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003531 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003532 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003533 }
Richard Smith027bf112011-11-17 22:56:20 +00003534 }
3535
3536 return MemPtr.getDecl();
3537}
3538
Richard Smith84401042013-06-03 05:03:02 +00003539static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3540 const BinaryOperator *BO,
3541 LValue &LV,
3542 bool IncludeMember = true) {
3543 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3544
3545 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003546 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003547 MemberPtr MemPtr;
3548 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3549 }
Craig Topper36250ad2014-05-12 05:36:57 +00003550 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003551 }
3552
3553 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3554 BO->getRHS(), IncludeMember);
3555}
3556
Richard Smith027bf112011-11-17 22:56:20 +00003557/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3558/// the provided lvalue, which currently refers to the base object.
3559static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3560 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003561 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003562 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003563 return false;
3564
Richard Smitha8105bc2012-01-06 16:39:00 +00003565 QualType TargetQT = E->getType();
3566 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3567 TargetQT = PT->getPointeeType();
3568
3569 // Check this cast lands within the final derived-to-base subobject path.
3570 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003571 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003572 << D.MostDerivedType << TargetQT;
3573 return false;
3574 }
3575
Richard Smith027bf112011-11-17 22:56:20 +00003576 // Check the type of the final cast. We don't need to check the path,
3577 // since a cast can only be formed if the path is unique.
3578 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003579 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3580 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003581 if (NewEntriesSize == D.MostDerivedPathLength)
3582 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3583 else
Richard Smith027bf112011-11-17 22:56:20 +00003584 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003585 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003586 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003587 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003588 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 }
Richard Smith027bf112011-11-17 22:56:20 +00003590
3591 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003592 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003593}
3594
Mike Stump876387b2009-10-27 22:09:17 +00003595namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003596enum EvalStmtResult {
3597 /// Evaluation failed.
3598 ESR_Failed,
3599 /// Hit a 'return' statement.
3600 ESR_Returned,
3601 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003602 ESR_Succeeded,
3603 /// Hit a 'continue' statement.
3604 ESR_Continue,
3605 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003606 ESR_Break,
3607 /// Still scanning for 'case' or 'default' statement.
3608 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003609};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003610}
Richard Smith254a73d2011-10-28 22:34:42 +00003611
Richard Smith97fcf4b2016-08-14 23:15:52 +00003612static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3613 // We don't need to evaluate the initializer for a static local.
3614 if (!VD->hasLocalStorage())
3615 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003616
Richard Smith97fcf4b2016-08-14 23:15:52 +00003617 LValue Result;
3618 Result.set(VD, Info.CurrentCall->Index);
3619 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003620
Richard Smith97fcf4b2016-08-14 23:15:52 +00003621 const Expr *InitE = VD->getInit();
3622 if (!InitE) {
3623 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3624 << false << VD->getType();
3625 Val = APValue();
3626 return false;
3627 }
Richard Smith51f03172013-06-20 03:00:05 +00003628
Richard Smith97fcf4b2016-08-14 23:15:52 +00003629 if (InitE->isValueDependent())
3630 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003631
Richard Smith97fcf4b2016-08-14 23:15:52 +00003632 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3633 // Wipe out any partially-computed value, to allow tracking that this
3634 // evaluation failed.
3635 Val = APValue();
3636 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003637 }
3638
3639 return true;
3640}
3641
Richard Smith97fcf4b2016-08-14 23:15:52 +00003642static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3643 bool OK = true;
3644
3645 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3646 OK &= EvaluateVarDecl(Info, VD);
3647
3648 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3649 for (auto *BD : DD->bindings())
3650 if (auto *VD = BD->getHoldingVar())
3651 OK &= EvaluateDecl(Info, VD);
3652
3653 return OK;
3654}
3655
3656
Richard Smith4e18ca52013-05-06 05:56:11 +00003657/// Evaluate a condition (either a variable declaration or an expression).
3658static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3659 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003660 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003661 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3662 return false;
3663 return EvaluateAsBooleanCondition(Cond, Result, Info);
3664}
3665
Richard Smith89210072016-04-04 23:29:43 +00003666namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003667/// \brief A location where the result (returned value) of evaluating a
3668/// statement should be stored.
3669struct StmtResult {
3670 /// The APValue that should be filled in with the returned value.
3671 APValue &Value;
3672 /// The location containing the result, if any (used to support RVO).
3673 const LValue *Slot;
3674};
Richard Smith89210072016-04-04 23:29:43 +00003675}
Richard Smith52a980a2015-08-28 02:43:42 +00003676
3677static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003678 const Stmt *S,
3679 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003680
3681/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003682static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003683 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003684 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003685 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003686 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003687 case ESR_Break:
3688 return ESR_Succeeded;
3689 case ESR_Succeeded:
3690 case ESR_Continue:
3691 return ESR_Continue;
3692 case ESR_Failed:
3693 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003694 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003695 return ESR;
3696 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003697 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003698}
3699
Richard Smith496ddcf2013-05-12 17:32:42 +00003700/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003701static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003702 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003703 BlockScopeRAII Scope(Info);
3704
Richard Smith496ddcf2013-05-12 17:32:42 +00003705 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003706 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003707 {
3708 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003709 if (const Stmt *Init = SS->getInit()) {
3710 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3711 if (ESR != ESR_Succeeded)
3712 return ESR;
3713 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003714 if (SS->getConditionVariable() &&
3715 !EvaluateDecl(Info, SS->getConditionVariable()))
3716 return ESR_Failed;
3717 if (!EvaluateInteger(SS->getCond(), Value, Info))
3718 return ESR_Failed;
3719 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003720
3721 // Find the switch case corresponding to the value of the condition.
3722 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003723 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003724 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3725 SC = SC->getNextSwitchCase()) {
3726 if (isa<DefaultStmt>(SC)) {
3727 Found = SC;
3728 continue;
3729 }
3730
3731 const CaseStmt *CS = cast<CaseStmt>(SC);
3732 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3733 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3734 : LHS;
3735 if (LHS <= Value && Value <= RHS) {
3736 Found = SC;
3737 break;
3738 }
3739 }
3740
3741 if (!Found)
3742 return ESR_Succeeded;
3743
3744 // Search the switch body for the switch case and evaluate it from there.
3745 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3746 case ESR_Break:
3747 return ESR_Succeeded;
3748 case ESR_Succeeded:
3749 case ESR_Continue:
3750 case ESR_Failed:
3751 case ESR_Returned:
3752 return ESR;
3753 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003754 // This can only happen if the switch case is nested within a statement
3755 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003756 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003757 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003758 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003759 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003760}
3761
Richard Smith254a73d2011-10-28 22:34:42 +00003762// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003763static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003764 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003765 if (!Info.nextStep(S))
3766 return ESR_Failed;
3767
Richard Smith496ddcf2013-05-12 17:32:42 +00003768 // If we're hunting down a 'case' or 'default' label, recurse through
3769 // substatements until we hit the label.
3770 if (Case) {
3771 // FIXME: We don't start the lifetime of objects whose initialization we
3772 // jump over. However, such objects must be of class type with a trivial
3773 // default constructor that initialize all subobjects, so must be empty,
3774 // so this almost never matters.
3775 switch (S->getStmtClass()) {
3776 case Stmt::CompoundStmtClass:
3777 // FIXME: Precompute which substatement of a compound statement we
3778 // would jump to, and go straight there rather than performing a
3779 // linear scan each time.
3780 case Stmt::LabelStmtClass:
3781 case Stmt::AttributedStmtClass:
3782 case Stmt::DoStmtClass:
3783 break;
3784
3785 case Stmt::CaseStmtClass:
3786 case Stmt::DefaultStmtClass:
3787 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003788 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003789 break;
3790
3791 case Stmt::IfStmtClass: {
3792 // FIXME: Precompute which side of an 'if' we would jump to, and go
3793 // straight there rather than scanning both sides.
3794 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003795
3796 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3797 // preceded by our switch label.
3798 BlockScopeRAII Scope(Info);
3799
Richard Smith496ddcf2013-05-12 17:32:42 +00003800 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3801 if (ESR != ESR_CaseNotFound || !IS->getElse())
3802 return ESR;
3803 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3804 }
3805
3806 case Stmt::WhileStmtClass: {
3807 EvalStmtResult ESR =
3808 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3809 if (ESR != ESR_Continue)
3810 return ESR;
3811 break;
3812 }
3813
3814 case Stmt::ForStmtClass: {
3815 const ForStmt *FS = cast<ForStmt>(S);
3816 EvalStmtResult ESR =
3817 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3818 if (ESR != ESR_Continue)
3819 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003820 if (FS->getInc()) {
3821 FullExpressionRAII IncScope(Info);
3822 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3823 return ESR_Failed;
3824 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003825 break;
3826 }
3827
3828 case Stmt::DeclStmtClass:
3829 // FIXME: If the variable has initialization that can't be jumped over,
3830 // bail out of any immediately-surrounding compound-statement too.
3831 default:
3832 return ESR_CaseNotFound;
3833 }
3834 }
3835
Richard Smith254a73d2011-10-28 22:34:42 +00003836 switch (S->getStmtClass()) {
3837 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003838 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003839 // Don't bother evaluating beyond an expression-statement which couldn't
3840 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003841 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003842 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003843 return ESR_Failed;
3844 return ESR_Succeeded;
3845 }
3846
Faisal Valie690b7a2016-07-02 22:34:24 +00003847 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003848 return ESR_Failed;
3849
3850 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003851 return ESR_Succeeded;
3852
Richard Smithd9f663b2013-04-22 15:31:51 +00003853 case Stmt::DeclStmtClass: {
3854 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003855 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003856 // Each declaration initialization is its own full-expression.
3857 // FIXME: This isn't quite right; if we're performing aggregate
3858 // initialization, each braced subexpression is its own full-expression.
3859 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003860 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003861 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003862 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003863 return ESR_Succeeded;
3864 }
3865
Richard Smith357362d2011-12-13 06:39:58 +00003866 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003867 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003868 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003869 if (RetExpr &&
3870 !(Result.Slot
3871 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3872 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003873 return ESR_Failed;
3874 return ESR_Returned;
3875 }
Richard Smith254a73d2011-10-28 22:34:42 +00003876
3877 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003878 BlockScopeRAII Scope(Info);
3879
Richard Smith254a73d2011-10-28 22:34:42 +00003880 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003881 for (const auto *BI : CS->body()) {
3882 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003883 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003884 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003885 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003886 return ESR;
3887 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003888 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003889 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003890
3891 case Stmt::IfStmtClass: {
3892 const IfStmt *IS = cast<IfStmt>(S);
3893
3894 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003895 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003896 if (const Stmt *Init = IS->getInit()) {
3897 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3898 if (ESR != ESR_Succeeded)
3899 return ESR;
3900 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003901 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003902 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003903 return ESR_Failed;
3904
3905 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3906 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3907 if (ESR != ESR_Succeeded)
3908 return ESR;
3909 }
3910 return ESR_Succeeded;
3911 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003912
3913 case Stmt::WhileStmtClass: {
3914 const WhileStmt *WS = cast<WhileStmt>(S);
3915 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003916 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003917 bool Continue;
3918 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3919 Continue))
3920 return ESR_Failed;
3921 if (!Continue)
3922 break;
3923
3924 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3925 if (ESR != ESR_Continue)
3926 return ESR;
3927 }
3928 return ESR_Succeeded;
3929 }
3930
3931 case Stmt::DoStmtClass: {
3932 const DoStmt *DS = cast<DoStmt>(S);
3933 bool Continue;
3934 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003935 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003936 if (ESR != ESR_Continue)
3937 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003938 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003939
Richard Smith08d6a2c2013-07-24 07:11:57 +00003940 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003941 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3942 return ESR_Failed;
3943 } while (Continue);
3944 return ESR_Succeeded;
3945 }
3946
3947 case Stmt::ForStmtClass: {
3948 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003949 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003950 if (FS->getInit()) {
3951 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3952 if (ESR != ESR_Succeeded)
3953 return ESR;
3954 }
3955 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003956 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003957 bool Continue = true;
3958 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3959 FS->getCond(), Continue))
3960 return ESR_Failed;
3961 if (!Continue)
3962 break;
3963
3964 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3965 if (ESR != ESR_Continue)
3966 return ESR;
3967
Richard Smith08d6a2c2013-07-24 07:11:57 +00003968 if (FS->getInc()) {
3969 FullExpressionRAII IncScope(Info);
3970 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3971 return ESR_Failed;
3972 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003973 }
3974 return ESR_Succeeded;
3975 }
3976
Richard Smith896e0d72013-05-06 06:51:17 +00003977 case Stmt::CXXForRangeStmtClass: {
3978 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003980
3981 // Initialize the __range variable.
3982 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3983 if (ESR != ESR_Succeeded)
3984 return ESR;
3985
3986 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003987 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3988 if (ESR != ESR_Succeeded)
3989 return ESR;
3990 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003991 if (ESR != ESR_Succeeded)
3992 return ESR;
3993
3994 while (true) {
3995 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003996 {
3997 bool Continue = true;
3998 FullExpressionRAII CondExpr(Info);
3999 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4000 return ESR_Failed;
4001 if (!Continue)
4002 break;
4003 }
Richard Smith896e0d72013-05-06 06:51:17 +00004004
4005 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004007 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4008 if (ESR != ESR_Succeeded)
4009 return ESR;
4010
4011 // Loop body.
4012 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4013 if (ESR != ESR_Continue)
4014 return ESR;
4015
4016 // Increment: ++__begin
4017 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4018 return ESR_Failed;
4019 }
4020
4021 return ESR_Succeeded;
4022 }
4023
Richard Smith496ddcf2013-05-12 17:32:42 +00004024 case Stmt::SwitchStmtClass:
4025 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4026
Richard Smith4e18ca52013-05-06 05:56:11 +00004027 case Stmt::ContinueStmtClass:
4028 return ESR_Continue;
4029
4030 case Stmt::BreakStmtClass:
4031 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004032
4033 case Stmt::LabelStmtClass:
4034 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4035
4036 case Stmt::AttributedStmtClass:
4037 // As a general principle, C++11 attributes can be ignored without
4038 // any semantic impact.
4039 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4040 Case);
4041
4042 case Stmt::CaseStmtClass:
4043 case Stmt::DefaultStmtClass:
4044 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004045 }
4046}
4047
Richard Smithcc36f692011-12-22 02:22:31 +00004048/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4049/// default constructor. If so, we'll fold it whether or not it's marked as
4050/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4051/// so we need special handling.
4052static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004053 const CXXConstructorDecl *CD,
4054 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004055 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4056 return false;
4057
Richard Smith66e05fe2012-01-18 05:21:49 +00004058 // Value-initialization does not call a trivial default constructor, so such a
4059 // call is a core constant expression whether or not the constructor is
4060 // constexpr.
4061 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004062 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004063 // FIXME: If DiagDecl is an implicitly-declared special member function,
4064 // we should be much more explicit about why it's not constexpr.
4065 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4066 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4067 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004068 } else {
4069 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4070 }
4071 }
4072 return true;
4073}
4074
Richard Smith357362d2011-12-13 06:39:58 +00004075/// CheckConstexprFunction - Check that a function can be called in a constant
4076/// expression.
4077static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4078 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004079 const FunctionDecl *Definition,
4080 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004081 // Potential constant expressions can contain calls to declared, but not yet
4082 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004083 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004084 Declaration->isConstexpr())
4085 return false;
4086
Richard Smith0838f3a2013-05-14 05:18:44 +00004087 // Bail out with no diagnostic if the function declaration itself is invalid.
4088 // We will have produced a relevant diagnostic while parsing it.
4089 if (Declaration->isInvalidDecl())
4090 return false;
4091
Richard Smith357362d2011-12-13 06:39:58 +00004092 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004093 if (Definition && Definition->isConstexpr() &&
4094 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004095 return true;
4096
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004097 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004098 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004099
Richard Smith5179eb72016-06-28 19:03:57 +00004100 // If this function is not constexpr because it is an inherited
4101 // non-constexpr constructor, diagnose that directly.
4102 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4103 if (CD && CD->isInheritingConstructor()) {
4104 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4105 if (!Inherited->isConstexpr())
4106 DiagDecl = CD = Inherited;
4107 }
4108
4109 // FIXME: If DiagDecl is an implicitly-declared special member function
4110 // or an inheriting constructor, we should be much more explicit about why
4111 // it's not constexpr.
4112 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004113 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004114 << CD->getInheritedConstructor().getConstructor()->getParent();
4115 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004116 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004117 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4119 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004120 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004121 }
4122 return false;
4123}
4124
Richard Smithbe6dd812014-11-19 21:27:17 +00004125/// Determine if a class has any fields that might need to be copied by a
4126/// trivial copy or move operation.
4127static bool hasFields(const CXXRecordDecl *RD) {
4128 if (!RD || RD->isEmpty())
4129 return false;
4130 for (auto *FD : RD->fields()) {
4131 if (FD->isUnnamedBitfield())
4132 continue;
4133 return true;
4134 }
4135 for (auto &Base : RD->bases())
4136 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4137 return true;
4138 return false;
4139}
4140
Richard Smithd62306a2011-11-10 06:34:14 +00004141namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004142typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004143}
4144
4145/// EvaluateArgs - Evaluate the arguments to a function call.
4146static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4147 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004148 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004149 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004150 I != E; ++I) {
4151 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4152 // If we're checking for a potential constant expression, evaluate all
4153 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004154 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004155 return false;
4156 Success = false;
4157 }
4158 }
4159 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004160}
4161
Richard Smith254a73d2011-10-28 22:34:42 +00004162/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004163static bool HandleFunctionCall(SourceLocation CallLoc,
4164 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004165 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004166 EvalInfo &Info, APValue &Result,
4167 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004168 ArgVector ArgValues(Args.size());
4169 if (!EvaluateArgs(Args, ArgValues, Info))
4170 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004171
Richard Smith253c2a32012-01-27 01:14:48 +00004172 if (!Info.CheckCallLimit(CallLoc))
4173 return false;
4174
4175 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004176
4177 // For a trivial copy or move assignment, perform an APValue copy. This is
4178 // essential for unions, where the operations performed by the assignment
4179 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004180 //
4181 // Skip this for non-union classes with no fields; in that case, the defaulted
4182 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004183 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004184 if (MD && MD->isDefaulted() &&
4185 (MD->getParent()->isUnion() ||
4186 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004187 assert(This &&
4188 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4189 LValue RHS;
4190 RHS.setFrom(Info.Ctx, ArgValues[0]);
4191 APValue RHSValue;
4192 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4193 RHS, RHSValue))
4194 return false;
4195 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4196 RHSValue))
4197 return false;
4198 This->moveInto(Result);
4199 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004200 } else if (MD && isLambdaCallOperator(MD)) {
4201 // We're in a lambda; determine the lambda capture field maps.
4202 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4203 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004204 }
4205
Richard Smith52a980a2015-08-28 02:43:42 +00004206 StmtResult Ret = {Result, ResultSlot};
4207 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004208 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004209 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004210 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004211 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004212 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004213 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004214}
4215
Richard Smithd62306a2011-11-10 06:34:14 +00004216/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004217static bool HandleConstructorCall(const Expr *E, const LValue &This,
4218 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004219 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004220 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004221 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004222 if (!Info.CheckCallLimit(CallLoc))
4223 return false;
4224
Richard Smith3607ffe2012-02-13 03:54:03 +00004225 const CXXRecordDecl *RD = Definition->getParent();
4226 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004227 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004228 return false;
4229 }
4230
Richard Smith5179eb72016-06-28 19:03:57 +00004231 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004232
Richard Smith52a980a2015-08-28 02:43:42 +00004233 // FIXME: Creating an APValue just to hold a nonexistent return value is
4234 // wasteful.
4235 APValue RetVal;
4236 StmtResult Ret = {RetVal, nullptr};
4237
Richard Smith5179eb72016-06-28 19:03:57 +00004238 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004239 if (Definition->isDelegatingConstructor()) {
4240 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004241 {
4242 FullExpressionRAII InitScope(Info);
4243 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4244 return false;
4245 }
Richard Smith52a980a2015-08-28 02:43:42 +00004246 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004247 }
4248
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004249 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004250 // essential for unions (or classes with anonymous union members), where the
4251 // operations performed by the constructor cannot be represented by
4252 // ctor-initializers.
4253 //
4254 // Skip this for empty non-union classes; we should not perform an
4255 // lvalue-to-rvalue conversion on them because their copy constructor does not
4256 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004257 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004258 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004259 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004260 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004261 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004262 return handleLValueToRValueConversion(
4263 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4264 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004265 }
4266
4267 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004268 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004269 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004270 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004271
John McCalld7bca762012-05-01 00:38:49 +00004272 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004273 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4274
Richard Smith08d6a2c2013-07-24 07:11:57 +00004275 // A scope for temporaries lifetime-extended by reference members.
4276 BlockScopeRAII LifetimeExtendedScope(Info);
4277
Richard Smith253c2a32012-01-27 01:14:48 +00004278 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004279 unsigned BasesSeen = 0;
4280#ifndef NDEBUG
4281 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4282#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004283 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004284 LValue Subobject = This;
4285 APValue *Value = &Result;
4286
4287 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004288 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004289 if (I->isBaseInitializer()) {
4290 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004291#ifndef NDEBUG
4292 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004293 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004294 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4295 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4296 "base class initializers not in expected order");
4297 ++BaseIt;
4298#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004299 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004300 BaseType->getAsCXXRecordDecl(), &Layout))
4301 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004302 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004303 } else if ((FD = I->getMember())) {
4304 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004305 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004306 if (RD->isUnion()) {
4307 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004308 Value = &Result.getUnionValue();
4309 } else {
4310 Value = &Result.getStructField(FD->getFieldIndex());
4311 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004312 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004313 // Walk the indirect field decl's chain to find the object to initialize,
4314 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004315 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004316 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004317 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4318 // Switch the union field if it differs. This happens if we had
4319 // preceding zero-initialization, and we're now initializing a union
4320 // subobject other than the first.
4321 // FIXME: In this case, the values of the other subobjects are
4322 // specified, since zero-initialization sets all padding bits to zero.
4323 if (Value->isUninit() ||
4324 (Value->isUnion() && Value->getUnionField() != FD)) {
4325 if (CD->isUnion())
4326 *Value = APValue(FD);
4327 else
4328 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004329 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004330 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004331 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004332 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004333 if (CD->isUnion())
4334 Value = &Value->getUnionValue();
4335 else
4336 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004337 }
Richard Smithd62306a2011-11-10 06:34:14 +00004338 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004339 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004340 }
Richard Smith253c2a32012-01-27 01:14:48 +00004341
Richard Smith08d6a2c2013-07-24 07:11:57 +00004342 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004343 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4344 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004345 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004346 // If we're checking for a potential constant expression, evaluate all
4347 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004348 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004349 return false;
4350 Success = false;
4351 }
Richard Smithd62306a2011-11-10 06:34:14 +00004352 }
4353
Richard Smithd9f663b2013-04-22 15:31:51 +00004354 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004355 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004356}
4357
Richard Smith5179eb72016-06-28 19:03:57 +00004358static bool HandleConstructorCall(const Expr *E, const LValue &This,
4359 ArrayRef<const Expr*> Args,
4360 const CXXConstructorDecl *Definition,
4361 EvalInfo &Info, APValue &Result) {
4362 ArgVector ArgValues(Args.size());
4363 if (!EvaluateArgs(Args, ArgValues, Info))
4364 return false;
4365
4366 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4367 Info, Result);
4368}
4369
Eli Friedman9a156e52008-11-12 09:44:48 +00004370//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004371// Generic Evaluation
4372//===----------------------------------------------------------------------===//
4373namespace {
4374
Aaron Ballman68af21c2014-01-03 19:26:43 +00004375template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004376class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004377 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004378private:
Richard Smith52a980a2015-08-28 02:43:42 +00004379 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004380 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004381 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004382 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004383 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004384 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004385 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004386
Richard Smith17100ba2012-02-16 02:46:34 +00004387 // Check whether a conditional operator with a non-constant condition is a
4388 // potential constant expression. If neither arm is a potential constant
4389 // expression, then the conditional operator is not either.
4390 template<typename ConditionalOperator>
4391 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004392 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004393
4394 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004395 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004396 {
Richard Smith17100ba2012-02-16 02:46:34 +00004397 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004398 StmtVisitorTy::Visit(E->getFalseExpr());
4399 if (Diag.empty())
4400 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004401 }
Richard Smith17100ba2012-02-16 02:46:34 +00004402
George Burgess IV8c892b52016-05-25 22:31:54 +00004403 {
4404 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004405 Diag.clear();
4406 StmtVisitorTy::Visit(E->getTrueExpr());
4407 if (Diag.empty())
4408 return;
4409 }
4410
4411 Error(E, diag::note_constexpr_conditional_never_const);
4412 }
4413
4414
4415 template<typename ConditionalOperator>
4416 bool HandleConditionalOperator(const ConditionalOperator *E) {
4417 bool BoolResult;
4418 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004419 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004420 CheckPotentialConstantConditional(E);
4421 return false;
4422 }
4423
4424 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4425 return StmtVisitorTy::Visit(EvalExpr);
4426 }
4427
Peter Collingbournee9200682011-05-13 03:29:01 +00004428protected:
4429 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004430 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004431 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4432
Richard Smith92b1ce02011-12-12 09:28:41 +00004433 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004434 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004435 }
4436
Aaron Ballman68af21c2014-01-03 19:26:43 +00004437 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004438
4439public:
4440 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4441
4442 EvalInfo &getEvalInfo() { return Info; }
4443
Richard Smithf57d8cb2011-12-09 22:58:01 +00004444 /// Report an evaluation error. This should only be called when an error is
4445 /// first discovered. When propagating an error, just return false.
4446 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004447 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004448 return false;
4449 }
4450 bool Error(const Expr *E) {
4451 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4452 }
4453
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004455 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004456 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004457 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004458 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004459 }
4460
Aaron Ballman68af21c2014-01-03 19:26:43 +00004461 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004463 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004467 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004468 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004470 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004471 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004472 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004473 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004474 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004475 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004476 // The initializer may not have been parsed yet, or might be erroneous.
4477 if (!E->getExpr())
4478 return Error(E);
4479 return StmtVisitorTy::Visit(E->getExpr());
4480 }
Richard Smith5894a912011-12-19 22:12:41 +00004481 // We cannot create any objects for which cleanups are required, so there is
4482 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004483 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004484 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004485
Aaron Ballman68af21c2014-01-03 19:26:43 +00004486 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004487 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4488 return static_cast<Derived*>(this)->VisitCastExpr(E);
4489 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004491 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4492 return static_cast<Derived*>(this)->VisitCastExpr(E);
4493 }
4494
Aaron Ballman68af21c2014-01-03 19:26:43 +00004495 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004496 switch (E->getOpcode()) {
4497 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004498 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004499
4500 case BO_Comma:
4501 VisitIgnoredValue(E->getLHS());
4502 return StmtVisitorTy::Visit(E->getRHS());
4503
4504 case BO_PtrMemD:
4505 case BO_PtrMemI: {
4506 LValue Obj;
4507 if (!HandleMemberPointerAccess(Info, E, Obj))
4508 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004509 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004510 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004511 return false;
4512 return DerivedSuccess(Result, E);
4513 }
4514 }
4515 }
4516
Aaron Ballman68af21c2014-01-03 19:26:43 +00004517 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004518 // Evaluate and cache the common expression. We treat it as a temporary,
4519 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004520 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004521 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004522 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004523
Richard Smith17100ba2012-02-16 02:46:34 +00004524 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004525 }
4526
Aaron Ballman68af21c2014-01-03 19:26:43 +00004527 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004528 bool IsBcpCall = false;
4529 // If the condition (ignoring parens) is a __builtin_constant_p call,
4530 // the result is a constant expression if it can be folded without
4531 // side-effects. This is an important GNU extension. See GCC PR38377
4532 // for discussion.
4533 if (const CallExpr *CallCE =
4534 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004535 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004536 IsBcpCall = true;
4537
4538 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4539 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004540 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004541 return false;
4542
Richard Smith6d4c6582013-11-05 22:18:15 +00004543 FoldConstant Fold(Info, IsBcpCall);
4544 if (!HandleConditionalOperator(E)) {
4545 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004546 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004547 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004548
4549 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004550 }
4551
Aaron Ballman68af21c2014-01-03 19:26:43 +00004552 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004553 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4554 return DerivedSuccess(*Value, E);
4555
4556 const Expr *Source = E->getSourceExpr();
4557 if (!Source)
4558 return Error(E);
4559 if (Source == E) { // sanity checking.
4560 assert(0 && "OpaqueValueExpr recursively refers to itself");
4561 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004562 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004563 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004564 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004565
Aaron Ballman68af21c2014-01-03 19:26:43 +00004566 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004567 APValue Result;
4568 if (!handleCallExpr(E, Result, nullptr))
4569 return false;
4570 return DerivedSuccess(Result, E);
4571 }
4572
4573 bool handleCallExpr(const CallExpr *E, APValue &Result,
4574 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004575 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004576 QualType CalleeType = Callee->getType();
4577
Craig Topper36250ad2014-05-12 05:36:57 +00004578 const FunctionDecl *FD = nullptr;
4579 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004580 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004581 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004582
Richard Smithe97cbd72011-11-11 04:05:33 +00004583 // Extract function decl and 'this' pointer from the callee.
4584 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004585 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004586 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4587 // Explicit bound member calls, such as x.f() or p->g();
4588 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 return false;
4590 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004591 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004592 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004593 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4594 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004595 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4596 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004597 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004598 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004599 return Error(Callee);
4600
4601 FD = dyn_cast<FunctionDecl>(Member);
4602 if (!FD)
4603 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004604 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004605 LValue Call;
4606 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004607 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004608
Richard Smitha8105bc2012-01-06 16:39:00 +00004609 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004610 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004611 FD = dyn_cast_or_null<FunctionDecl>(
4612 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004613 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004614 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004615 // Don't call function pointers which have been cast to some other type.
4616 // Per DR (no number yet), the caller and callee can differ in noexcept.
4617 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4618 CalleeType->getPointeeType(), FD->getType())) {
4619 return Error(E);
4620 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004621
4622 // Overloaded operator calls to member functions are represented as normal
4623 // calls with '*this' as the first argument.
4624 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4625 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004626 // FIXME: When selecting an implicit conversion for an overloaded
4627 // operator delete, we sometimes try to evaluate calls to conversion
4628 // operators without a 'this' parameter!
4629 if (Args.empty())
4630 return Error(E);
4631
Richard Smithe97cbd72011-11-11 04:05:33 +00004632 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4633 return false;
4634 This = &ThisVal;
4635 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004636 } else if (MD && MD->isLambdaStaticInvoker()) {
4637 // Map the static invoker for the lambda back to the call operator.
4638 // Conveniently, we don't have to slice out the 'this' argument (as is
4639 // being done for the non-static case), since a static member function
4640 // doesn't have an implicit argument passed in.
4641 const CXXRecordDecl *ClosureClass = MD->getParent();
4642 assert(
4643 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4644 "Number of captures must be zero for conversion to function-ptr");
4645
4646 const CXXMethodDecl *LambdaCallOp =
4647 ClosureClass->getLambdaCallOperator();
4648
4649 // Set 'FD', the function that will be called below, to the call
4650 // operator. If the closure object represents a generic lambda, find
4651 // the corresponding specialization of the call operator.
4652
4653 if (ClosureClass->isGenericLambda()) {
4654 assert(MD->isFunctionTemplateSpecialization() &&
4655 "A generic lambda's static-invoker function must be a "
4656 "template specialization");
4657 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4658 FunctionTemplateDecl *CallOpTemplate =
4659 LambdaCallOp->getDescribedFunctionTemplate();
4660 void *InsertPos = nullptr;
4661 FunctionDecl *CorrespondingCallOpSpecialization =
4662 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4663 assert(CorrespondingCallOpSpecialization &&
4664 "We must always have a function call operator specialization "
4665 "that corresponds to our static invoker specialization");
4666 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4667 } else
4668 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004669 }
4670
Faisal Valid92e7492017-01-08 18:56:11 +00004671
Richard Smithe97cbd72011-11-11 04:05:33 +00004672 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004673 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004674
Richard Smith47b34932012-02-01 02:39:43 +00004675 if (This && !This->checkSubobject(Info, E, CSK_This))
4676 return false;
4677
Richard Smith3607ffe2012-02-13 03:54:03 +00004678 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4679 // calls to such functions in constant expressions.
4680 if (This && !HasQualifier &&
4681 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4682 return Error(E, diag::note_constexpr_virtual_call);
4683
Craig Topper36250ad2014-05-12 05:36:57 +00004684 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004685 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004686
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004687 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004688 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4689 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004690 return false;
4691
Richard Smith52a980a2015-08-28 02:43:42 +00004692 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004693 }
4694
Aaron Ballman68af21c2014-01-03 19:26:43 +00004695 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004696 return StmtVisitorTy::Visit(E->getInitializer());
4697 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004698 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004699 if (E->getNumInits() == 0)
4700 return DerivedZeroInitialization(E);
4701 if (E->getNumInits() == 1)
4702 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004703 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004704 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004705 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004706 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004707 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004708 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004709 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004710 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004711 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004712 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004713 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004714
Richard Smithd62306a2011-11-10 06:34:14 +00004715 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004716 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004717 assert(!E->isArrow() && "missing call to bound member function?");
4718
Richard Smith2e312c82012-03-03 22:46:17 +00004719 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004720 if (!Evaluate(Val, Info, E->getBase()))
4721 return false;
4722
4723 QualType BaseTy = E->getBase()->getType();
4724
4725 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004727 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004728 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004729 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4730
Richard Smith3229b742013-05-05 21:17:10 +00004731 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004732 SubobjectDesignator Designator(BaseTy);
4733 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004734
Richard Smith3229b742013-05-05 21:17:10 +00004735 APValue Result;
4736 return extractSubobject(Info, E, Obj, Designator, Result) &&
4737 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004738 }
4739
Aaron Ballman68af21c2014-01-03 19:26:43 +00004740 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004741 switch (E->getCastKind()) {
4742 default:
4743 break;
4744
Richard Smitha23ab512013-05-23 00:30:41 +00004745 case CK_AtomicToNonAtomic: {
4746 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004747 // This does not need to be done in place even for class/array types:
4748 // atomic-to-non-atomic conversion implies copying the object
4749 // representation.
4750 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004751 return false;
4752 return DerivedSuccess(AtomicVal, E);
4753 }
4754
Richard Smith11562c52011-10-28 17:51:58 +00004755 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004756 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004757 return StmtVisitorTy::Visit(E->getSubExpr());
4758
4759 case CK_LValueToRValue: {
4760 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004761 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4762 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004763 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004764 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004765 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004766 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004767 return false;
4768 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004769 }
4770 }
4771
Richard Smithf57d8cb2011-12-09 22:58:01 +00004772 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004773 }
4774
Aaron Ballman68af21c2014-01-03 19:26:43 +00004775 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004776 return VisitUnaryPostIncDec(UO);
4777 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004778 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004779 return VisitUnaryPostIncDec(UO);
4780 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004781 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004782 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004783 return Error(UO);
4784
4785 LValue LVal;
4786 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4787 return false;
4788 APValue RVal;
4789 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4790 UO->isIncrementOp(), &RVal))
4791 return false;
4792 return DerivedSuccess(RVal, UO);
4793 }
4794
Aaron Ballman68af21c2014-01-03 19:26:43 +00004795 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004796 // We will have checked the full-expressions inside the statement expression
4797 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004798 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004799 return Error(E);
4800
Richard Smith08d6a2c2013-07-24 07:11:57 +00004801 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004802 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004803 if (CS->body_empty())
4804 return true;
4805
Richard Smith51f03172013-06-20 03:00:05 +00004806 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4807 BE = CS->body_end();
4808 /**/; ++BI) {
4809 if (BI + 1 == BE) {
4810 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4811 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004812 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004813 diag::note_constexpr_stmt_expr_unsupported);
4814 return false;
4815 }
4816 return this->Visit(FinalExpr);
4817 }
4818
4819 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004820 StmtResult Result = { ReturnValue, nullptr };
4821 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004822 if (ESR != ESR_Succeeded) {
4823 // FIXME: If the statement-expression terminated due to 'return',
4824 // 'break', or 'continue', it would be nice to propagate that to
4825 // the outer statement evaluation rather than bailing out.
4826 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004827 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004828 diag::note_constexpr_stmt_expr_unsupported);
4829 return false;
4830 }
4831 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004832
4833 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004834 }
4835
Richard Smith4a678122011-10-24 18:44:57 +00004836 /// Visit a value which is evaluated, but whose value is ignored.
4837 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004838 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004839 }
David Majnemere9807b22016-02-26 04:23:19 +00004840
4841 /// Potentially visit a MemberExpr's base expression.
4842 void VisitIgnoredBaseExpression(const Expr *E) {
4843 // While MSVC doesn't evaluate the base expression, it does diagnose the
4844 // presence of side-effecting behavior.
4845 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4846 return;
4847 VisitIgnoredValue(E);
4848 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004849};
4850
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004851}
Peter Collingbournee9200682011-05-13 03:29:01 +00004852
4853//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004854// Common base class for lvalue and temporary evaluation.
4855//===----------------------------------------------------------------------===//
4856namespace {
4857template<class Derived>
4858class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004859 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004860protected:
4861 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004862 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004863 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004864 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004865
4866 bool Success(APValue::LValueBase B) {
4867 Result.set(B);
4868 return true;
4869 }
4870
George Burgess IVf9013bf2017-02-10 22:52:29 +00004871 bool evaluatePointer(const Expr *E, LValue &Result) {
4872 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4873 }
4874
Richard Smith027bf112011-11-17 22:56:20 +00004875public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004876 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4877 : ExprEvaluatorBaseTy(Info), Result(Result),
4878 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004879
Richard Smith2e312c82012-03-03 22:46:17 +00004880 bool Success(const APValue &V, const Expr *E) {
4881 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004882 return true;
4883 }
Richard Smith027bf112011-11-17 22:56:20 +00004884
Richard Smith027bf112011-11-17 22:56:20 +00004885 bool VisitMemberExpr(const MemberExpr *E) {
4886 // Handle non-static data members.
4887 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004888 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004889 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004890 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004891 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004892 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004893 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004894 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004895 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004896 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004897 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004898 BaseTy = E->getBase()->getType();
4899 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004900 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004901 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004902 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004903 Result.setInvalid(E);
4904 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004905 }
Richard Smith027bf112011-11-17 22:56:20 +00004906
Richard Smith1b78b3d2012-01-25 22:15:11 +00004907 const ValueDecl *MD = E->getMemberDecl();
4908 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4909 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4910 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4911 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004912 if (!HandleLValueMember(this->Info, E, Result, FD))
4913 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004914 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004915 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4916 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004917 } else
4918 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004919
Richard Smith1b78b3d2012-01-25 22:15:11 +00004920 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004921 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004922 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004923 RefValue))
4924 return false;
4925 return Success(RefValue, E);
4926 }
4927 return true;
4928 }
4929
4930 bool VisitBinaryOperator(const BinaryOperator *E) {
4931 switch (E->getOpcode()) {
4932 default:
4933 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4934
4935 case BO_PtrMemD:
4936 case BO_PtrMemI:
4937 return HandleMemberPointerAccess(this->Info, E, Result);
4938 }
4939 }
4940
4941 bool VisitCastExpr(const CastExpr *E) {
4942 switch (E->getCastKind()) {
4943 default:
4944 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4945
4946 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004947 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004948 if (!this->Visit(E->getSubExpr()))
4949 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004950
4951 // Now figure out the necessary offset to add to the base LV to get from
4952 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004953 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4954 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004955 }
4956 }
4957};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004958}
Richard Smith027bf112011-11-17 22:56:20 +00004959
4960//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004961// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004962//
4963// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4964// function designators (in C), decl references to void objects (in C), and
4965// temporaries (if building with -Wno-address-of-temporary).
4966//
4967// LValue evaluation produces values comprising a base expression of one of the
4968// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004969// - Declarations
4970// * VarDecl
4971// * FunctionDecl
4972// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004973// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004974// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004975// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004976// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004977// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004978// * ObjCEncodeExpr
4979// * AddrLabelExpr
4980// * BlockExpr
4981// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004982// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004983// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004984// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004985// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4986// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004987// * A MaterializeTemporaryExpr that has static storage duration, with no
4988// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004989// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004990//===----------------------------------------------------------------------===//
4991namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004992class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004993 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004994public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004995 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4996 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00004997
Richard Smith11562c52011-10-28 17:51:58 +00004998 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004999 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005000
Peter Collingbournee9200682011-05-13 03:29:01 +00005001 bool VisitDeclRefExpr(const DeclRefExpr *E);
5002 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005003 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005004 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5005 bool VisitMemberExpr(const MemberExpr *E);
5006 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5007 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005008 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005009 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005010 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5011 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005012 bool VisitUnaryReal(const UnaryOperator *E);
5013 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005014 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5015 return VisitUnaryPreIncDec(UO);
5016 }
5017 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5018 return VisitUnaryPreIncDec(UO);
5019 }
Richard Smith3229b742013-05-05 21:17:10 +00005020 bool VisitBinAssign(const BinaryOperator *BO);
5021 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005022
Peter Collingbournee9200682011-05-13 03:29:01 +00005023 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005024 switch (E->getCastKind()) {
5025 default:
Richard Smith027bf112011-11-17 22:56:20 +00005026 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005027
Eli Friedmance3e02a2011-10-11 00:13:24 +00005028 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005029 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005030 if (!Visit(E->getSubExpr()))
5031 return false;
5032 Result.Designator.setInvalid();
5033 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005034
Richard Smith027bf112011-11-17 22:56:20 +00005035 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005036 if (!Visit(E->getSubExpr()))
5037 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005038 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005039 }
5040 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005041};
5042} // end anonymous namespace
5043
Richard Smith11562c52011-10-28 17:51:58 +00005044/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005045/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005046/// * function designators in C, and
5047/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005048/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005049static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5050 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005051 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005052 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005053 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005054}
5055
Peter Collingbournee9200682011-05-13 03:29:01 +00005056bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005058 return Success(FD);
5059 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005060 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005061 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005062 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005063 return Error(E);
5064}
Richard Smith733237d2011-10-24 23:14:33 +00005065
Faisal Vali0528a312016-11-13 06:09:16 +00005066
Richard Smith11562c52011-10-28 17:51:58 +00005067bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005068
5069 // If we are within a lambda's call operator, check whether the 'VD' referred
5070 // to within 'E' actually represents a lambda-capture that maps to a
5071 // data-member/field within the closure object, and if so, evaluate to the
5072 // field or what the field refers to.
5073 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5074 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5075 if (Info.checkingPotentialConstantExpression())
5076 return false;
5077 // Start with 'Result' referring to the complete closure object...
5078 Result = *Info.CurrentCall->This;
5079 // ... then update it to refer to the field of the closure object
5080 // that represents the capture.
5081 if (!HandleLValueMember(Info, E, Result, FD))
5082 return false;
5083 // And if the field is of reference type, update 'Result' to refer to what
5084 // the field refers to.
5085 if (FD->getType()->isReferenceType()) {
5086 APValue RVal;
5087 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5088 RVal))
5089 return false;
5090 Result.setFrom(Info.Ctx, RVal);
5091 }
5092 return true;
5093 }
5094 }
Craig Topper36250ad2014-05-12 05:36:57 +00005095 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005096 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5097 // Only if a local variable was declared in the function currently being
5098 // evaluated, do we expect to be able to find its value in the current
5099 // frame. (Otherwise it was likely declared in an enclosing context and
5100 // could either have a valid evaluatable value (for e.g. a constexpr
5101 // variable) or be ill-formed (and trigger an appropriate evaluation
5102 // diagnostic)).
5103 if (Info.CurrentCall->Callee &&
5104 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5105 Frame = Info.CurrentCall;
5106 }
5107 }
Richard Smith3229b742013-05-05 21:17:10 +00005108
Richard Smithfec09922011-11-01 16:57:24 +00005109 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005110 if (Frame) {
5111 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005112 return true;
5113 }
Richard Smithce40ad62011-11-12 22:28:03 +00005114 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005115 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005116
Richard Smith3229b742013-05-05 21:17:10 +00005117 APValue *V;
5118 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005119 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005120 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005121 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005122 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005123 return false;
5124 }
Richard Smith3229b742013-05-05 21:17:10 +00005125 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005126}
5127
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005128bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5129 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005130 // Walk through the expression to find the materialized temporary itself.
5131 SmallVector<const Expr *, 2> CommaLHSs;
5132 SmallVector<SubobjectAdjustment, 2> Adjustments;
5133 const Expr *Inner = E->GetTemporaryExpr()->
5134 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005135
Richard Smith84401042013-06-03 05:03:02 +00005136 // If we passed any comma operators, evaluate their LHSs.
5137 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5138 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5139 return false;
5140
Richard Smithe6c01442013-06-05 00:46:14 +00005141 // A materialized temporary with static storage duration can appear within the
5142 // result of a constant expression evaluation, so we need to preserve its
5143 // value for use outside this evaluation.
5144 APValue *Value;
5145 if (E->getStorageDuration() == SD_Static) {
5146 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005147 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005148 Result.set(E);
5149 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005150 Value = &Info.CurrentCall->
5151 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005152 Result.set(E, Info.CurrentCall->Index);
5153 }
5154
Richard Smithea4ad5d2013-06-06 08:19:16 +00005155 QualType Type = Inner->getType();
5156
Richard Smith84401042013-06-03 05:03:02 +00005157 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005158 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5159 (E->getStorageDuration() == SD_Static &&
5160 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5161 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005162 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005163 }
Richard Smith84401042013-06-03 05:03:02 +00005164
5165 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005166 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5167 --I;
5168 switch (Adjustments[I].Kind) {
5169 case SubobjectAdjustment::DerivedToBaseAdjustment:
5170 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5171 Type, Result))
5172 return false;
5173 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5174 break;
5175
5176 case SubobjectAdjustment::FieldAdjustment:
5177 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5178 return false;
5179 Type = Adjustments[I].Field->getType();
5180 break;
5181
5182 case SubobjectAdjustment::MemberPointerAdjustment:
5183 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5184 Adjustments[I].Ptr.RHS))
5185 return false;
5186 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5187 break;
5188 }
5189 }
5190
5191 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005192}
5193
Peter Collingbournee9200682011-05-13 03:29:01 +00005194bool
5195LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005196 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5197 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005198 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5199 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005200 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005201}
5202
Richard Smith6e525142011-12-27 12:18:28 +00005203bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005204 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005205 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005206
Faisal Valie690b7a2016-07-02 22:34:24 +00005207 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005208 << E->getExprOperand()->getType()
5209 << E->getExprOperand()->getSourceRange();
5210 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005211}
5212
Francois Pichet0066db92012-04-16 04:08:35 +00005213bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5214 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005215}
Francois Pichet0066db92012-04-16 04:08:35 +00005216
Peter Collingbournee9200682011-05-13 03:29:01 +00005217bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005218 // Handle static data members.
5219 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005220 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005221 return VisitVarDecl(E, VD);
5222 }
5223
Richard Smith254a73d2011-10-28 22:34:42 +00005224 // Handle static member functions.
5225 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5226 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005227 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005228 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005229 }
5230 }
5231
Richard Smithd62306a2011-11-10 06:34:14 +00005232 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005233 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005234}
5235
Peter Collingbournee9200682011-05-13 03:29:01 +00005236bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005237 // FIXME: Deal with vectors as array subscript bases.
5238 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005239 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005240
George Burgess IVf9013bf2017-02-10 22:52:29 +00005241 if (!evaluatePointer(E->getBase(), Result))
John McCall45d55e42010-05-07 21:00:08 +00005242 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005243
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005244 APSInt Index;
5245 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005246 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005247
Richard Smithd6cc1982017-01-31 02:23:02 +00005248 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005249}
Eli Friedman9a156e52008-11-12 09:44:48 +00005250
Peter Collingbournee9200682011-05-13 03:29:01 +00005251bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005252 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005253}
5254
Richard Smith66c96992012-02-18 22:04:06 +00005255bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5256 if (!Visit(E->getSubExpr()))
5257 return false;
5258 // __real is a no-op on scalar lvalues.
5259 if (E->getSubExpr()->getType()->isAnyComplexType())
5260 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5261 return true;
5262}
5263
5264bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5265 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5266 "lvalue __imag__ on scalar?");
5267 if (!Visit(E->getSubExpr()))
5268 return false;
5269 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5270 return true;
5271}
5272
Richard Smith243ef902013-05-05 23:31:59 +00005273bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005274 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005275 return Error(UO);
5276
5277 if (!this->Visit(UO->getSubExpr()))
5278 return false;
5279
Richard Smith243ef902013-05-05 23:31:59 +00005280 return handleIncDec(
5281 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005282 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005283}
5284
5285bool LValueExprEvaluator::VisitCompoundAssignOperator(
5286 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005287 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005288 return Error(CAO);
5289
Richard Smith3229b742013-05-05 21:17:10 +00005290 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005291
5292 // The overall lvalue result is the result of evaluating the LHS.
5293 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005294 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005295 Evaluate(RHS, this->Info, CAO->getRHS());
5296 return false;
5297 }
5298
Richard Smith3229b742013-05-05 21:17:10 +00005299 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5300 return false;
5301
Richard Smith43e77732013-05-07 04:50:00 +00005302 return handleCompoundAssignment(
5303 this->Info, CAO,
5304 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5305 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005306}
5307
5308bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005309 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005310 return Error(E);
5311
Richard Smith3229b742013-05-05 21:17:10 +00005312 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005313
5314 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005315 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005316 Evaluate(NewVal, this->Info, E->getRHS());
5317 return false;
5318 }
5319
Richard Smith3229b742013-05-05 21:17:10 +00005320 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5321 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005322
5323 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005324 NewVal);
5325}
5326
Eli Friedman9a156e52008-11-12 09:44:48 +00005327//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005328// Pointer Evaluation
5329//===----------------------------------------------------------------------===//
5330
George Burgess IVe3763372016-12-22 02:50:20 +00005331/// \brief Attempts to compute the number of bytes available at the pointer
5332/// returned by a function with the alloc_size attribute. Returns true if we
5333/// were successful. Places an unsigned number into `Result`.
5334///
5335/// This expects the given CallExpr to be a call to a function with an
5336/// alloc_size attribute.
5337static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5338 const CallExpr *Call,
5339 llvm::APInt &Result) {
5340 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5341
5342 // alloc_size args are 1-indexed, 0 means not present.
5343 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5344 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5345 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5346 if (Call->getNumArgs() <= SizeArgNo)
5347 return false;
5348
5349 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5350 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5351 return false;
5352 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5353 return false;
5354 Into = Into.zextOrSelf(BitsInSizeT);
5355 return true;
5356 };
5357
5358 APSInt SizeOfElem;
5359 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5360 return false;
5361
5362 if (!AllocSize->getNumElemsParam()) {
5363 Result = std::move(SizeOfElem);
5364 return true;
5365 }
5366
5367 APSInt NumberOfElems;
5368 // Argument numbers start at 1
5369 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5370 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5371 return false;
5372
5373 bool Overflow;
5374 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5375 if (Overflow)
5376 return false;
5377
5378 Result = std::move(BytesAvailable);
5379 return true;
5380}
5381
5382/// \brief Convenience function. LVal's base must be a call to an alloc_size
5383/// function.
5384static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5385 const LValue &LVal,
5386 llvm::APInt &Result) {
5387 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5388 "Can't get the size of a non alloc_size function");
5389 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5390 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5391 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5392}
5393
5394/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5395/// a function with the alloc_size attribute. If it was possible to do so, this
5396/// function will return true, make Result's Base point to said function call,
5397/// and mark Result's Base as invalid.
5398static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5399 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005400 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005401 return false;
5402
5403 // Because we do no form of static analysis, we only support const variables.
5404 //
5405 // Additionally, we can't support parameters, nor can we support static
5406 // variables (in the latter case, use-before-assign isn't UB; in the former,
5407 // we have no clue what they'll be assigned to).
5408 const auto *VD =
5409 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5410 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5411 return false;
5412
5413 const Expr *Init = VD->getAnyInitializer();
5414 if (!Init)
5415 return false;
5416
5417 const Expr *E = Init->IgnoreParens();
5418 if (!tryUnwrapAllocSizeCall(E))
5419 return false;
5420
5421 // Store E instead of E unwrapped so that the type of the LValue's base is
5422 // what the user wanted.
5423 Result.setInvalid(E);
5424
5425 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5426 Result.addUnsizedArray(Info, Pointee);
5427 return true;
5428}
5429
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005430namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005431class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005432 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005433 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005434 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005435
Peter Collingbournee9200682011-05-13 03:29:01 +00005436 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005437 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005438 return true;
5439 }
George Burgess IVe3763372016-12-22 02:50:20 +00005440
George Burgess IVf9013bf2017-02-10 22:52:29 +00005441 bool evaluateLValue(const Expr *E, LValue &Result) {
5442 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5443 }
5444
5445 bool evaluatePointer(const Expr *E, LValue &Result) {
5446 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5447 }
5448
George Burgess IVe3763372016-12-22 02:50:20 +00005449 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005450public:
Mike Stump11289f42009-09-09 15:08:12 +00005451
George Burgess IVf9013bf2017-02-10 22:52:29 +00005452 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5453 : ExprEvaluatorBaseTy(info), Result(Result),
5454 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005455
Richard Smith2e312c82012-03-03 22:46:17 +00005456 bool Success(const APValue &V, const Expr *E) {
5457 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005458 return true;
5459 }
Richard Smithfddd3842011-12-30 21:15:51 +00005460 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005461 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5462 Result.set((Expr*)nullptr, 0, false, true, Offset);
5463 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005464 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005465
John McCall45d55e42010-05-07 21:00:08 +00005466 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005467 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005468 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005469 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005470 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005471 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005472 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005473 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005474 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005475 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005476 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005477 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005478 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005479 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005480 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005481 }
Richard Smithd62306a2011-11-10 06:34:14 +00005482 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005483 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005484 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005485 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005486 if (!Info.CurrentCall->This) {
5487 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005488 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005489 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005490 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005491 return false;
5492 }
Richard Smithd62306a2011-11-10 06:34:14 +00005493 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005494 // If we are inside a lambda's call operator, the 'this' expression refers
5495 // to the enclosing '*this' object (either by value or reference) which is
5496 // either copied into the closure object's field that represents the '*this'
5497 // or refers to '*this'.
5498 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5499 // Update 'Result' to refer to the data member/field of the closure object
5500 // that represents the '*this' capture.
5501 if (!HandleLValueMember(Info, E, Result,
5502 Info.CurrentCall->LambdaThisCaptureField))
5503 return false;
5504 // If we captured '*this' by reference, replace the field with its referent.
5505 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5506 ->isPointerType()) {
5507 APValue RVal;
5508 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5509 RVal))
5510 return false;
5511
5512 Result.setFrom(Info.Ctx, RVal);
5513 }
5514 }
Richard Smithd62306a2011-11-10 06:34:14 +00005515 return true;
5516 }
John McCallc07a0c72011-02-17 10:25:35 +00005517
Eli Friedman449fe542009-03-23 04:56:01 +00005518 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005519};
Chris Lattner05706e882008-07-11 18:11:29 +00005520} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005521
George Burgess IVf9013bf2017-02-10 22:52:29 +00005522static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5523 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005524 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005525 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005526}
5527
John McCall45d55e42010-05-07 21:00:08 +00005528bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005529 if (E->getOpcode() != BO_Add &&
5530 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005531 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005532
Chris Lattner05706e882008-07-11 18:11:29 +00005533 const Expr *PExp = E->getLHS();
5534 const Expr *IExp = E->getRHS();
5535 if (IExp->getType()->isPointerType())
5536 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005537
George Burgess IVf9013bf2017-02-10 22:52:29 +00005538 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005539 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005540 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005541
John McCall45d55e42010-05-07 21:00:08 +00005542 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005543 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005544 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005545
Richard Smith96e0c102011-11-04 02:25:55 +00005546 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005547 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005548
Ted Kremenek28831752012-08-23 20:46:57 +00005549 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005550 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005551}
Eli Friedman9a156e52008-11-12 09:44:48 +00005552
John McCall45d55e42010-05-07 21:00:08 +00005553bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005554 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005555}
Mike Stump11289f42009-09-09 15:08:12 +00005556
Peter Collingbournee9200682011-05-13 03:29:01 +00005557bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5558 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005559
Eli Friedman847a2bc2009-12-27 05:43:15 +00005560 switch (E->getCastKind()) {
5561 default:
5562 break;
5563
John McCalle3027922010-08-25 11:45:40 +00005564 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005565 case CK_CPointerToObjCPointerCast:
5566 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005567 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005568 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005569 if (!Visit(SubExpr))
5570 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005571 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5572 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5573 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005574 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005575 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005576 if (SubExpr->getType()->isVoidPointerType())
5577 CCEDiag(E, diag::note_constexpr_invalid_cast)
5578 << 3 << SubExpr->getType();
5579 else
5580 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5581 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005582 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5583 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005584 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005585
Anders Carlsson18275092010-10-31 20:41:46 +00005586 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005587 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005588 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005589 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005590 if (!Result.Base && Result.Offset.isZero())
5591 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005592
Richard Smithd62306a2011-11-10 06:34:14 +00005593 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005594 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005595 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5596 castAs<PointerType>()->getPointeeType(),
5597 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005598
Richard Smith027bf112011-11-17 22:56:20 +00005599 case CK_BaseToDerived:
5600 if (!Visit(E->getSubExpr()))
5601 return false;
5602 if (!Result.Base && Result.Offset.isZero())
5603 return true;
5604 return HandleBaseToDerivedCast(Info, E, Result);
5605
Richard Smith0b0a0b62011-10-29 20:57:55 +00005606 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005607 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005608 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005609
John McCalle3027922010-08-25 11:45:40 +00005610 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005611 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5612
Richard Smith2e312c82012-03-03 22:46:17 +00005613 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005614 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005615 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005616
John McCall45d55e42010-05-07 21:00:08 +00005617 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005618 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5619 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005620 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005621 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005622 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005623 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005624 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005625 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005626 return true;
5627 } else {
5628 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005629 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005630 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005631 }
5632 }
John McCalle3027922010-08-25 11:45:40 +00005633 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005634 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005635 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005636 return false;
5637 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005638 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005639 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005640 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005641 return false;
5642 }
Richard Smith96e0c102011-11-04 02:25:55 +00005643 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005644 if (const ConstantArrayType *CAT
5645 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5646 Result.addArray(Info, E, CAT);
5647 else
5648 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005649 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005650
John McCalle3027922010-08-25 11:45:40 +00005651 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005652 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005653
5654 case CK_LValueToRValue: {
5655 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005656 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005657 return false;
5658
5659 APValue RVal;
5660 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5661 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5662 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005663 return InvalidBaseOK &&
5664 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005665 return Success(RVal, E);
5666 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005667 }
5668
Richard Smith11562c52011-10-28 17:51:58 +00005669 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005670}
Chris Lattner05706e882008-07-11 18:11:29 +00005671
Hal Finkel0dd05d42014-10-03 17:18:37 +00005672static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5673 // C++ [expr.alignof]p3:
5674 // When alignof is applied to a reference type, the result is the
5675 // alignment of the referenced type.
5676 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5677 T = Ref->getPointeeType();
5678
5679 // __alignof is defined to return the preferred alignment.
5680 return Info.Ctx.toCharUnitsFromBits(
5681 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5682}
5683
5684static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5685 E = E->IgnoreParens();
5686
5687 // The kinds of expressions that we have special-case logic here for
5688 // should be kept up to date with the special checks for those
5689 // expressions in Sema.
5690
5691 // alignof decl is always accepted, even if it doesn't make sense: we default
5692 // to 1 in those cases.
5693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5694 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5695 /*RefAsPointee*/true);
5696
5697 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5698 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5699 /*RefAsPointee*/true);
5700
5701 return GetAlignOfType(Info, E->getType());
5702}
5703
George Burgess IVe3763372016-12-22 02:50:20 +00005704// To be clear: this happily visits unsupported builtins. Better name welcomed.
5705bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5706 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5707 return true;
5708
George Burgess IVf9013bf2017-02-10 22:52:29 +00005709 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005710 return false;
5711
5712 Result.setInvalid(E);
5713 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5714 Result.addUnsizedArray(Info, PointeeTy);
5715 return true;
5716}
5717
Peter Collingbournee9200682011-05-13 03:29:01 +00005718bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005719 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005720 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005721
Richard Smith6328cbd2016-11-16 00:57:23 +00005722 if (unsigned BuiltinOp = E->getBuiltinCallee())
5723 return VisitBuiltinCallExpr(E, BuiltinOp);
5724
George Burgess IVe3763372016-12-22 02:50:20 +00005725 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005726}
5727
5728bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5729 unsigned BuiltinOp) {
5730 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005731 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005732 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005733 case Builtin::BI__builtin_assume_aligned: {
5734 // We need to be very careful here because: if the pointer does not have the
5735 // asserted alignment, then the behavior is undefined, and undefined
5736 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005737 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005738 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005739
Hal Finkel0dd05d42014-10-03 17:18:37 +00005740 LValue OffsetResult(Result);
5741 APSInt Alignment;
5742 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5743 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005744 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005745
5746 if (E->getNumArgs() > 2) {
5747 APSInt Offset;
5748 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5749 return false;
5750
Richard Smith642a2362017-01-30 23:30:26 +00005751 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005752 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5753 }
5754
5755 // If there is a base object, then it must have the correct alignment.
5756 if (OffsetResult.Base) {
5757 CharUnits BaseAlignment;
5758 if (const ValueDecl *VD =
5759 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5760 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5761 } else {
5762 BaseAlignment =
5763 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5764 }
5765
5766 if (BaseAlignment < Align) {
5767 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005768 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005769 CCEDiag(E->getArg(0),
5770 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005771 << (unsigned)BaseAlignment.getQuantity()
5772 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005773 return false;
5774 }
5775 }
5776
5777 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005778 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005779 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005780
Richard Smith642a2362017-01-30 23:30:26 +00005781 (OffsetResult.Base
5782 ? CCEDiag(E->getArg(0),
5783 diag::note_constexpr_baa_insufficient_alignment) << 1
5784 : CCEDiag(E->getArg(0),
5785 diag::note_constexpr_baa_value_insufficient_alignment))
5786 << (int)OffsetResult.Offset.getQuantity()
5787 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005788 return false;
5789 }
5790
5791 return true;
5792 }
Richard Smithe9507952016-11-12 01:39:56 +00005793
5794 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005795 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005796 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005797 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005798 if (Info.getLangOpts().CPlusPlus11)
5799 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5800 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005801 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005802 else
5803 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5804 // Fall through.
5805 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005806 case Builtin::BI__builtin_wcschr:
5807 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005808 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005809 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005810 if (!Visit(E->getArg(0)))
5811 return false;
5812 APSInt Desired;
5813 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5814 return false;
5815 uint64_t MaxLength = uint64_t(-1);
5816 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005817 BuiltinOp != Builtin::BIwcschr &&
5818 BuiltinOp != Builtin::BI__builtin_strchr &&
5819 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005820 APSInt N;
5821 if (!EvaluateInteger(E->getArg(2), N, Info))
5822 return false;
5823 MaxLength = N.getExtValue();
5824 }
5825
Richard Smith8110c9d2016-11-29 19:45:17 +00005826 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005827
Richard Smith8110c9d2016-11-29 19:45:17 +00005828 // Figure out what value we're actually looking for (after converting to
5829 // the corresponding unsigned type if necessary).
5830 uint64_t DesiredVal;
5831 bool StopAtNull = false;
5832 switch (BuiltinOp) {
5833 case Builtin::BIstrchr:
5834 case Builtin::BI__builtin_strchr:
5835 // strchr compares directly to the passed integer, and therefore
5836 // always fails if given an int that is not a char.
5837 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5838 E->getArg(1)->getType(),
5839 Desired),
5840 Desired))
5841 return ZeroInitialization(E);
5842 StopAtNull = true;
5843 // Fall through.
5844 case Builtin::BImemchr:
5845 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005846 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005847 // memchr compares by converting both sides to unsigned char. That's also
5848 // correct for strchr if we get this far (to cope with plain char being
5849 // unsigned in the strchr case).
5850 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5851 break;
Richard Smithe9507952016-11-12 01:39:56 +00005852
Richard Smith8110c9d2016-11-29 19:45:17 +00005853 case Builtin::BIwcschr:
5854 case Builtin::BI__builtin_wcschr:
5855 StopAtNull = true;
5856 // Fall through.
5857 case Builtin::BIwmemchr:
5858 case Builtin::BI__builtin_wmemchr:
5859 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5860 DesiredVal = Desired.getZExtValue();
5861 break;
5862 }
Richard Smithe9507952016-11-12 01:39:56 +00005863
5864 for (; MaxLength; --MaxLength) {
5865 APValue Char;
5866 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5867 !Char.isInt())
5868 return false;
5869 if (Char.getInt().getZExtValue() == DesiredVal)
5870 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005871 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005872 break;
5873 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5874 return false;
5875 }
5876 // Not found: return nullptr.
5877 return ZeroInitialization(E);
5878 }
5879
Richard Smith6cbd65d2013-07-11 02:27:57 +00005880 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005881 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005882 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005883}
Chris Lattner05706e882008-07-11 18:11:29 +00005884
5885//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005886// Member Pointer Evaluation
5887//===----------------------------------------------------------------------===//
5888
5889namespace {
5890class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005891 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005892 MemberPtr &Result;
5893
5894 bool Success(const ValueDecl *D) {
5895 Result = MemberPtr(D);
5896 return true;
5897 }
5898public:
5899
5900 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5901 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5902
Richard Smith2e312c82012-03-03 22:46:17 +00005903 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005904 Result.setFrom(V);
5905 return true;
5906 }
Richard Smithfddd3842011-12-30 21:15:51 +00005907 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005908 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005909 }
5910
5911 bool VisitCastExpr(const CastExpr *E);
5912 bool VisitUnaryAddrOf(const UnaryOperator *E);
5913};
5914} // end anonymous namespace
5915
5916static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5917 EvalInfo &Info) {
5918 assert(E->isRValue() && E->getType()->isMemberPointerType());
5919 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5920}
5921
5922bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5923 switch (E->getCastKind()) {
5924 default:
5925 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5926
5927 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005928 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005929 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005930
5931 case CK_BaseToDerivedMemberPointer: {
5932 if (!Visit(E->getSubExpr()))
5933 return false;
5934 if (E->path_empty())
5935 return true;
5936 // Base-to-derived member pointer casts store the path in derived-to-base
5937 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5938 // the wrong end of the derived->base arc, so stagger the path by one class.
5939 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5940 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5941 PathI != PathE; ++PathI) {
5942 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5943 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5944 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005945 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005946 }
5947 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5948 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005949 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005950 return true;
5951 }
5952
5953 case CK_DerivedToBaseMemberPointer:
5954 if (!Visit(E->getSubExpr()))
5955 return false;
5956 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5957 PathE = E->path_end(); PathI != PathE; ++PathI) {
5958 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5959 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5960 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005961 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005962 }
5963 return true;
5964 }
5965}
5966
5967bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5968 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5969 // member can be formed.
5970 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5971}
5972
5973//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005974// Record Evaluation
5975//===----------------------------------------------------------------------===//
5976
5977namespace {
5978 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005979 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005980 const LValue &This;
5981 APValue &Result;
5982 public:
5983
5984 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5985 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5986
Richard Smith2e312c82012-03-03 22:46:17 +00005987 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005988 Result = V;
5989 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005990 }
Richard Smithb8348f52016-05-12 22:16:28 +00005991 bool ZeroInitialization(const Expr *E) {
5992 return ZeroInitialization(E, E->getType());
5993 }
5994 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005995
Richard Smith52a980a2015-08-28 02:43:42 +00005996 bool VisitCallExpr(const CallExpr *E) {
5997 return handleCallExpr(E, Result, &This);
5998 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005999 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006000 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006001 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6002 return VisitCXXConstructExpr(E, E->getType());
6003 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006004 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006005 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006006 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006007 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006008 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006009}
Richard Smithd62306a2011-11-10 06:34:14 +00006010
Richard Smithfddd3842011-12-30 21:15:51 +00006011/// Perform zero-initialization on an object of non-union class type.
6012/// C++11 [dcl.init]p5:
6013/// To zero-initialize an object or reference of type T means:
6014/// [...]
6015/// -- if T is a (possibly cv-qualified) non-union class type,
6016/// each non-static data member and each base-class subobject is
6017/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006018static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6019 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006020 const LValue &This, APValue &Result) {
6021 assert(!RD->isUnion() && "Expected non-union class type");
6022 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6023 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006024 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006025
John McCalld7bca762012-05-01 00:38:49 +00006026 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006027 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6028
6029 if (CD) {
6030 unsigned Index = 0;
6031 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006032 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006033 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6034 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006035 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6036 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006037 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006038 Result.getStructBase(Index)))
6039 return false;
6040 }
6041 }
6042
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006043 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006044 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006045 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006046 continue;
6047
6048 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006049 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006050 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006051
David Blaikie2d7c57e2012-04-30 02:36:29 +00006052 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006053 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006054 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006055 return false;
6056 }
6057
6058 return true;
6059}
6060
Richard Smithb8348f52016-05-12 22:16:28 +00006061bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6062 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006063 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006064 if (RD->isUnion()) {
6065 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6066 // object's first non-static named data member is zero-initialized
6067 RecordDecl::field_iterator I = RD->field_begin();
6068 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006069 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006070 return true;
6071 }
6072
6073 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006074 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006075 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006076 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006077 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006078 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006079 }
6080
Richard Smith5d108602012-02-17 00:44:16 +00006081 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006082 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006083 return false;
6084 }
6085
Richard Smitha8105bc2012-01-06 16:39:00 +00006086 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006087}
6088
Richard Smithe97cbd72011-11-11 04:05:33 +00006089bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6090 switch (E->getCastKind()) {
6091 default:
6092 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6093
6094 case CK_ConstructorConversion:
6095 return Visit(E->getSubExpr());
6096
6097 case CK_DerivedToBase:
6098 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006099 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006100 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006101 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006102 if (!DerivedObject.isStruct())
6103 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006104
6105 // Derived-to-base rvalue conversion: just slice off the derived part.
6106 APValue *Value = &DerivedObject;
6107 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6108 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6109 PathE = E->path_end(); PathI != PathE; ++PathI) {
6110 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6111 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6112 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6113 RD = Base;
6114 }
6115 Result = *Value;
6116 return true;
6117 }
6118 }
6119}
6120
Richard Smithd62306a2011-11-10 06:34:14 +00006121bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006122 if (E->isTransparent())
6123 return Visit(E->getInit(0));
6124
Richard Smithd62306a2011-11-10 06:34:14 +00006125 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006126 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006127 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6128
6129 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006130 const FieldDecl *Field = E->getInitializedFieldInUnion();
6131 Result = APValue(Field);
6132 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006133 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006134
6135 // If the initializer list for a union does not contain any elements, the
6136 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006137 // FIXME: The element should be initialized from an initializer list.
6138 // Is this difference ever observable for initializer lists which
6139 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006140 ImplicitValueInitExpr VIE(Field->getType());
6141 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6142
Richard Smithd62306a2011-11-10 06:34:14 +00006143 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006144 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6145 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006146
6147 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6148 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6149 isa<CXXDefaultInitExpr>(InitExpr));
6150
Richard Smithb228a862012-02-15 02:18:13 +00006151 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006152 }
6153
Richard Smith872307e2016-03-08 22:17:41 +00006154 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006155 if (Result.isUninit())
6156 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6157 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006158 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006159 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006160
6161 // Initialize base classes.
6162 if (CXXRD) {
6163 for (const auto &Base : CXXRD->bases()) {
6164 assert(ElementNo < E->getNumInits() && "missing init for base class");
6165 const Expr *Init = E->getInit(ElementNo);
6166
6167 LValue Subobject = This;
6168 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6169 return false;
6170
6171 APValue &FieldVal = Result.getStructBase(ElementNo);
6172 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006173 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006174 return false;
6175 Success = false;
6176 }
6177 ++ElementNo;
6178 }
6179 }
6180
6181 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006182 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006183 // Anonymous bit-fields are not considered members of the class for
6184 // purposes of aggregate initialization.
6185 if (Field->isUnnamedBitfield())
6186 continue;
6187
6188 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006189
Richard Smith253c2a32012-01-27 01:14:48 +00006190 bool HaveInit = ElementNo < E->getNumInits();
6191
6192 // FIXME: Diagnostics here should point to the end of the initializer
6193 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006194 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006195 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006196 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006197
6198 // Perform an implicit value-initialization for members beyond the end of
6199 // the initializer list.
6200 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006201 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006202
Richard Smith852c9db2013-04-20 22:23:05 +00006203 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6204 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6205 isa<CXXDefaultInitExpr>(Init));
6206
Richard Smith49ca8aa2013-08-06 07:09:20 +00006207 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6208 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6209 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006210 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006211 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006212 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006213 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006214 }
6215 }
6216
Richard Smith253c2a32012-01-27 01:14:48 +00006217 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006218}
6219
Richard Smithb8348f52016-05-12 22:16:28 +00006220bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6221 QualType T) {
6222 // Note that E's type is not necessarily the type of our class here; we might
6223 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006224 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006225 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6226
Richard Smithfddd3842011-12-30 21:15:51 +00006227 bool ZeroInit = E->requiresZeroInitialization();
6228 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006229 // If we've already performed zero-initialization, we're already done.
6230 if (!Result.isUninit())
6231 return true;
6232
Richard Smithda3f4fd2014-03-05 23:32:50 +00006233 // We can get here in two different ways:
6234 // 1) We're performing value-initialization, and should zero-initialize
6235 // the object, or
6236 // 2) We're performing default-initialization of an object with a trivial
6237 // constexpr default constructor, in which case we should start the
6238 // lifetimes of all the base subobjects (there can be no data member
6239 // subobjects in this case) per [basic.life]p1.
6240 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006241 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006242 }
6243
Craig Topper36250ad2014-05-12 05:36:57 +00006244 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006245 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006246
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006247 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006248 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006249
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006250 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006251 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006252 if (const MaterializeTemporaryExpr *ME
6253 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6254 return Visit(ME->GetTemporaryExpr());
6255
Richard Smithb8348f52016-05-12 22:16:28 +00006256 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006257 return false;
6258
Craig Topper5fc8fc22014-08-27 06:28:36 +00006259 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006260 return HandleConstructorCall(E, This, Args,
6261 cast<CXXConstructorDecl>(Definition), Info,
6262 Result);
6263}
6264
6265bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6266 const CXXInheritedCtorInitExpr *E) {
6267 if (!Info.CurrentCall) {
6268 assert(Info.checkingPotentialConstantExpression());
6269 return false;
6270 }
6271
6272 const CXXConstructorDecl *FD = E->getConstructor();
6273 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6274 return false;
6275
6276 const FunctionDecl *Definition = nullptr;
6277 auto Body = FD->getBody(Definition);
6278
6279 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6280 return false;
6281
6282 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006283 cast<CXXConstructorDecl>(Definition), Info,
6284 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006285}
6286
Richard Smithcc1b96d2013-06-12 22:31:48 +00006287bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6288 const CXXStdInitializerListExpr *E) {
6289 const ConstantArrayType *ArrayType =
6290 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6291
6292 LValue Array;
6293 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6294 return false;
6295
6296 // Get a pointer to the first element of the array.
6297 Array.addArray(Info, E, ArrayType);
6298
6299 // FIXME: Perform the checks on the field types in SemaInit.
6300 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6301 RecordDecl::field_iterator Field = Record->field_begin();
6302 if (Field == Record->field_end())
6303 return Error(E);
6304
6305 // Start pointer.
6306 if (!Field->getType()->isPointerType() ||
6307 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6308 ArrayType->getElementType()))
6309 return Error(E);
6310
6311 // FIXME: What if the initializer_list type has base classes, etc?
6312 Result = APValue(APValue::UninitStruct(), 0, 2);
6313 Array.moveInto(Result.getStructField(0));
6314
6315 if (++Field == Record->field_end())
6316 return Error(E);
6317
6318 if (Field->getType()->isPointerType() &&
6319 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6320 ArrayType->getElementType())) {
6321 // End pointer.
6322 if (!HandleLValueArrayAdjustment(Info, E, Array,
6323 ArrayType->getElementType(),
6324 ArrayType->getSize().getZExtValue()))
6325 return false;
6326 Array.moveInto(Result.getStructField(1));
6327 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6328 // Length.
6329 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6330 else
6331 return Error(E);
6332
6333 if (++Field != Record->field_end())
6334 return Error(E);
6335
6336 return true;
6337}
6338
Faisal Valic72a08c2017-01-09 03:02:53 +00006339bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6340 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6341 if (ClosureClass->isInvalidDecl()) return false;
6342
6343 if (Info.checkingPotentialConstantExpression()) return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00006344
6345 const size_t NumFields =
6346 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006347
6348 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6349 E->capture_init_end()) &&
6350 "The number of lambda capture initializers should equal the number of "
6351 "fields within the closure type");
6352
Faisal Vali051e3a22017-02-16 04:12:21 +00006353 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6354 // Iterate through all the lambda's closure object's fields and initialize
6355 // them.
6356 auto *CaptureInitIt = E->capture_init_begin();
6357 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6358 bool Success = true;
6359 for (const auto *Field : ClosureClass->fields()) {
6360 assert(CaptureInitIt != E->capture_init_end());
6361 // Get the initializer for this field
6362 Expr *const CurFieldInit = *CaptureInitIt++;
6363
6364 // If there is no initializer, either this is a VLA or an error has
6365 // occurred.
6366 if (!CurFieldInit)
6367 return Error(E);
6368
6369 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6370 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6371 if (!Info.keepEvaluatingAfterFailure())
6372 return false;
6373 Success = false;
6374 }
6375 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006376 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006377 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006378}
6379
Richard Smithd62306a2011-11-10 06:34:14 +00006380static bool EvaluateRecord(const Expr *E, const LValue &This,
6381 APValue &Result, EvalInfo &Info) {
6382 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006383 "can't evaluate expression as a record rvalue");
6384 return RecordExprEvaluator(Info, This, Result).Visit(E);
6385}
6386
6387//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006388// Temporary Evaluation
6389//
6390// Temporaries are represented in the AST as rvalues, but generally behave like
6391// lvalues. The full-object of which the temporary is a subobject is implicitly
6392// materialized so that a reference can bind to it.
6393//===----------------------------------------------------------------------===//
6394namespace {
6395class TemporaryExprEvaluator
6396 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6397public:
6398 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006399 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006400
6401 /// Visit an expression which constructs the value of this temporary.
6402 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006403 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006404 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6405 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006406 }
6407
6408 bool VisitCastExpr(const CastExpr *E) {
6409 switch (E->getCastKind()) {
6410 default:
6411 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6412
6413 case CK_ConstructorConversion:
6414 return VisitConstructExpr(E->getSubExpr());
6415 }
6416 }
6417 bool VisitInitListExpr(const InitListExpr *E) {
6418 return VisitConstructExpr(E);
6419 }
6420 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6421 return VisitConstructExpr(E);
6422 }
6423 bool VisitCallExpr(const CallExpr *E) {
6424 return VisitConstructExpr(E);
6425 }
Richard Smith513955c2014-12-17 19:24:30 +00006426 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6427 return VisitConstructExpr(E);
6428 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006429 bool VisitLambdaExpr(const LambdaExpr *E) {
6430 return VisitConstructExpr(E);
6431 }
Richard Smith027bf112011-11-17 22:56:20 +00006432};
6433} // end anonymous namespace
6434
6435/// Evaluate an expression of record type as a temporary.
6436static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006437 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006438 return TemporaryExprEvaluator(Info, Result).Visit(E);
6439}
6440
6441//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006442// Vector Evaluation
6443//===----------------------------------------------------------------------===//
6444
6445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006446 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006447 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006448 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006449 public:
Mike Stump11289f42009-09-09 15:08:12 +00006450
Richard Smith2d406342011-10-22 21:10:00 +00006451 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6452 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006453
Craig Topper9798b932015-09-29 04:30:05 +00006454 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006455 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6456 // FIXME: remove this APValue copy.
6457 Result = APValue(V.data(), V.size());
6458 return true;
6459 }
Richard Smith2e312c82012-03-03 22:46:17 +00006460 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006461 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006462 Result = V;
6463 return true;
6464 }
Richard Smithfddd3842011-12-30 21:15:51 +00006465 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006466
Richard Smith2d406342011-10-22 21:10:00 +00006467 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006468 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006469 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006470 bool VisitInitListExpr(const InitListExpr *E);
6471 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006472 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006473 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006474 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006475 };
6476} // end anonymous namespace
6477
6478static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006479 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006480 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006481}
6482
George Burgess IV533ff002015-12-11 00:23:35 +00006483bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006484 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006485 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006486
Richard Smith161f09a2011-12-06 22:44:34 +00006487 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006488 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006489
Eli Friedmanc757de22011-03-25 00:43:55 +00006490 switch (E->getCastKind()) {
6491 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006492 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006493 if (SETy->isIntegerType()) {
6494 APSInt IntResult;
6495 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006496 return false;
6497 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006498 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006499 APFloat FloatResult(0.0);
6500 if (!EvaluateFloat(SE, FloatResult, Info))
6501 return false;
6502 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006503 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006504 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006505 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006506
6507 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006508 SmallVector<APValue, 4> Elts(NElts, Val);
6509 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006510 }
Eli Friedman803acb32011-12-22 03:51:45 +00006511 case CK_BitCast: {
6512 // Evaluate the operand into an APInt we can extract from.
6513 llvm::APInt SValInt;
6514 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6515 return false;
6516 // Extract the elements
6517 QualType EltTy = VTy->getElementType();
6518 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6519 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6520 SmallVector<APValue, 4> Elts;
6521 if (EltTy->isRealFloatingType()) {
6522 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006523 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006524 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006525 FloatEltSize = 80;
6526 for (unsigned i = 0; i < NElts; i++) {
6527 llvm::APInt Elt;
6528 if (BigEndian)
6529 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6530 else
6531 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006532 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006533 }
6534 } else if (EltTy->isIntegerType()) {
6535 for (unsigned i = 0; i < NElts; i++) {
6536 llvm::APInt Elt;
6537 if (BigEndian)
6538 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6539 else
6540 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6541 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6542 }
6543 } else {
6544 return Error(E);
6545 }
6546 return Success(Elts, E);
6547 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006548 default:
Richard Smith11562c52011-10-28 17:51:58 +00006549 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006550 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006551}
6552
Richard Smith2d406342011-10-22 21:10:00 +00006553bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006554VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006555 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006556 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006557 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006558
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006559 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006560 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006561
Eli Friedmanb9c71292012-01-03 23:24:20 +00006562 // The number of initializers can be less than the number of
6563 // vector elements. For OpenCL, this can be due to nested vector
6564 // initialization. For GCC compatibility, missing trailing elements
6565 // should be initialized with zeroes.
6566 unsigned CountInits = 0, CountElts = 0;
6567 while (CountElts < NumElements) {
6568 // Handle nested vector initialization.
6569 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006570 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006571 APValue v;
6572 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6573 return Error(E);
6574 unsigned vlen = v.getVectorLength();
6575 for (unsigned j = 0; j < vlen; j++)
6576 Elements.push_back(v.getVectorElt(j));
6577 CountElts += vlen;
6578 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006579 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006580 if (CountInits < NumInits) {
6581 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006582 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006583 } else // trailing integer zero.
6584 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6585 Elements.push_back(APValue(sInt));
6586 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006587 } else {
6588 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006589 if (CountInits < NumInits) {
6590 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006591 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006592 } else // trailing float zero.
6593 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6594 Elements.push_back(APValue(f));
6595 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006596 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006597 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006598 }
Richard Smith2d406342011-10-22 21:10:00 +00006599 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006600}
6601
Richard Smith2d406342011-10-22 21:10:00 +00006602bool
Richard Smithfddd3842011-12-30 21:15:51 +00006603VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006604 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006605 QualType EltTy = VT->getElementType();
6606 APValue ZeroElement;
6607 if (EltTy->isIntegerType())
6608 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6609 else
6610 ZeroElement =
6611 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6612
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006613 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006614 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006615}
6616
Richard Smith2d406342011-10-22 21:10:00 +00006617bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006618 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006619 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006620}
6621
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006622//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006623// Array Evaluation
6624//===----------------------------------------------------------------------===//
6625
6626namespace {
6627 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006628 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006629 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006630 APValue &Result;
6631 public:
6632
Richard Smithd62306a2011-11-10 06:34:14 +00006633 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6634 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006635
6636 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006637 assert((V.isArray() || V.isLValue()) &&
6638 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006639 Result = V;
6640 return true;
6641 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006642
Richard Smithfddd3842011-12-30 21:15:51 +00006643 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006644 const ConstantArrayType *CAT =
6645 Info.Ctx.getAsConstantArrayType(E->getType());
6646 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006647 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006648
6649 Result = APValue(APValue::UninitArray(), 0,
6650 CAT->getSize().getZExtValue());
6651 if (!Result.hasArrayFiller()) return true;
6652
Richard Smithfddd3842011-12-30 21:15:51 +00006653 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006654 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006655 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006656 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006657 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006658 }
6659
Richard Smith52a980a2015-08-28 02:43:42 +00006660 bool VisitCallExpr(const CallExpr *E) {
6661 return handleCallExpr(E, Result, &This);
6662 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006663 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006664 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006665 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006666 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6667 const LValue &Subobject,
6668 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006669 };
6670} // end anonymous namespace
6671
Richard Smithd62306a2011-11-10 06:34:14 +00006672static bool EvaluateArray(const Expr *E, const LValue &This,
6673 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006674 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006675 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006676}
6677
6678bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6679 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6680 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006681 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006682
Richard Smithca2cfbf2011-12-22 01:07:19 +00006683 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6684 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006685 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006686 LValue LV;
6687 if (!EvaluateLValue(E->getInit(0), LV, Info))
6688 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006689 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006690 LV.moveInto(Val);
6691 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006692 }
6693
Richard Smith253c2a32012-01-27 01:14:48 +00006694 bool Success = true;
6695
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006696 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6697 "zero-initialized array shouldn't have any initialized elts");
6698 APValue Filler;
6699 if (Result.isArray() && Result.hasArrayFiller())
6700 Filler = Result.getArrayFiller();
6701
Richard Smith9543c5e2013-04-22 14:44:29 +00006702 unsigned NumEltsToInit = E->getNumInits();
6703 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006704 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006705
6706 // If the initializer might depend on the array index, run it for each
6707 // array element. For now, just whitelist non-class value-initialization.
6708 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6709 NumEltsToInit = NumElts;
6710
6711 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006712
6713 // If the array was previously zero-initialized, preserve the
6714 // zero-initialized values.
6715 if (!Filler.isUninit()) {
6716 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6717 Result.getArrayInitializedElt(I) = Filler;
6718 if (Result.hasArrayFiller())
6719 Result.getArrayFiller() = Filler;
6720 }
6721
Richard Smithd62306a2011-11-10 06:34:14 +00006722 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006723 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006724 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6725 const Expr *Init =
6726 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006727 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006728 Info, Subobject, Init) ||
6729 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006730 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006731 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006732 return false;
6733 Success = false;
6734 }
Richard Smithd62306a2011-11-10 06:34:14 +00006735 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006736
Richard Smith9543c5e2013-04-22 14:44:29 +00006737 if (!Result.hasArrayFiller())
6738 return Success;
6739
6740 // If we get here, we have a trivial filler, which we can just evaluate
6741 // once and splat over the rest of the array elements.
6742 assert(FillerExpr && "no array filler for incomplete init list");
6743 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6744 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006745}
6746
Richard Smith410306b2016-12-12 02:53:20 +00006747bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6748 if (E->getCommonExpr() &&
6749 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6750 Info, E->getCommonExpr()->getSourceExpr()))
6751 return false;
6752
6753 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6754
6755 uint64_t Elements = CAT->getSize().getZExtValue();
6756 Result = APValue(APValue::UninitArray(), Elements, Elements);
6757
6758 LValue Subobject = This;
6759 Subobject.addArray(Info, E, CAT);
6760
6761 bool Success = true;
6762 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6763 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6764 Info, Subobject, E->getSubExpr()) ||
6765 !HandleLValueArrayAdjustment(Info, E, Subobject,
6766 CAT->getElementType(), 1)) {
6767 if (!Info.noteFailure())
6768 return false;
6769 Success = false;
6770 }
6771 }
6772
6773 return Success;
6774}
6775
Richard Smith027bf112011-11-17 22:56:20 +00006776bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006777 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6778}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006779
Richard Smith9543c5e2013-04-22 14:44:29 +00006780bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6781 const LValue &Subobject,
6782 APValue *Value,
6783 QualType Type) {
6784 bool HadZeroInit = !Value->isUninit();
6785
6786 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6787 unsigned N = CAT->getSize().getZExtValue();
6788
6789 // Preserve the array filler if we had prior zero-initialization.
6790 APValue Filler =
6791 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6792 : APValue();
6793
6794 *Value = APValue(APValue::UninitArray(), N, N);
6795
6796 if (HadZeroInit)
6797 for (unsigned I = 0; I != N; ++I)
6798 Value->getArrayInitializedElt(I) = Filler;
6799
6800 // Initialize the elements.
6801 LValue ArrayElt = Subobject;
6802 ArrayElt.addArray(Info, E, CAT);
6803 for (unsigned I = 0; I != N; ++I)
6804 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6805 CAT->getElementType()) ||
6806 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6807 CAT->getElementType(), 1))
6808 return false;
6809
6810 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006811 }
Richard Smith027bf112011-11-17 22:56:20 +00006812
Richard Smith9543c5e2013-04-22 14:44:29 +00006813 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006814 return Error(E);
6815
Richard Smithb8348f52016-05-12 22:16:28 +00006816 return RecordExprEvaluator(Info, Subobject, *Value)
6817 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006818}
6819
Richard Smithf3e9e432011-11-07 09:22:26 +00006820//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006821// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006822//
6823// As a GNU extension, we support casting pointers to sufficiently-wide integer
6824// types and back in constant folding. Integer values are thus represented
6825// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006826//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006827
6828namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006829class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006830 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006831 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006832public:
Richard Smith2e312c82012-03-03 22:46:17 +00006833 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006834 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006835
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006836 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006837 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006838 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006839 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006840 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006841 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006842 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006843 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006844 return true;
6845 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006846 bool Success(const llvm::APSInt &SI, const Expr *E) {
6847 return Success(SI, E, Result);
6848 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006849
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006850 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006851 assert(E->getType()->isIntegralOrEnumerationType() &&
6852 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006853 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006854 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006855 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006856 Result.getInt().setIsUnsigned(
6857 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006858 return true;
6859 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006860 bool Success(const llvm::APInt &I, const Expr *E) {
6861 return Success(I, E, Result);
6862 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006863
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006864 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006865 assert(E->getType()->isIntegralOrEnumerationType() &&
6866 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006867 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006868 return true;
6869 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006870 bool Success(uint64_t Value, const Expr *E) {
6871 return Success(Value, E, Result);
6872 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006873
Ken Dyckdbc01912011-03-11 02:13:43 +00006874 bool Success(CharUnits Size, const Expr *E) {
6875 return Success(Size.getQuantity(), E);
6876 }
6877
Richard Smith2e312c82012-03-03 22:46:17 +00006878 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006879 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006880 Result = V;
6881 return true;
6882 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006883 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006884 }
Mike Stump11289f42009-09-09 15:08:12 +00006885
Richard Smithfddd3842011-12-30 21:15:51 +00006886 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006887
Peter Collingbournee9200682011-05-13 03:29:01 +00006888 //===--------------------------------------------------------------------===//
6889 // Visitor Methods
6890 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006891
Chris Lattner7174bf32008-07-12 00:38:25 +00006892 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006893 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006894 }
6895 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006896 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006897 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006898
6899 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6900 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006901 if (CheckReferencedDecl(E, E->getDecl()))
6902 return true;
6903
6904 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006905 }
6906 bool VisitMemberExpr(const MemberExpr *E) {
6907 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006908 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006909 return true;
6910 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006911
6912 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006913 }
6914
Peter Collingbournee9200682011-05-13 03:29:01 +00006915 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006916 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006917 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006918 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006919 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006920
Peter Collingbournee9200682011-05-13 03:29:01 +00006921 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006922 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006923
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006924 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006925 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006926 }
Mike Stump11289f42009-09-09 15:08:12 +00006927
Ted Kremeneke65b0862012-03-06 20:05:56 +00006928 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6929 return Success(E->getValue(), E);
6930 }
Richard Smith410306b2016-12-12 02:53:20 +00006931
6932 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6933 if (Info.ArrayInitIndex == uint64_t(-1)) {
6934 // We were asked to evaluate this subexpression independent of the
6935 // enclosing ArrayInitLoopExpr. We can't do that.
6936 Info.FFDiag(E);
6937 return false;
6938 }
6939 return Success(Info.ArrayInitIndex, E);
6940 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006941
Richard Smith4ce706a2011-10-11 21:43:33 +00006942 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006943 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006944 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006945 }
6946
Douglas Gregor29c42f22012-02-24 07:38:34 +00006947 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6948 return Success(E->getValue(), E);
6949 }
6950
John Wiegley6242b6a2011-04-28 00:16:57 +00006951 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6952 return Success(E->getValue(), E);
6953 }
6954
John Wiegleyf9f65842011-04-25 06:54:41 +00006955 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6956 return Success(E->getValue(), E);
6957 }
6958
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006959 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006960 bool VisitUnaryImag(const UnaryOperator *E);
6961
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006962 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006963 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006964
Eli Friedman4e7a2412009-02-27 04:45:43 +00006965 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006966};
Chris Lattner05706e882008-07-11 18:11:29 +00006967} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006968
Richard Smith11562c52011-10-28 17:51:58 +00006969/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6970/// produce either the integer value or a pointer.
6971///
6972/// GCC has a heinous extension which folds casts between pointer types and
6973/// pointer-sized integral types. We support this by allowing the evaluation of
6974/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6975/// Some simple arithmetic on such values is supported (they are treated much
6976/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006977static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006978 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006979 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006980 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006981}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006982
Richard Smithf57d8cb2011-12-09 22:58:01 +00006983static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006984 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006985 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006986 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006987 if (!Val.isInt()) {
6988 // FIXME: It would be better to produce the diagnostic for casting
6989 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006990 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006991 return false;
6992 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006993 Result = Val.getInt();
6994 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006995}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006996
Richard Smithf57d8cb2011-12-09 22:58:01 +00006997/// Check whether the given declaration can be directly converted to an integral
6998/// rvalue. If not, no diagnostic is produced; there are other things we can
6999/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007000bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007001 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007002 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007003 // Check for signedness/width mismatches between E type and ECD value.
7004 bool SameSign = (ECD->getInitVal().isSigned()
7005 == E->getType()->isSignedIntegerOrEnumerationType());
7006 bool SameWidth = (ECD->getInitVal().getBitWidth()
7007 == Info.Ctx.getIntWidth(E->getType()));
7008 if (SameSign && SameWidth)
7009 return Success(ECD->getInitVal(), E);
7010 else {
7011 // Get rid of mismatch (otherwise Success assertions will fail)
7012 // by computing a new value matching the type of E.
7013 llvm::APSInt Val = ECD->getInitVal();
7014 if (!SameSign)
7015 Val.setIsSigned(!ECD->getInitVal().isSigned());
7016 if (!SameWidth)
7017 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7018 return Success(Val, E);
7019 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007020 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007021 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007022}
7023
Chris Lattner86ee2862008-10-06 06:40:35 +00007024/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7025/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007026static int EvaluateBuiltinClassifyType(const CallExpr *E,
7027 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007028 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007029 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007030 enum gcc_type_class {
7031 no_type_class = -1,
7032 void_type_class, integer_type_class, char_type_class,
7033 enumeral_type_class, boolean_type_class,
7034 pointer_type_class, reference_type_class, offset_type_class,
7035 real_type_class, complex_type_class,
7036 function_type_class, method_type_class,
7037 record_type_class, union_type_class,
7038 array_type_class, string_type_class,
7039 lang_type_class
7040 };
Mike Stump11289f42009-09-09 15:08:12 +00007041
7042 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007043 // ideal, however it is what gcc does.
7044 if (E->getNumArgs() == 0)
7045 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007046
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007047 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7048 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7049
7050 switch (CanTy->getTypeClass()) {
7051#define TYPE(ID, BASE)
7052#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7053#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7054#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7055#include "clang/AST/TypeNodes.def"
7056 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7057
7058 case Type::Builtin:
7059 switch (BT->getKind()) {
7060#define BUILTIN_TYPE(ID, SINGLETON_ID)
7061#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7062#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7063#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7064#include "clang/AST/BuiltinTypes.def"
7065 case BuiltinType::Void:
7066 return void_type_class;
7067
7068 case BuiltinType::Bool:
7069 return boolean_type_class;
7070
7071 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7072 case BuiltinType::UChar:
7073 case BuiltinType::UShort:
7074 case BuiltinType::UInt:
7075 case BuiltinType::ULong:
7076 case BuiltinType::ULongLong:
7077 case BuiltinType::UInt128:
7078 return integer_type_class;
7079
7080 case BuiltinType::NullPtr:
7081 return pointer_type_class;
7082
7083 case BuiltinType::WChar_U:
7084 case BuiltinType::Char16:
7085 case BuiltinType::Char32:
7086 case BuiltinType::ObjCId:
7087 case BuiltinType::ObjCClass:
7088 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007089#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7090 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007091#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007092 case BuiltinType::OCLSampler:
7093 case BuiltinType::OCLEvent:
7094 case BuiltinType::OCLClkEvent:
7095 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007096 case BuiltinType::OCLReserveID:
7097 case BuiltinType::Dependent:
7098 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7099 };
7100
7101 case Type::Enum:
7102 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7103 break;
7104
7105 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007106 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007107 break;
7108
7109 case Type::MemberPointer:
7110 if (CanTy->isMemberDataPointerType())
7111 return offset_type_class;
7112 else {
7113 // We expect member pointers to be either data or function pointers,
7114 // nothing else.
7115 assert(CanTy->isMemberFunctionPointerType());
7116 return method_type_class;
7117 }
7118
7119 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007120 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007121
7122 case Type::FunctionNoProto:
7123 case Type::FunctionProto:
7124 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7125
7126 case Type::Record:
7127 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7128 switch (RT->getDecl()->getTagKind()) {
7129 case TagTypeKind::TTK_Struct:
7130 case TagTypeKind::TTK_Class:
7131 case TagTypeKind::TTK_Interface:
7132 return record_type_class;
7133
7134 case TagTypeKind::TTK_Enum:
7135 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7136
7137 case TagTypeKind::TTK_Union:
7138 return union_type_class;
7139 }
7140 }
David Blaikie83d382b2011-09-23 05:06:16 +00007141 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007142
7143 case Type::ConstantArray:
7144 case Type::VariableArray:
7145 case Type::IncompleteArray:
7146 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7147
7148 case Type::BlockPointer:
7149 case Type::LValueReference:
7150 case Type::RValueReference:
7151 case Type::Vector:
7152 case Type::ExtVector:
7153 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007154 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007155 case Type::ObjCObject:
7156 case Type::ObjCInterface:
7157 case Type::ObjCObjectPointer:
7158 case Type::Pipe:
7159 case Type::Atomic:
7160 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7161 }
7162
7163 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007164}
7165
Richard Smith5fab0c92011-12-28 19:48:30 +00007166/// EvaluateBuiltinConstantPForLValue - Determine the result of
7167/// __builtin_constant_p when applied to the given lvalue.
7168///
7169/// An lvalue is only "constant" if it is a pointer or reference to the first
7170/// character of a string literal.
7171template<typename LValue>
7172static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007173 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007174 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7175}
7176
7177/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7178/// GCC as we can manage.
7179static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7180 QualType ArgType = Arg->getType();
7181
7182 // __builtin_constant_p always has one operand. The rules which gcc follows
7183 // are not precisely documented, but are as follows:
7184 //
7185 // - If the operand is of integral, floating, complex or enumeration type,
7186 // and can be folded to a known value of that type, it returns 1.
7187 // - If the operand and can be folded to a pointer to the first character
7188 // of a string literal (or such a pointer cast to an integral type), it
7189 // returns 1.
7190 //
7191 // Otherwise, it returns 0.
7192 //
7193 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7194 // its support for this does not currently work.
7195 if (ArgType->isIntegralOrEnumerationType()) {
7196 Expr::EvalResult Result;
7197 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7198 return false;
7199
7200 APValue &V = Result.Val;
7201 if (V.getKind() == APValue::Int)
7202 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007203 if (V.getKind() == APValue::LValue)
7204 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007205 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7206 return Arg->isEvaluatable(Ctx);
7207 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7208 LValue LV;
7209 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007210 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007211 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7212 : EvaluatePointer(Arg, LV, Info)) &&
7213 !Status.HasSideEffects)
7214 return EvaluateBuiltinConstantPForLValue(LV);
7215 }
7216
7217 // Anything else isn't considered to be sufficiently constant.
7218 return false;
7219}
7220
John McCall95007602010-05-10 23:27:23 +00007221/// Retrieves the "underlying object type" of the given expression,
7222/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007223static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007224 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7225 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007226 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007227 } else if (const Expr *E = B.get<const Expr*>()) {
7228 if (isa<CompoundLiteralExpr>(E))
7229 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007230 }
7231
7232 return QualType();
7233}
7234
George Burgess IV3a03fab2015-09-04 21:28:13 +00007235/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007236/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007237/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007238/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7239///
7240/// Always returns an RValue with a pointer representation.
7241static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7242 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7243
7244 auto *NoParens = E->IgnoreParens();
7245 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007246 if (Cast == nullptr)
7247 return NoParens;
7248
7249 // We only conservatively allow a few kinds of casts, because this code is
7250 // inherently a simple solution that seeks to support the common case.
7251 auto CastKind = Cast->getCastKind();
7252 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7253 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007254 return NoParens;
7255
7256 auto *SubExpr = Cast->getSubExpr();
7257 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7258 return NoParens;
7259 return ignorePointerCastsAndParens(SubExpr);
7260}
7261
George Burgess IVa51c4072015-10-16 01:49:01 +00007262/// Checks to see if the given LValue's Designator is at the end of the LValue's
7263/// record layout. e.g.
7264/// struct { struct { int a, b; } fst, snd; } obj;
7265/// obj.fst // no
7266/// obj.snd // yes
7267/// obj.fst.a // no
7268/// obj.fst.b // no
7269/// obj.snd.a // no
7270/// obj.snd.b // yes
7271///
7272/// Please note: this function is specialized for how __builtin_object_size
7273/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007274///
7275/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007276static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7277 assert(!LVal.Designator.Invalid);
7278
George Burgess IV4168d752016-06-27 19:40:41 +00007279 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7280 const RecordDecl *Parent = FD->getParent();
7281 Invalid = Parent->isInvalidDecl();
7282 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007283 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007284 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007285 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7286 };
7287
7288 auto &Base = LVal.getLValueBase();
7289 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7290 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007291 bool Invalid;
7292 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7293 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007294 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007295 for (auto *FD : IFD->chain()) {
7296 bool Invalid;
7297 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7298 return Invalid;
7299 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007300 }
7301 }
7302
George Burgess IVe3763372016-12-22 02:50:20 +00007303 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007304 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007305 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7306 assert(isBaseAnAllocSizeCall(Base) &&
7307 "Unsized array in non-alloc_size call?");
7308 // If this is an alloc_size base, we should ignore the initial array index
7309 ++I;
7310 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7311 }
7312
7313 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7314 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007315 if (BaseType->isArrayType()) {
7316 // Because __builtin_object_size treats arrays as objects, we can ignore
7317 // the index iff this is the last array in the Designator.
7318 if (I + 1 == E)
7319 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007320 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7321 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007322 if (Index + 1 != CAT->getSize())
7323 return false;
7324 BaseType = CAT->getElementType();
7325 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007326 const auto *CT = BaseType->castAs<ComplexType>();
7327 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007328 if (Index != 1)
7329 return false;
7330 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007331 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007332 bool Invalid;
7333 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7334 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007335 BaseType = FD->getType();
7336 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007337 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007338 return false;
7339 }
7340 }
7341 return true;
7342}
7343
George Burgess IVe3763372016-12-22 02:50:20 +00007344/// Tests to see if the LValue has a user-specified designator (that isn't
7345/// necessarily valid). Note that this always returns 'true' if the LValue has
7346/// an unsized array as its first designator entry, because there's currently no
7347/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007348static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007349 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007350 return false;
7351
George Burgess IVe3763372016-12-22 02:50:20 +00007352 if (!LVal.Designator.Entries.empty())
7353 return LVal.Designator.isMostDerivedAnUnsizedArray();
7354
George Burgess IVa51c4072015-10-16 01:49:01 +00007355 if (!LVal.InvalidBase)
7356 return true;
7357
George Burgess IVe3763372016-12-22 02:50:20 +00007358 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7359 // the LValueBase.
7360 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7361 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007362}
7363
George Burgess IVe3763372016-12-22 02:50:20 +00007364/// Attempts to detect a user writing into a piece of memory that's impossible
7365/// to figure out the size of by just using types.
7366static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7367 const SubobjectDesignator &Designator = LVal.Designator;
7368 // Notes:
7369 // - Users can only write off of the end when we have an invalid base. Invalid
7370 // bases imply we don't know where the memory came from.
7371 // - We used to be a bit more aggressive here; we'd only be conservative if
7372 // the array at the end was flexible, or if it had 0 or 1 elements. This
7373 // broke some common standard library extensions (PR30346), but was
7374 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7375 // with some sort of whitelist. OTOH, it seems that GCC is always
7376 // conservative with the last element in structs (if it's an array), so our
7377 // current behavior is more compatible than a whitelisting approach would
7378 // be.
7379 return LVal.InvalidBase &&
7380 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7381 Designator.MostDerivedIsArrayElement &&
7382 isDesignatorAtObjectEnd(Ctx, LVal);
7383}
7384
7385/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7386/// Fails if the conversion would cause loss of precision.
7387static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7388 CharUnits &Result) {
7389 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7390 if (Int.ugt(CharUnitsMax))
7391 return false;
7392 Result = CharUnits::fromQuantity(Int.getZExtValue());
7393 return true;
7394}
7395
7396/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7397/// determine how many bytes exist from the beginning of the object to either
7398/// the end of the current subobject, or the end of the object itself, depending
7399/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007400///
George Burgess IVe3763372016-12-22 02:50:20 +00007401/// If this returns false, the value of Result is undefined.
7402static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7403 unsigned Type, const LValue &LVal,
7404 CharUnits &EndOffset) {
7405 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007406
George Burgess IV7fb7e362017-01-03 23:35:19 +00007407 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7408 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7409 return false;
7410 return HandleSizeof(Info, ExprLoc, Ty, Result);
7411 };
7412
George Burgess IVe3763372016-12-22 02:50:20 +00007413 // We want to evaluate the size of the entire object. This is a valid fallback
7414 // for when Type=1 and the designator is invalid, because we're asked for an
7415 // upper-bound.
7416 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7417 // Type=3 wants a lower bound, so we can't fall back to this.
7418 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007419 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007420
7421 llvm::APInt APEndOffset;
7422 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7423 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7424 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7425
7426 if (LVal.InvalidBase)
7427 return false;
7428
7429 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007430 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007431 }
7432
George Burgess IVe3763372016-12-22 02:50:20 +00007433 // We want to evaluate the size of a subobject.
7434 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007435
7436 // The following is a moderately common idiom in C:
7437 //
7438 // struct Foo { int a; char c[1]; };
7439 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7440 // strcpy(&F->c[0], Bar);
7441 //
George Burgess IVe3763372016-12-22 02:50:20 +00007442 // In order to not break too much legacy code, we need to support it.
7443 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7444 // If we can resolve this to an alloc_size call, we can hand that back,
7445 // because we know for certain how many bytes there are to write to.
7446 llvm::APInt APEndOffset;
7447 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7448 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7449 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7450
7451 // If we cannot determine the size of the initial allocation, then we can't
7452 // given an accurate upper-bound. However, we are still able to give
7453 // conservative lower-bounds for Type=3.
7454 if (Type == 1)
7455 return false;
7456 }
7457
7458 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007459 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007460 return false;
7461
George Burgess IVe3763372016-12-22 02:50:20 +00007462 // According to the GCC documentation, we want the size of the subobject
7463 // denoted by the pointer. But that's not quite right -- what we actually
7464 // want is the size of the immediately-enclosing array, if there is one.
7465 int64_t ElemsRemaining;
7466 if (Designator.MostDerivedIsArrayElement &&
7467 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7468 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7469 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7470 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7471 } else {
7472 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7473 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007474
George Burgess IVe3763372016-12-22 02:50:20 +00007475 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7476 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007477}
7478
George Burgess IVe3763372016-12-22 02:50:20 +00007479/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7480/// returns true and stores the result in @p Size.
7481///
7482/// If @p WasError is non-null, this will report whether the failure to evaluate
7483/// is to be treated as an Error in IntExprEvaluator.
7484static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7485 EvalInfo &Info, uint64_t &Size) {
7486 // Determine the denoted object.
7487 LValue LVal;
7488 {
7489 // The operand of __builtin_object_size is never evaluated for side-effects.
7490 // If there are any, but we can determine the pointed-to object anyway, then
7491 // ignore the side-effects.
7492 SpeculativeEvaluationRAII SpeculativeEval(Info);
7493 FoldOffsetRAII Fold(Info);
7494
7495 if (E->isGLValue()) {
7496 // It's possible for us to be given GLValues if we're called via
7497 // Expr::tryEvaluateObjectSize.
7498 APValue RVal;
7499 if (!EvaluateAsRValue(Info, E, RVal))
7500 return false;
7501 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007502 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7503 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007504 return false;
7505 }
7506
7507 // If we point to before the start of the object, there are no accessible
7508 // bytes.
7509 if (LVal.getLValueOffset().isNegative()) {
7510 Size = 0;
7511 return true;
7512 }
7513
7514 CharUnits EndOffset;
7515 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7516 return false;
7517
7518 // If we've fallen outside of the end offset, just pretend there's nothing to
7519 // write to/read from.
7520 if (EndOffset <= LVal.getLValueOffset())
7521 Size = 0;
7522 else
7523 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7524 return true;
John McCall95007602010-05-10 23:27:23 +00007525}
7526
Peter Collingbournee9200682011-05-13 03:29:01 +00007527bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007528 if (unsigned BuiltinOp = E->getBuiltinCallee())
7529 return VisitBuiltinCallExpr(E, BuiltinOp);
7530
7531 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7532}
7533
7534bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7535 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007536 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007537 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007538 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007539
7540 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007541 // The type was checked when we built the expression.
7542 unsigned Type =
7543 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7544 assert(Type <= 3 && "unexpected type");
7545
George Burgess IVe3763372016-12-22 02:50:20 +00007546 uint64_t Size;
7547 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7548 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007549
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007550 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007551 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007552
Richard Smith01ade172012-05-23 04:13:20 +00007553 // Expression had no side effects, but we couldn't statically determine the
7554 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007555 switch (Info.EvalMode) {
7556 case EvalInfo::EM_ConstantExpression:
7557 case EvalInfo::EM_PotentialConstantExpression:
7558 case EvalInfo::EM_ConstantFold:
7559 case EvalInfo::EM_EvaluateForOverflow:
7560 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007561 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007562 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007563 return Error(E);
7564 case EvalInfo::EM_ConstantExpressionUnevaluated:
7565 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007566 // Reduce it to a constant now.
7567 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007568 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007569
7570 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007571 }
7572
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007573 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007574 case Builtin::BI__builtin_bswap32:
7575 case Builtin::BI__builtin_bswap64: {
7576 APSInt Val;
7577 if (!EvaluateInteger(E->getArg(0), Val, Info))
7578 return false;
7579
7580 return Success(Val.byteSwap(), E);
7581 }
7582
Richard Smith8889a3d2013-06-13 06:26:32 +00007583 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007584 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007585
7586 // FIXME: BI__builtin_clrsb
7587 // FIXME: BI__builtin_clrsbl
7588 // FIXME: BI__builtin_clrsbll
7589
Richard Smith80b3c8e2013-06-13 05:04:16 +00007590 case Builtin::BI__builtin_clz:
7591 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007592 case Builtin::BI__builtin_clzll:
7593 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007594 APSInt Val;
7595 if (!EvaluateInteger(E->getArg(0), Val, Info))
7596 return false;
7597 if (!Val)
7598 return Error(E);
7599
7600 return Success(Val.countLeadingZeros(), E);
7601 }
7602
Richard Smith8889a3d2013-06-13 06:26:32 +00007603 case Builtin::BI__builtin_constant_p:
7604 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7605
Richard Smith80b3c8e2013-06-13 05:04:16 +00007606 case Builtin::BI__builtin_ctz:
7607 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007608 case Builtin::BI__builtin_ctzll:
7609 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007610 APSInt Val;
7611 if (!EvaluateInteger(E->getArg(0), Val, Info))
7612 return false;
7613 if (!Val)
7614 return Error(E);
7615
7616 return Success(Val.countTrailingZeros(), E);
7617 }
7618
Richard Smith8889a3d2013-06-13 06:26:32 +00007619 case Builtin::BI__builtin_eh_return_data_regno: {
7620 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7621 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7622 return Success(Operand, E);
7623 }
7624
7625 case Builtin::BI__builtin_expect:
7626 return Visit(E->getArg(0));
7627
7628 case Builtin::BI__builtin_ffs:
7629 case Builtin::BI__builtin_ffsl:
7630 case Builtin::BI__builtin_ffsll: {
7631 APSInt Val;
7632 if (!EvaluateInteger(E->getArg(0), Val, Info))
7633 return false;
7634
7635 unsigned N = Val.countTrailingZeros();
7636 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7637 }
7638
7639 case Builtin::BI__builtin_fpclassify: {
7640 APFloat Val(0.0);
7641 if (!EvaluateFloat(E->getArg(5), Val, Info))
7642 return false;
7643 unsigned Arg;
7644 switch (Val.getCategory()) {
7645 case APFloat::fcNaN: Arg = 0; break;
7646 case APFloat::fcInfinity: Arg = 1; break;
7647 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7648 case APFloat::fcZero: Arg = 4; break;
7649 }
7650 return Visit(E->getArg(Arg));
7651 }
7652
7653 case Builtin::BI__builtin_isinf_sign: {
7654 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007655 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007656 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7657 }
7658
Richard Smithea3019d2013-10-15 19:07:14 +00007659 case Builtin::BI__builtin_isinf: {
7660 APFloat Val(0.0);
7661 return EvaluateFloat(E->getArg(0), Val, Info) &&
7662 Success(Val.isInfinity() ? 1 : 0, E);
7663 }
7664
7665 case Builtin::BI__builtin_isfinite: {
7666 APFloat Val(0.0);
7667 return EvaluateFloat(E->getArg(0), Val, Info) &&
7668 Success(Val.isFinite() ? 1 : 0, E);
7669 }
7670
7671 case Builtin::BI__builtin_isnan: {
7672 APFloat Val(0.0);
7673 return EvaluateFloat(E->getArg(0), Val, Info) &&
7674 Success(Val.isNaN() ? 1 : 0, E);
7675 }
7676
7677 case Builtin::BI__builtin_isnormal: {
7678 APFloat Val(0.0);
7679 return EvaluateFloat(E->getArg(0), Val, Info) &&
7680 Success(Val.isNormal() ? 1 : 0, E);
7681 }
7682
Richard Smith8889a3d2013-06-13 06:26:32 +00007683 case Builtin::BI__builtin_parity:
7684 case Builtin::BI__builtin_parityl:
7685 case Builtin::BI__builtin_parityll: {
7686 APSInt Val;
7687 if (!EvaluateInteger(E->getArg(0), Val, Info))
7688 return false;
7689
7690 return Success(Val.countPopulation() % 2, E);
7691 }
7692
Richard Smith80b3c8e2013-06-13 05:04:16 +00007693 case Builtin::BI__builtin_popcount:
7694 case Builtin::BI__builtin_popcountl:
7695 case Builtin::BI__builtin_popcountll: {
7696 APSInt Val;
7697 if (!EvaluateInteger(E->getArg(0), Val, Info))
7698 return false;
7699
7700 return Success(Val.countPopulation(), E);
7701 }
7702
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007703 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007704 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007705 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007706 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007707 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007708 << /*isConstexpr*/0 << /*isConstructor*/0
7709 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007710 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007711 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007712 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007713 case Builtin::BI__builtin_strlen:
7714 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007715 // As an extension, we support __builtin_strlen() as a constant expression,
7716 // and support folding strlen() to a constant.
7717 LValue String;
7718 if (!EvaluatePointer(E->getArg(0), String, Info))
7719 return false;
7720
Richard Smith8110c9d2016-11-29 19:45:17 +00007721 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7722
Richard Smithe6c19f22013-11-15 02:10:04 +00007723 // Fast path: if it's a string literal, search the string value.
7724 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7725 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007726 // The string literal may have embedded null characters. Find the first
7727 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007728 StringRef Str = S->getBytes();
7729 int64_t Off = String.Offset.getQuantity();
7730 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007731 S->getCharByteWidth() == 1 &&
7732 // FIXME: Add fast-path for wchar_t too.
7733 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007734 Str = Str.substr(Off);
7735
7736 StringRef::size_type Pos = Str.find(0);
7737 if (Pos != StringRef::npos)
7738 Str = Str.substr(0, Pos);
7739
7740 return Success(Str.size(), E);
7741 }
7742
7743 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007744 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007745
7746 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007747 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7748 APValue Char;
7749 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7750 !Char.isInt())
7751 return false;
7752 if (!Char.getInt())
7753 return Success(Strlen, E);
7754 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7755 return false;
7756 }
7757 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007758
Richard Smithe151bab2016-11-11 23:43:35 +00007759 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007760 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007761 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007762 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007763 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007764 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007765 // A call to strlen is not a constant expression.
7766 if (Info.getLangOpts().CPlusPlus11)
7767 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7768 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007769 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007770 else
7771 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7772 // Fall through.
7773 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007774 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007775 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007776 case Builtin::BI__builtin_wcsncmp:
7777 case Builtin::BI__builtin_memcmp:
7778 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007779 LValue String1, String2;
7780 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7781 !EvaluatePointer(E->getArg(1), String2, Info))
7782 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007783
7784 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7785
Richard Smithe151bab2016-11-11 23:43:35 +00007786 uint64_t MaxLength = uint64_t(-1);
7787 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007788 BuiltinOp != Builtin::BIwcscmp &&
7789 BuiltinOp != Builtin::BI__builtin_strcmp &&
7790 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007791 APSInt N;
7792 if (!EvaluateInteger(E->getArg(2), N, Info))
7793 return false;
7794 MaxLength = N.getExtValue();
7795 }
7796 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007797 BuiltinOp != Builtin::BIwmemcmp &&
7798 BuiltinOp != Builtin::BI__builtin_memcmp &&
7799 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007800 for (; MaxLength; --MaxLength) {
7801 APValue Char1, Char2;
7802 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7803 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7804 !Char1.isInt() || !Char2.isInt())
7805 return false;
7806 if (Char1.getInt() != Char2.getInt())
7807 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7808 if (StopAtNull && !Char1.getInt())
7809 return Success(0, E);
7810 assert(!(StopAtNull && !Char2.getInt()));
7811 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7812 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7813 return false;
7814 }
7815 // We hit the strncmp / memcmp limit.
7816 return Success(0, E);
7817 }
7818
Richard Smith01ba47d2012-04-13 00:45:38 +00007819 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007820 case Builtin::BI__atomic_is_lock_free:
7821 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007822 APSInt SizeVal;
7823 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7824 return false;
7825
7826 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7827 // of two less than the maximum inline atomic width, we know it is
7828 // lock-free. If the size isn't a power of two, or greater than the
7829 // maximum alignment where we promote atomics, we know it is not lock-free
7830 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7831 // the answer can only be determined at runtime; for example, 16-byte
7832 // atomics have lock-free implementations on some, but not all,
7833 // x86-64 processors.
7834
7835 // Check power-of-two.
7836 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007837 if (Size.isPowerOfTwo()) {
7838 // Check against inlining width.
7839 unsigned InlineWidthBits =
7840 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7841 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7842 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7843 Size == CharUnits::One() ||
7844 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7845 Expr::NPC_NeverValueDependent))
7846 // OK, we will inline appropriately-aligned operations of this size,
7847 // and _Atomic(T) is appropriately-aligned.
7848 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007849
Richard Smith01ba47d2012-04-13 00:45:38 +00007850 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7851 castAs<PointerType>()->getPointeeType();
7852 if (!PointeeType->isIncompleteType() &&
7853 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7854 // OK, we will inline operations on this object.
7855 return Success(1, E);
7856 }
7857 }
7858 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007859
Richard Smith01ba47d2012-04-13 00:45:38 +00007860 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7861 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007862 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007863 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007864}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007865
Richard Smith8b3497e2011-10-31 01:37:14 +00007866static bool HasSameBase(const LValue &A, const LValue &B) {
7867 if (!A.getLValueBase())
7868 return !B.getLValueBase();
7869 if (!B.getLValueBase())
7870 return false;
7871
Richard Smithce40ad62011-11-12 22:28:03 +00007872 if (A.getLValueBase().getOpaqueValue() !=
7873 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007874 const Decl *ADecl = GetLValueBaseDecl(A);
7875 if (!ADecl)
7876 return false;
7877 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007878 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007879 return false;
7880 }
7881
7882 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007883 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007884}
7885
Richard Smithd20f1e62014-10-21 23:01:04 +00007886/// \brief Determine whether this is a pointer past the end of the complete
7887/// object referred to by the lvalue.
7888static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7889 const LValue &LV) {
7890 // A null pointer can be viewed as being "past the end" but we don't
7891 // choose to look at it that way here.
7892 if (!LV.getLValueBase())
7893 return false;
7894
7895 // If the designator is valid and refers to a subobject, we're not pointing
7896 // past the end.
7897 if (!LV.getLValueDesignator().Invalid &&
7898 !LV.getLValueDesignator().isOnePastTheEnd())
7899 return false;
7900
David Majnemerc378ca52015-08-29 08:32:55 +00007901 // A pointer to an incomplete type might be past-the-end if the type's size is
7902 // zero. We cannot tell because the type is incomplete.
7903 QualType Ty = getType(LV.getLValueBase());
7904 if (Ty->isIncompleteType())
7905 return true;
7906
Richard Smithd20f1e62014-10-21 23:01:04 +00007907 // We're a past-the-end pointer if we point to the byte after the object,
7908 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007909 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007910 return LV.getLValueOffset() == Size;
7911}
7912
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007913namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007914
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007915/// \brief Data recursive integer evaluator of certain binary operators.
7916///
7917/// We use a data recursive algorithm for binary operators so that we are able
7918/// to handle extreme cases of chained binary operators without causing stack
7919/// overflow.
7920class DataRecursiveIntBinOpEvaluator {
7921 struct EvalResult {
7922 APValue Val;
7923 bool Failed;
7924
7925 EvalResult() : Failed(false) { }
7926
7927 void swap(EvalResult &RHS) {
7928 Val.swap(RHS.Val);
7929 Failed = RHS.Failed;
7930 RHS.Failed = false;
7931 }
7932 };
7933
7934 struct Job {
7935 const Expr *E;
7936 EvalResult LHSResult; // meaningful only for binary operator expression.
7937 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007938
David Blaikie73726062015-08-12 23:09:24 +00007939 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007940 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007941
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007942 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007943 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007944 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007945
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007946 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007947 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007948 };
7949
7950 SmallVector<Job, 16> Queue;
7951
7952 IntExprEvaluator &IntEval;
7953 EvalInfo &Info;
7954 APValue &FinalResult;
7955
7956public:
7957 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7958 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7959
7960 /// \brief True if \param E is a binary operator that we are going to handle
7961 /// data recursively.
7962 /// We handle binary operators that are comma, logical, or that have operands
7963 /// with integral or enumeration type.
7964 static bool shouldEnqueue(const BinaryOperator *E) {
7965 return E->getOpcode() == BO_Comma ||
7966 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007967 (E->isRValue() &&
7968 E->getType()->isIntegralOrEnumerationType() &&
7969 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007970 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007971 }
7972
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007973 bool Traverse(const BinaryOperator *E) {
7974 enqueue(E);
7975 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007976 while (!Queue.empty())
7977 process(PrevResult);
7978
7979 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007980
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007981 FinalResult.swap(PrevResult.Val);
7982 return true;
7983 }
7984
7985private:
7986 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7987 return IntEval.Success(Value, E, Result);
7988 }
7989 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7990 return IntEval.Success(Value, E, Result);
7991 }
7992 bool Error(const Expr *E) {
7993 return IntEval.Error(E);
7994 }
7995 bool Error(const Expr *E, diag::kind D) {
7996 return IntEval.Error(E, D);
7997 }
7998
7999 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8000 return Info.CCEDiag(E, D);
8001 }
8002
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008003 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8004 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008005 bool &SuppressRHSDiags);
8006
8007 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8008 const BinaryOperator *E, APValue &Result);
8009
8010 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8011 Result.Failed = !Evaluate(Result.Val, Info, E);
8012 if (Result.Failed)
8013 Result.Val = APValue();
8014 }
8015
Richard Trieuba4d0872012-03-21 23:30:30 +00008016 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008017
8018 void enqueue(const Expr *E) {
8019 E = E->IgnoreParens();
8020 Queue.resize(Queue.size()+1);
8021 Queue.back().E = E;
8022 Queue.back().Kind = Job::AnyExprKind;
8023 }
8024};
8025
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008026}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008027
8028bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008029 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008030 bool &SuppressRHSDiags) {
8031 if (E->getOpcode() == BO_Comma) {
8032 // Ignore LHS but note if we could not evaluate it.
8033 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008034 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008035 return true;
8036 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008037
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008038 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008039 bool LHSAsBool;
8040 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008041 // We were able to evaluate the LHS, see if we can get away with not
8042 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008043 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8044 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008045 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008046 }
8047 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008048 LHSResult.Failed = true;
8049
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008050 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008051 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008052 if (!Info.noteSideEffect())
8053 return false;
8054
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008055 // We can't evaluate the LHS; however, sometimes the result
8056 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8057 // Don't ignore RHS and suppress diagnostics from this arm.
8058 SuppressRHSDiags = true;
8059 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008060
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008061 return true;
8062 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008063
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008064 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8065 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008066
George Burgess IVa145e252016-05-25 22:38:36 +00008067 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008068 return false; // Ignore RHS;
8069
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008070 return true;
8071}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008072
Richard Smithd6cc1982017-01-31 02:23:02 +00008073static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) {
8074 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8075 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8076 // offsets.
8077 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8078 CharUnits &Offset = LVal.getLValueOffset();
8079 uint64_t Offset64 = Offset.getQuantity();
8080 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8081 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8082 : Offset64 + Index64);
8083}
8084
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008085bool DataRecursiveIntBinOpEvaluator::
8086 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8087 const BinaryOperator *E, APValue &Result) {
8088 if (E->getOpcode() == BO_Comma) {
8089 if (RHSResult.Failed)
8090 return false;
8091 Result = RHSResult.Val;
8092 return true;
8093 }
8094
8095 if (E->isLogicalOp()) {
8096 bool lhsResult, rhsResult;
8097 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8098 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8099
8100 if (LHSIsOK) {
8101 if (RHSIsOK) {
8102 if (E->getOpcode() == BO_LOr)
8103 return Success(lhsResult || rhsResult, E, Result);
8104 else
8105 return Success(lhsResult && rhsResult, E, Result);
8106 }
8107 } else {
8108 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008109 // We can't evaluate the LHS; however, sometimes the result
8110 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8111 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008112 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008113 }
8114 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008115
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008116 return false;
8117 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008118
8119 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8120 E->getRHS()->getType()->isIntegralOrEnumerationType());
8121
8122 if (LHSResult.Failed || RHSResult.Failed)
8123 return false;
8124
8125 const APValue &LHSVal = LHSResult.Val;
8126 const APValue &RHSVal = RHSResult.Val;
8127
8128 // Handle cases like (unsigned long)&a + 4.
8129 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8130 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008131 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008132 return true;
8133 }
8134
8135 // Handle cases like 4 + (unsigned long)&a
8136 if (E->getOpcode() == BO_Add &&
8137 RHSVal.isLValue() && LHSVal.isInt()) {
8138 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008139 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008140 return true;
8141 }
8142
8143 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8144 // Handle (intptr_t)&&A - (intptr_t)&&B.
8145 if (!LHSVal.getLValueOffset().isZero() ||
8146 !RHSVal.getLValueOffset().isZero())
8147 return false;
8148 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8149 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8150 if (!LHSExpr || !RHSExpr)
8151 return false;
8152 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8153 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8154 if (!LHSAddrExpr || !RHSAddrExpr)
8155 return false;
8156 // Make sure both labels come from the same function.
8157 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8158 RHSAddrExpr->getLabel()->getDeclContext())
8159 return false;
8160 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8161 return true;
8162 }
Richard Smith43e77732013-05-07 04:50:00 +00008163
8164 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008165 if (!LHSVal.isInt() || !RHSVal.isInt())
8166 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008167
8168 // Set up the width and signedness manually, in case it can't be deduced
8169 // from the operation we're performing.
8170 // FIXME: Don't do this in the cases where we can deduce it.
8171 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8172 E->getType()->isUnsignedIntegerOrEnumerationType());
8173 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8174 RHSVal.getInt(), Value))
8175 return false;
8176 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008177}
8178
Richard Trieuba4d0872012-03-21 23:30:30 +00008179void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008180 Job &job = Queue.back();
8181
8182 switch (job.Kind) {
8183 case Job::AnyExprKind: {
8184 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8185 if (shouldEnqueue(Bop)) {
8186 job.Kind = Job::BinOpKind;
8187 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008188 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008189 }
8190 }
8191
8192 EvaluateExpr(job.E, Result);
8193 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008194 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008195 }
8196
8197 case Job::BinOpKind: {
8198 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008199 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008200 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008201 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008202 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008203 }
8204 if (SuppressRHSDiags)
8205 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008206 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008207 job.Kind = Job::BinOpVisitedLHSKind;
8208 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008209 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 }
8211
8212 case Job::BinOpVisitedLHSKind: {
8213 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8214 EvalResult RHS;
8215 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008216 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008217 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008218 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008219 }
8220 }
8221
8222 llvm_unreachable("Invalid Job::Kind!");
8223}
8224
George Burgess IV8c892b52016-05-25 22:31:54 +00008225namespace {
8226/// Used when we determine that we should fail, but can keep evaluating prior to
8227/// noting that we had a failure.
8228class DelayedNoteFailureRAII {
8229 EvalInfo &Info;
8230 bool NoteFailure;
8231
8232public:
8233 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8234 : Info(Info), NoteFailure(NoteFailure) {}
8235 ~DelayedNoteFailureRAII() {
8236 if (NoteFailure) {
8237 bool ContinueAfterFailure = Info.noteFailure();
8238 (void)ContinueAfterFailure;
8239 assert(ContinueAfterFailure &&
8240 "Shouldn't have kept evaluating on failure.");
8241 }
8242 }
8243};
8244}
8245
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008247 // We don't call noteFailure immediately because the assignment happens after
8248 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008249 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008250 return Error(E);
8251
George Burgess IV8c892b52016-05-25 22:31:54 +00008252 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8254 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008255
Anders Carlssonacc79812008-11-16 07:17:21 +00008256 QualType LHSTy = E->getLHS()->getType();
8257 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008258
Chandler Carruthb29a7432014-10-11 11:03:30 +00008259 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008260 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008261 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008262 if (E->isAssignmentOp()) {
8263 LValue LV;
8264 EvaluateLValue(E->getLHS(), LV, Info);
8265 LHSOK = false;
8266 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008267 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8268 if (LHSOK) {
8269 LHS.makeComplexFloat();
8270 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8271 }
8272 } else {
8273 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8274 }
George Burgess IVa145e252016-05-25 22:38:36 +00008275 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008276 return false;
8277
Chandler Carruthb29a7432014-10-11 11:03:30 +00008278 if (E->getRHS()->getType()->isRealFloatingType()) {
8279 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8280 return false;
8281 RHS.makeComplexFloat();
8282 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8283 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008284 return false;
8285
8286 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008287 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008288 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008289 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008290 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8291
John McCalle3027922010-08-25 11:45:40 +00008292 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008293 return Success((CR_r == APFloat::cmpEqual &&
8294 CR_i == APFloat::cmpEqual), E);
8295 else {
John McCalle3027922010-08-25 11:45:40 +00008296 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008297 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008298 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008299 CR_r == APFloat::cmpLessThan ||
8300 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008301 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008302 CR_i == APFloat::cmpLessThan ||
8303 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008304 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008305 } else {
John McCalle3027922010-08-25 11:45:40 +00008306 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008307 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8308 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8309 else {
John McCalle3027922010-08-25 11:45:40 +00008310 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008311 "Invalid compex comparison.");
8312 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8313 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8314 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008315 }
8316 }
Mike Stump11289f42009-09-09 15:08:12 +00008317
Anders Carlssonacc79812008-11-16 07:17:21 +00008318 if (LHSTy->isRealFloatingType() &&
8319 RHSTy->isRealFloatingType()) {
8320 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008321
Richard Smith253c2a32012-01-27 01:14:48 +00008322 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008323 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008324 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008325
Richard Smith253c2a32012-01-27 01:14:48 +00008326 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008327 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008328
Anders Carlssonacc79812008-11-16 07:17:21 +00008329 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008330
Anders Carlssonacc79812008-11-16 07:17:21 +00008331 switch (E->getOpcode()) {
8332 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008333 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008334 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008335 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008336 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008337 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008338 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008339 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008341 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008342 E);
John McCalle3027922010-08-25 11:45:40 +00008343 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008344 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008345 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008346 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008347 || CR == APFloat::cmpLessThan
8348 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008349 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008350 }
Mike Stump11289f42009-09-09 15:08:12 +00008351
Eli Friedmana38da572009-04-28 19:17:36 +00008352 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008353 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008354 LValue LHSValue, RHSValue;
8355
8356 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008357 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008358 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008359
Richard Smith253c2a32012-01-27 01:14:48 +00008360 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008361 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008362
Richard Smith8b3497e2011-10-31 01:37:14 +00008363 // Reject differing bases from the normal codepath; we special-case
8364 // comparisons to null.
8365 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008366 if (E->getOpcode() == BO_Sub) {
8367 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008368 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008369 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008370 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008371 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008372 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008373 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008374 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8375 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8376 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008377 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008378 // Make sure both labels come from the same function.
8379 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8380 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008381 return Error(E);
8382 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008383 }
Richard Smith83c68212011-10-31 05:11:32 +00008384 // Inequalities and subtractions between unrelated pointers have
8385 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008386 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008387 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008388 // A constant address may compare equal to the address of a symbol.
8389 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008390 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008391 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8392 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008393 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008394 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008395 // distinct addresses. In clang, the result of such a comparison is
8396 // unspecified, so it is not a constant expression. However, we do know
8397 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008398 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8399 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008400 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008401 // We can't tell whether weak symbols will end up pointing to the same
8402 // object.
8403 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008404 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008405 // We can't compare the address of the start of one object with the
8406 // past-the-end address of another object, per C++ DR1652.
8407 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8408 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8409 (RHSValue.Base && RHSValue.Offset.isZero() &&
8410 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8411 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008412 // We can't tell whether an object is at the same address as another
8413 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008414 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8415 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008416 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008417 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008418 // (Note that clang defaults to -fmerge-all-constants, which can
8419 // lead to inconsistent results for comparisons involving the address
8420 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008421 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008422 }
Eli Friedman64004332009-03-23 04:38:34 +00008423
Richard Smith1b470412012-02-01 08:10:20 +00008424 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8425 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8426
Richard Smith84f6dcf2012-02-02 01:16:57 +00008427 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8428 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8429
John McCalle3027922010-08-25 11:45:40 +00008430 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008431 // C++11 [expr.add]p6:
8432 // Unless both pointers point to elements of the same array object, or
8433 // one past the last element of the array object, the behavior is
8434 // undefined.
8435 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8436 !AreElementsOfSameArray(getType(LHSValue.Base),
8437 LHSDesignator, RHSDesignator))
8438 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8439
Chris Lattner882bdf22010-04-20 17:13:14 +00008440 QualType Type = E->getLHS()->getType();
8441 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008442
Richard Smithd62306a2011-11-10 06:34:14 +00008443 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008444 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008445 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008446
Richard Smith84c6b3d2013-09-10 21:34:14 +00008447 // As an extension, a type may have zero size (empty struct or union in
8448 // C, array of zero length). Pointer subtraction in such cases has
8449 // undefined behavior, so is not constant.
8450 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008451 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008452 << ElementType;
8453 return false;
8454 }
8455
Richard Smith1b470412012-02-01 08:10:20 +00008456 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8457 // and produce incorrect results when it overflows. Such behavior
8458 // appears to be non-conforming, but is common, so perhaps we should
8459 // assume the standard intended for such cases to be undefined behavior
8460 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008461
Richard Smith1b470412012-02-01 08:10:20 +00008462 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8463 // overflow in the final conversion to ptrdiff_t.
8464 APSInt LHS(
8465 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8466 APSInt RHS(
8467 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8468 APSInt ElemSize(
8469 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8470 APSInt TrueResult = (LHS - RHS) / ElemSize;
8471 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8472
Richard Smith0c6124b2015-12-03 01:36:22 +00008473 if (Result.extend(65) != TrueResult &&
8474 !HandleOverflow(Info, E, TrueResult, E->getType()))
8475 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008476 return Success(Result, E);
8477 }
Richard Smithde21b242012-01-31 06:41:30 +00008478
8479 // C++11 [expr.rel]p3:
8480 // Pointers to void (after pointer conversions) can be compared, with a
8481 // result defined as follows: If both pointers represent the same
8482 // address or are both the null pointer value, the result is true if the
8483 // operator is <= or >= and false otherwise; otherwise the result is
8484 // unspecified.
8485 // We interpret this as applying to pointers to *cv* void.
8486 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008487 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008488 CCEDiag(E, diag::note_constexpr_void_comparison);
8489
Richard Smith84f6dcf2012-02-02 01:16:57 +00008490 // C++11 [expr.rel]p2:
8491 // - If two pointers point to non-static data members of the same object,
8492 // or to subobjects or array elements fo such members, recursively, the
8493 // pointer to the later declared member compares greater provided the
8494 // two members have the same access control and provided their class is
8495 // not a union.
8496 // [...]
8497 // - Otherwise pointer comparisons are unspecified.
8498 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8499 E->isRelationalOp()) {
8500 bool WasArrayIndex;
8501 unsigned Mismatch =
8502 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8503 RHSDesignator, WasArrayIndex);
8504 // At the point where the designators diverge, the comparison has a
8505 // specified value if:
8506 // - we are comparing array indices
8507 // - we are comparing fields of a union, or fields with the same access
8508 // Otherwise, the result is unspecified and thus the comparison is not a
8509 // constant expression.
8510 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8511 Mismatch < RHSDesignator.Entries.size()) {
8512 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8513 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8514 if (!LF && !RF)
8515 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8516 else if (!LF)
8517 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8518 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8519 << RF->getParent() << RF;
8520 else if (!RF)
8521 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8522 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8523 << LF->getParent() << LF;
8524 else if (!LF->getParent()->isUnion() &&
8525 LF->getAccess() != RF->getAccess())
8526 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8527 << LF << LF->getAccess() << RF << RF->getAccess()
8528 << LF->getParent();
8529 }
8530 }
8531
Eli Friedman6c31cb42012-04-16 04:30:08 +00008532 // The comparison here must be unsigned, and performed with the same
8533 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008534 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8535 uint64_t CompareLHS = LHSOffset.getQuantity();
8536 uint64_t CompareRHS = RHSOffset.getQuantity();
8537 assert(PtrSize <= 64 && "Unexpected pointer width");
8538 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8539 CompareLHS &= Mask;
8540 CompareRHS &= Mask;
8541
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008542 // If there is a base and this is a relational operator, we can only
8543 // compare pointers within the object in question; otherwise, the result
8544 // depends on where the object is located in memory.
8545 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8546 QualType BaseTy = getType(LHSValue.Base);
8547 if (BaseTy->isIncompleteType())
8548 return Error(E);
8549 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8550 uint64_t OffsetLimit = Size.getQuantity();
8551 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8552 return Error(E);
8553 }
8554
Richard Smith8b3497e2011-10-31 01:37:14 +00008555 switch (E->getOpcode()) {
8556 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008557 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8558 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8559 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8560 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8561 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8562 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008563 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008564 }
8565 }
Richard Smith7bb00672012-02-01 01:42:44 +00008566
8567 if (LHSTy->isMemberPointerType()) {
8568 assert(E->isEqualityOp() && "unexpected member pointer operation");
8569 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8570
8571 MemberPtr LHSValue, RHSValue;
8572
8573 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008574 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008575 return false;
8576
8577 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8578 return false;
8579
8580 // C++11 [expr.eq]p2:
8581 // If both operands are null, they compare equal. Otherwise if only one is
8582 // null, they compare unequal.
8583 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8584 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8585 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8586 }
8587
8588 // Otherwise if either is a pointer to a virtual member function, the
8589 // result is unspecified.
8590 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8591 if (MD->isVirtual())
8592 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8594 if (MD->isVirtual())
8595 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8596
8597 // Otherwise they compare equal if and only if they would refer to the
8598 // same member of the same most derived object or the same subobject if
8599 // they were dereferenced with a hypothetical object of the associated
8600 // class type.
8601 bool Equal = LHSValue == RHSValue;
8602 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8603 }
8604
Richard Smithab44d9b2012-02-14 22:35:28 +00008605 if (LHSTy->isNullPtrType()) {
8606 assert(E->isComparisonOp() && "unexpected nullptr operation");
8607 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8608 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8609 // are compared, the result is true of the operator is <=, >= or ==, and
8610 // false otherwise.
8611 BinaryOperator::Opcode Opcode = E->getOpcode();
8612 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8613 }
8614
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008615 assert((!LHSTy->isIntegralOrEnumerationType() ||
8616 !RHSTy->isIntegralOrEnumerationType()) &&
8617 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8618 // We can't continue from here for non-integral types.
8619 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008620}
8621
Peter Collingbournee190dee2011-03-11 19:24:49 +00008622/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8623/// a result as the expression's type.
8624bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8625 const UnaryExprOrTypeTraitExpr *E) {
8626 switch(E->getKind()) {
8627 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008628 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008629 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008630 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008631 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008632 }
Eli Friedman64004332009-03-23 04:38:34 +00008633
Peter Collingbournee190dee2011-03-11 19:24:49 +00008634 case UETT_VecStep: {
8635 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008636
Peter Collingbournee190dee2011-03-11 19:24:49 +00008637 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008638 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008639
Peter Collingbournee190dee2011-03-11 19:24:49 +00008640 // The vec_step built-in functions that take a 3-component
8641 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8642 if (n == 3)
8643 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008644
Peter Collingbournee190dee2011-03-11 19:24:49 +00008645 return Success(n, E);
8646 } else
8647 return Success(1, E);
8648 }
8649
8650 case UETT_SizeOf: {
8651 QualType SrcTy = E->getTypeOfArgument();
8652 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8653 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008654 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8655 SrcTy = Ref->getPointeeType();
8656
Richard Smithd62306a2011-11-10 06:34:14 +00008657 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008658 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008659 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008660 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008661 }
Alexey Bataev00396512015-07-02 03:40:19 +00008662 case UETT_OpenMPRequiredSimdAlign:
8663 assert(E->isArgumentType());
8664 return Success(
8665 Info.Ctx.toCharUnitsFromBits(
8666 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8667 .getQuantity(),
8668 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008669 }
8670
8671 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008672}
8673
Peter Collingbournee9200682011-05-13 03:29:01 +00008674bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008675 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008676 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008677 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008678 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008679 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008680 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008681 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008682 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008683 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008684 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008685 APSInt IdxResult;
8686 if (!EvaluateInteger(Idx, IdxResult, Info))
8687 return false;
8688 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8689 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008690 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008691 CurrentType = AT->getElementType();
8692 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8693 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008694 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008695 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008696
James Y Knight7281c352015-12-29 22:31:18 +00008697 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008698 FieldDecl *MemberDecl = ON.getField();
8699 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008700 if (!RT)
8701 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008702 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008703 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008704 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008705 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008706 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008707 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008708 CurrentType = MemberDecl->getType().getNonReferenceType();
8709 break;
8710 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008711
James Y Knight7281c352015-12-29 22:31:18 +00008712 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008713 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008714
James Y Knight7281c352015-12-29 22:31:18 +00008715 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008716 CXXBaseSpecifier *BaseSpec = ON.getBase();
8717 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008718 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008719
8720 // Find the layout of the class whose base we are looking into.
8721 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008722 if (!RT)
8723 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008724 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008725 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008726 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8727
8728 // Find the base class itself.
8729 CurrentType = BaseSpec->getType();
8730 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8731 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008732 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008733
8734 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008735 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008736 break;
8737 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008738 }
8739 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008740 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008741}
8742
Chris Lattnere13042c2008-07-11 19:10:17 +00008743bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008744 switch (E->getOpcode()) {
8745 default:
8746 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8747 // See C99 6.6p3.
8748 return Error(E);
8749 case UO_Extension:
8750 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8751 // If so, we could clear the diagnostic ID.
8752 return Visit(E->getSubExpr());
8753 case UO_Plus:
8754 // The result is just the value.
8755 return Visit(E->getSubExpr());
8756 case UO_Minus: {
8757 if (!Visit(E->getSubExpr()))
8758 return false;
8759 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008760 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008761 if (Value.isSigned() && Value.isMinSignedValue() &&
8762 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8763 E->getType()))
8764 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008765 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766 }
8767 case UO_Not: {
8768 if (!Visit(E->getSubExpr()))
8769 return false;
8770 if (!Result.isInt()) return Error(E);
8771 return Success(~Result.getInt(), E);
8772 }
8773 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008774 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008775 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008776 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008777 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008778 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008779 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008780}
Mike Stump11289f42009-09-09 15:08:12 +00008781
Chris Lattner477c4be2008-07-12 01:15:53 +00008782/// HandleCast - This is used to evaluate implicit or explicit casts where the
8783/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008784bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8785 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008786 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008787 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008788
Eli Friedmanc757de22011-03-25 00:43:55 +00008789 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008790 case CK_BaseToDerived:
8791 case CK_DerivedToBase:
8792 case CK_UncheckedDerivedToBase:
8793 case CK_Dynamic:
8794 case CK_ToUnion:
8795 case CK_ArrayToPointerDecay:
8796 case CK_FunctionToPointerDecay:
8797 case CK_NullToPointer:
8798 case CK_NullToMemberPointer:
8799 case CK_BaseToDerivedMemberPointer:
8800 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008801 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008802 case CK_ConstructorConversion:
8803 case CK_IntegralToPointer:
8804 case CK_ToVoid:
8805 case CK_VectorSplat:
8806 case CK_IntegralToFloating:
8807 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008808 case CK_CPointerToObjCPointerCast:
8809 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008810 case CK_AnyPointerToBlockPointerCast:
8811 case CK_ObjCObjectLValueCast:
8812 case CK_FloatingRealToComplex:
8813 case CK_FloatingComplexToReal:
8814 case CK_FloatingComplexCast:
8815 case CK_FloatingComplexToIntegralComplex:
8816 case CK_IntegralRealToComplex:
8817 case CK_IntegralComplexCast:
8818 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008819 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008820 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008821 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008822 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008823 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008824 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008825 llvm_unreachable("invalid cast kind for integral value");
8826
Eli Friedman9faf2f92011-03-25 19:07:11 +00008827 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008828 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008829 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008830 case CK_ARCProduceObject:
8831 case CK_ARCConsumeObject:
8832 case CK_ARCReclaimReturnedObject:
8833 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008834 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008835 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008836
Richard Smith4ef685b2012-01-17 21:17:26 +00008837 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008838 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008839 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008840 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008841 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008842
8843 case CK_MemberPointerToBoolean:
8844 case CK_PointerToBoolean:
8845 case CK_IntegralToBoolean:
8846 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008847 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008848 case CK_FloatingComplexToBoolean:
8849 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008850 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008851 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008852 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008853 uint64_t IntResult = BoolResult;
8854 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8855 IntResult = (uint64_t)-1;
8856 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008857 }
8858
Eli Friedmanc757de22011-03-25 00:43:55 +00008859 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008860 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008861 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008862
Eli Friedman742421e2009-02-20 01:15:07 +00008863 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008864 // Allow casts of address-of-label differences if they are no-ops
8865 // or narrowing. (The narrowing case isn't actually guaranteed to
8866 // be constant-evaluatable except in some narrow cases which are hard
8867 // to detect here. We let it through on the assumption the user knows
8868 // what they are doing.)
8869 if (Result.isAddrLabelDiff())
8870 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008871 // Only allow casts of lvalues if they are lossless.
8872 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8873 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008874
Richard Smith911e1422012-01-30 22:27:01 +00008875 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8876 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008877 }
Mike Stump11289f42009-09-09 15:08:12 +00008878
Eli Friedmanc757de22011-03-25 00:43:55 +00008879 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008880 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8881
John McCall45d55e42010-05-07 21:00:08 +00008882 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008883 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008884 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008885
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008886 if (LV.getLValueBase()) {
8887 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008888 // FIXME: Allow a larger integer size than the pointer size, and allow
8889 // narrowing back down to pointer width in subsequent integral casts.
8890 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008891 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008892 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008893
Richard Smithcf74da72011-11-16 07:18:12 +00008894 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008895 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008896 return true;
8897 }
8898
Yaxun Liu402804b2016-12-15 08:09:08 +00008899 uint64_t V;
8900 if (LV.isNullPointer())
8901 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8902 else
8903 V = LV.getLValueOffset().getQuantity();
8904
8905 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008906 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008907 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008908
Eli Friedmanc757de22011-03-25 00:43:55 +00008909 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008910 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008911 if (!EvaluateComplex(SubExpr, C, Info))
8912 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008913 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008914 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008915
Eli Friedmanc757de22011-03-25 00:43:55 +00008916 case CK_FloatingToIntegral: {
8917 APFloat F(0.0);
8918 if (!EvaluateFloat(SubExpr, F, Info))
8919 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008920
Richard Smith357362d2011-12-13 06:39:58 +00008921 APSInt Value;
8922 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8923 return false;
8924 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008925 }
8926 }
Mike Stump11289f42009-09-09 15:08:12 +00008927
Eli Friedmanc757de22011-03-25 00:43:55 +00008928 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008929}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008930
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008931bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8932 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008933 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008934 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8935 return false;
8936 if (!LV.isComplexInt())
8937 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008938 return Success(LV.getComplexIntReal(), E);
8939 }
8940
8941 return Visit(E->getSubExpr());
8942}
8943
Eli Friedman4e7a2412009-02-27 04:45:43 +00008944bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008945 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008946 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008947 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8948 return false;
8949 if (!LV.isComplexInt())
8950 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008951 return Success(LV.getComplexIntImag(), E);
8952 }
8953
Richard Smith4a678122011-10-24 18:44:57 +00008954 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008955 return Success(0, E);
8956}
8957
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008958bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8959 return Success(E->getPackLength(), E);
8960}
8961
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008962bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8963 return Success(E->getValue(), E);
8964}
8965
Chris Lattner05706e882008-07-11 18:11:29 +00008966//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008967// Float Evaluation
8968//===----------------------------------------------------------------------===//
8969
8970namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008971class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008972 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008973 APFloat &Result;
8974public:
8975 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008976 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008977
Richard Smith2e312c82012-03-03 22:46:17 +00008978 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008979 Result = V.getFloat();
8980 return true;
8981 }
Eli Friedman24c01542008-08-22 00:06:13 +00008982
Richard Smithfddd3842011-12-30 21:15:51 +00008983 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008984 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8985 return true;
8986 }
8987
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008988 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008989
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008990 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008991 bool VisitBinaryOperator(const BinaryOperator *E);
8992 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008993 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008994
John McCallb1fb0d32010-05-07 22:08:54 +00008995 bool VisitUnaryReal(const UnaryOperator *E);
8996 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008997
Richard Smithfddd3842011-12-30 21:15:51 +00008998 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008999};
9000} // end anonymous namespace
9001
9002static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009003 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009004 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009005}
9006
Jay Foad39c79802011-01-12 09:06:06 +00009007static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009008 QualType ResultTy,
9009 const Expr *Arg,
9010 bool SNaN,
9011 llvm::APFloat &Result) {
9012 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9013 if (!S) return false;
9014
9015 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9016
9017 llvm::APInt fill;
9018
9019 // Treat empty strings as if they were zero.
9020 if (S->getString().empty())
9021 fill = llvm::APInt(32, 0);
9022 else if (S->getString().getAsInteger(0, fill))
9023 return false;
9024
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009025 if (Context.getTargetInfo().isNan2008()) {
9026 if (SNaN)
9027 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9028 else
9029 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9030 } else {
9031 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9032 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9033 // a different encoding to what became a standard in 2008, and for pre-
9034 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9035 // sNaN. This is now known as "legacy NaN" encoding.
9036 if (SNaN)
9037 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9038 else
9039 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9040 }
9041
John McCall16291492010-02-28 13:00:19 +00009042 return true;
9043}
9044
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009045bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009046 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009047 default:
9048 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9049
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009050 case Builtin::BI__builtin_huge_val:
9051 case Builtin::BI__builtin_huge_valf:
9052 case Builtin::BI__builtin_huge_vall:
9053 case Builtin::BI__builtin_inf:
9054 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009055 case Builtin::BI__builtin_infl: {
9056 const llvm::fltSemantics &Sem =
9057 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009058 Result = llvm::APFloat::getInf(Sem);
9059 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009060 }
Mike Stump11289f42009-09-09 15:08:12 +00009061
John McCall16291492010-02-28 13:00:19 +00009062 case Builtin::BI__builtin_nans:
9063 case Builtin::BI__builtin_nansf:
9064 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009065 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9066 true, Result))
9067 return Error(E);
9068 return true;
John McCall16291492010-02-28 13:00:19 +00009069
Chris Lattner0b7282e2008-10-06 06:31:58 +00009070 case Builtin::BI__builtin_nan:
9071 case Builtin::BI__builtin_nanf:
9072 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009073 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009074 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009075 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9076 false, Result))
9077 return Error(E);
9078 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009079
9080 case Builtin::BI__builtin_fabs:
9081 case Builtin::BI__builtin_fabsf:
9082 case Builtin::BI__builtin_fabsl:
9083 if (!EvaluateFloat(E->getArg(0), Result, Info))
9084 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009085
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009086 if (Result.isNegative())
9087 Result.changeSign();
9088 return true;
9089
Richard Smith8889a3d2013-06-13 06:26:32 +00009090 // FIXME: Builtin::BI__builtin_powi
9091 // FIXME: Builtin::BI__builtin_powif
9092 // FIXME: Builtin::BI__builtin_powil
9093
Mike Stump11289f42009-09-09 15:08:12 +00009094 case Builtin::BI__builtin_copysign:
9095 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009096 case Builtin::BI__builtin_copysignl: {
9097 APFloat RHS(0.);
9098 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9099 !EvaluateFloat(E->getArg(1), RHS, Info))
9100 return false;
9101 Result.copySign(RHS);
9102 return true;
9103 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009104 }
9105}
9106
John McCallb1fb0d32010-05-07 22:08:54 +00009107bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009108 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9109 ComplexValue CV;
9110 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9111 return false;
9112 Result = CV.FloatReal;
9113 return true;
9114 }
9115
9116 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009117}
9118
9119bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009120 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9121 ComplexValue CV;
9122 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9123 return false;
9124 Result = CV.FloatImag;
9125 return true;
9126 }
9127
Richard Smith4a678122011-10-24 18:44:57 +00009128 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009129 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9130 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009131 return true;
9132}
9133
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009134bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009135 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009136 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009137 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009138 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009139 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009140 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9141 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009142 Result.changeSign();
9143 return true;
9144 }
9145}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009146
Eli Friedman24c01542008-08-22 00:06:13 +00009147bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009148 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9149 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009150
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009151 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009152 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009153 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009154 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009155 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9156 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009157}
9158
9159bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9160 Result = E->getValue();
9161 return true;
9162}
9163
Peter Collingbournee9200682011-05-13 03:29:01 +00009164bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9165 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009166
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009167 switch (E->getCastKind()) {
9168 default:
Richard Smith11562c52011-10-28 17:51:58 +00009169 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009170
9171 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009172 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009173 return EvaluateInteger(SubExpr, IntResult, Info) &&
9174 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9175 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009176 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009177
9178 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009179 if (!Visit(SubExpr))
9180 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009181 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9182 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009183 }
John McCalld7646252010-11-14 08:17:51 +00009184
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009185 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009186 ComplexValue V;
9187 if (!EvaluateComplex(SubExpr, V, Info))
9188 return false;
9189 Result = V.getComplexFloatReal();
9190 return true;
9191 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009192 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009193}
9194
Eli Friedman24c01542008-08-22 00:06:13 +00009195//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009196// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009197//===----------------------------------------------------------------------===//
9198
9199namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009200class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009201 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009202 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009203
Anders Carlsson537969c2008-11-16 20:27:53 +00009204public:
John McCall93d91dc2010-05-07 17:22:02 +00009205 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009206 : ExprEvaluatorBaseTy(info), Result(Result) {}
9207
Richard Smith2e312c82012-03-03 22:46:17 +00009208 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009209 Result.setFrom(V);
9210 return true;
9211 }
Mike Stump11289f42009-09-09 15:08:12 +00009212
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009213 bool ZeroInitialization(const Expr *E);
9214
Anders Carlsson537969c2008-11-16 20:27:53 +00009215 //===--------------------------------------------------------------------===//
9216 // Visitor Methods
9217 //===--------------------------------------------------------------------===//
9218
Peter Collingbournee9200682011-05-13 03:29:01 +00009219 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009220 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009221 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009222 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009223 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009224};
9225} // end anonymous namespace
9226
John McCall93d91dc2010-05-07 17:22:02 +00009227static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9228 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009229 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009230 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009231}
9232
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009233bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009234 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009235 if (ElemTy->isRealFloatingType()) {
9236 Result.makeComplexFloat();
9237 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9238 Result.FloatReal = Zero;
9239 Result.FloatImag = Zero;
9240 } else {
9241 Result.makeComplexInt();
9242 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9243 Result.IntReal = Zero;
9244 Result.IntImag = Zero;
9245 }
9246 return true;
9247}
9248
Peter Collingbournee9200682011-05-13 03:29:01 +00009249bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9250 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009251
9252 if (SubExpr->getType()->isRealFloatingType()) {
9253 Result.makeComplexFloat();
9254 APFloat &Imag = Result.FloatImag;
9255 if (!EvaluateFloat(SubExpr, Imag, Info))
9256 return false;
9257
9258 Result.FloatReal = APFloat(Imag.getSemantics());
9259 return true;
9260 } else {
9261 assert(SubExpr->getType()->isIntegerType() &&
9262 "Unexpected imaginary literal.");
9263
9264 Result.makeComplexInt();
9265 APSInt &Imag = Result.IntImag;
9266 if (!EvaluateInteger(SubExpr, Imag, Info))
9267 return false;
9268
9269 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9270 return true;
9271 }
9272}
9273
Peter Collingbournee9200682011-05-13 03:29:01 +00009274bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009275
John McCallfcef3cf2010-12-14 17:51:41 +00009276 switch (E->getCastKind()) {
9277 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009278 case CK_BaseToDerived:
9279 case CK_DerivedToBase:
9280 case CK_UncheckedDerivedToBase:
9281 case CK_Dynamic:
9282 case CK_ToUnion:
9283 case CK_ArrayToPointerDecay:
9284 case CK_FunctionToPointerDecay:
9285 case CK_NullToPointer:
9286 case CK_NullToMemberPointer:
9287 case CK_BaseToDerivedMemberPointer:
9288 case CK_DerivedToBaseMemberPointer:
9289 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009290 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009291 case CK_ConstructorConversion:
9292 case CK_IntegralToPointer:
9293 case CK_PointerToIntegral:
9294 case CK_PointerToBoolean:
9295 case CK_ToVoid:
9296 case CK_VectorSplat:
9297 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009298 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009299 case CK_IntegralToBoolean:
9300 case CK_IntegralToFloating:
9301 case CK_FloatingToIntegral:
9302 case CK_FloatingToBoolean:
9303 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009304 case CK_CPointerToObjCPointerCast:
9305 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009306 case CK_AnyPointerToBlockPointerCast:
9307 case CK_ObjCObjectLValueCast:
9308 case CK_FloatingComplexToReal:
9309 case CK_FloatingComplexToBoolean:
9310 case CK_IntegralComplexToReal:
9311 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009312 case CK_ARCProduceObject:
9313 case CK_ARCConsumeObject:
9314 case CK_ARCReclaimReturnedObject:
9315 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009316 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009317 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009318 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009319 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009320 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009321 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009322 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009323 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009324
John McCallfcef3cf2010-12-14 17:51:41 +00009325 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009326 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009327 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009328 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009329
9330 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009331 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009332 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009333 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009334
9335 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009336 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009337 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009338 return false;
9339
John McCallfcef3cf2010-12-14 17:51:41 +00009340 Result.makeComplexFloat();
9341 Result.FloatImag = APFloat(Real.getSemantics());
9342 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009343 }
9344
John McCallfcef3cf2010-12-14 17:51:41 +00009345 case CK_FloatingComplexCast: {
9346 if (!Visit(E->getSubExpr()))
9347 return false;
9348
9349 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9350 QualType From
9351 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9352
Richard Smith357362d2011-12-13 06:39:58 +00009353 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9354 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009355 }
9356
9357 case CK_FloatingComplexToIntegralComplex: {
9358 if (!Visit(E->getSubExpr()))
9359 return false;
9360
9361 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9362 QualType From
9363 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9364 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009365 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9366 To, Result.IntReal) &&
9367 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9368 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009369 }
9370
9371 case CK_IntegralRealToComplex: {
9372 APSInt &Real = Result.IntReal;
9373 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9374 return false;
9375
9376 Result.makeComplexInt();
9377 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9378 return true;
9379 }
9380
9381 case CK_IntegralComplexCast: {
9382 if (!Visit(E->getSubExpr()))
9383 return false;
9384
9385 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9386 QualType From
9387 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9388
Richard Smith911e1422012-01-30 22:27:01 +00009389 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9390 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009391 return true;
9392 }
9393
9394 case CK_IntegralComplexToFloatingComplex: {
9395 if (!Visit(E->getSubExpr()))
9396 return false;
9397
Ted Kremenek28831752012-08-23 20:46:57 +00009398 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009399 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009400 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009401 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009402 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9403 To, Result.FloatReal) &&
9404 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9405 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009406 }
9407 }
9408
9409 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009410}
9411
John McCall93d91dc2010-05-07 17:22:02 +00009412bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009413 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009414 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9415
Chandler Carrutha216cad2014-10-11 00:57:18 +00009416 // Track whether the LHS or RHS is real at the type system level. When this is
9417 // the case we can simplify our evaluation strategy.
9418 bool LHSReal = false, RHSReal = false;
9419
9420 bool LHSOK;
9421 if (E->getLHS()->getType()->isRealFloatingType()) {
9422 LHSReal = true;
9423 APFloat &Real = Result.FloatReal;
9424 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9425 if (LHSOK) {
9426 Result.makeComplexFloat();
9427 Result.FloatImag = APFloat(Real.getSemantics());
9428 }
9429 } else {
9430 LHSOK = Visit(E->getLHS());
9431 }
George Burgess IVa145e252016-05-25 22:38:36 +00009432 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009433 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009434
John McCall93d91dc2010-05-07 17:22:02 +00009435 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009436 if (E->getRHS()->getType()->isRealFloatingType()) {
9437 RHSReal = true;
9438 APFloat &Real = RHS.FloatReal;
9439 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9440 return false;
9441 RHS.makeComplexFloat();
9442 RHS.FloatImag = APFloat(Real.getSemantics());
9443 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009444 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009445
Chandler Carrutha216cad2014-10-11 00:57:18 +00009446 assert(!(LHSReal && RHSReal) &&
9447 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009448 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009449 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009450 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009451 if (Result.isComplexFloat()) {
9452 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9453 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009454 if (LHSReal)
9455 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9456 else if (!RHSReal)
9457 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9458 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009459 } else {
9460 Result.getComplexIntReal() += RHS.getComplexIntReal();
9461 Result.getComplexIntImag() += RHS.getComplexIntImag();
9462 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009463 break;
John McCalle3027922010-08-25 11:45:40 +00009464 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009465 if (Result.isComplexFloat()) {
9466 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9467 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009468 if (LHSReal) {
9469 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9470 Result.getComplexFloatImag().changeSign();
9471 } else if (!RHSReal) {
9472 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9473 APFloat::rmNearestTiesToEven);
9474 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009475 } else {
9476 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9477 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9478 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009479 break;
John McCalle3027922010-08-25 11:45:40 +00009480 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009481 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009482 // This is an implementation of complex multiplication according to the
9483 // constraints laid out in C11 Annex G. The implemantion uses the
9484 // following naming scheme:
9485 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009486 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009487 APFloat &A = LHS.getComplexFloatReal();
9488 APFloat &B = LHS.getComplexFloatImag();
9489 APFloat &C = RHS.getComplexFloatReal();
9490 APFloat &D = RHS.getComplexFloatImag();
9491 APFloat &ResR = Result.getComplexFloatReal();
9492 APFloat &ResI = Result.getComplexFloatImag();
9493 if (LHSReal) {
9494 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9495 ResR = A * C;
9496 ResI = A * D;
9497 } else if (RHSReal) {
9498 ResR = C * A;
9499 ResI = C * B;
9500 } else {
9501 // In the fully general case, we need to handle NaNs and infinities
9502 // robustly.
9503 APFloat AC = A * C;
9504 APFloat BD = B * D;
9505 APFloat AD = A * D;
9506 APFloat BC = B * C;
9507 ResR = AC - BD;
9508 ResI = AD + BC;
9509 if (ResR.isNaN() && ResI.isNaN()) {
9510 bool Recalc = false;
9511 if (A.isInfinity() || B.isInfinity()) {
9512 A = APFloat::copySign(
9513 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9514 B = APFloat::copySign(
9515 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9516 if (C.isNaN())
9517 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9518 if (D.isNaN())
9519 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9520 Recalc = true;
9521 }
9522 if (C.isInfinity() || D.isInfinity()) {
9523 C = APFloat::copySign(
9524 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9525 D = APFloat::copySign(
9526 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9527 if (A.isNaN())
9528 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9529 if (B.isNaN())
9530 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9531 Recalc = true;
9532 }
9533 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9534 AD.isInfinity() || BC.isInfinity())) {
9535 if (A.isNaN())
9536 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9537 if (B.isNaN())
9538 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9539 if (C.isNaN())
9540 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9541 if (D.isNaN())
9542 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9543 Recalc = true;
9544 }
9545 if (Recalc) {
9546 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9547 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9548 }
9549 }
9550 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009551 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009552 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009553 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009554 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9555 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009556 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009557 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9558 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9559 }
9560 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009561 case BO_Div:
9562 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009563 // This is an implementation of complex division according to the
9564 // constraints laid out in C11 Annex G. The implemantion uses the
9565 // following naming scheme:
9566 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009567 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009568 APFloat &A = LHS.getComplexFloatReal();
9569 APFloat &B = LHS.getComplexFloatImag();
9570 APFloat &C = RHS.getComplexFloatReal();
9571 APFloat &D = RHS.getComplexFloatImag();
9572 APFloat &ResR = Result.getComplexFloatReal();
9573 APFloat &ResI = Result.getComplexFloatImag();
9574 if (RHSReal) {
9575 ResR = A / C;
9576 ResI = B / C;
9577 } else {
9578 if (LHSReal) {
9579 // No real optimizations we can do here, stub out with zero.
9580 B = APFloat::getZero(A.getSemantics());
9581 }
9582 int DenomLogB = 0;
9583 APFloat MaxCD = maxnum(abs(C), abs(D));
9584 if (MaxCD.isFinite()) {
9585 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009586 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9587 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009588 }
9589 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009590 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9591 APFloat::rmNearestTiesToEven);
9592 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9593 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009594 if (ResR.isNaN() && ResI.isNaN()) {
9595 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9596 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9597 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9598 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9599 D.isFinite()) {
9600 A = APFloat::copySign(
9601 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9602 B = APFloat::copySign(
9603 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9604 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9605 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9606 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9607 C = APFloat::copySign(
9608 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9609 D = APFloat::copySign(
9610 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9611 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9612 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9613 }
9614 }
9615 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009616 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009617 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9618 return Error(E, diag::note_expr_divide_by_zero);
9619
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009620 ComplexValue LHS = Result;
9621 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9622 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9623 Result.getComplexIntReal() =
9624 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9625 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9626 Result.getComplexIntImag() =
9627 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9628 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9629 }
9630 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009631 }
9632
John McCall93d91dc2010-05-07 17:22:02 +00009633 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009634}
9635
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009636bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9637 // Get the operand value into 'Result'.
9638 if (!Visit(E->getSubExpr()))
9639 return false;
9640
9641 switch (E->getOpcode()) {
9642 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009643 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009644 case UO_Extension:
9645 return true;
9646 case UO_Plus:
9647 // The result is always just the subexpr.
9648 return true;
9649 case UO_Minus:
9650 if (Result.isComplexFloat()) {
9651 Result.getComplexFloatReal().changeSign();
9652 Result.getComplexFloatImag().changeSign();
9653 }
9654 else {
9655 Result.getComplexIntReal() = -Result.getComplexIntReal();
9656 Result.getComplexIntImag() = -Result.getComplexIntImag();
9657 }
9658 return true;
9659 case UO_Not:
9660 if (Result.isComplexFloat())
9661 Result.getComplexFloatImag().changeSign();
9662 else
9663 Result.getComplexIntImag() = -Result.getComplexIntImag();
9664 return true;
9665 }
9666}
9667
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009668bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9669 if (E->getNumInits() == 2) {
9670 if (E->getType()->isComplexType()) {
9671 Result.makeComplexFloat();
9672 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9673 return false;
9674 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9675 return false;
9676 } else {
9677 Result.makeComplexInt();
9678 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9679 return false;
9680 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9681 return false;
9682 }
9683 return true;
9684 }
9685 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9686}
9687
Anders Carlsson537969c2008-11-16 20:27:53 +00009688//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009689// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9690// implicit conversion.
9691//===----------------------------------------------------------------------===//
9692
9693namespace {
9694class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009695 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009696 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009697 APValue &Result;
9698public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009699 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9700 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009701
9702 bool Success(const APValue &V, const Expr *E) {
9703 Result = V;
9704 return true;
9705 }
9706
9707 bool ZeroInitialization(const Expr *E) {
9708 ImplicitValueInitExpr VIE(
9709 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009710 // For atomic-qualified class (and array) types in C++, initialize the
9711 // _Atomic-wrapped subobject directly, in-place.
9712 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9713 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009714 }
9715
9716 bool VisitCastExpr(const CastExpr *E) {
9717 switch (E->getCastKind()) {
9718 default:
9719 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9720 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009721 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9722 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009723 }
9724 }
9725};
9726} // end anonymous namespace
9727
Richard Smith64cb9ca2017-02-22 22:09:50 +00009728static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9729 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009730 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009731 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009732}
9733
9734//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009735// Void expression evaluation, primarily for a cast to void on the LHS of a
9736// comma operator
9737//===----------------------------------------------------------------------===//
9738
9739namespace {
9740class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009741 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009742public:
9743 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9744
Richard Smith2e312c82012-03-03 22:46:17 +00009745 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009746
9747 bool VisitCastExpr(const CastExpr *E) {
9748 switch (E->getCastKind()) {
9749 default:
9750 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9751 case CK_ToVoid:
9752 VisitIgnoredValue(E->getSubExpr());
9753 return true;
9754 }
9755 }
Hal Finkela8443c32014-07-17 14:49:58 +00009756
9757 bool VisitCallExpr(const CallExpr *E) {
9758 switch (E->getBuiltinCallee()) {
9759 default:
9760 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9761 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009762 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009763 // The argument is not evaluated!
9764 return true;
9765 }
9766 }
Richard Smith42d3af92011-12-07 00:43:50 +00009767};
9768} // end anonymous namespace
9769
9770static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9771 assert(E->isRValue() && E->getType()->isVoidType());
9772 return VoidExprEvaluator(Info).Visit(E);
9773}
9774
9775//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009776// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009777//===----------------------------------------------------------------------===//
9778
Richard Smith2e312c82012-03-03 22:46:17 +00009779static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009780 // In C, function designators are not lvalues, but we evaluate them as if they
9781 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009782 QualType T = E->getType();
9783 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009784 LValue LV;
9785 if (!EvaluateLValue(E, LV, Info))
9786 return false;
9787 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009788 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009789 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009790 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009791 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009792 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009793 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009794 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009795 LValue LV;
9796 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009797 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009798 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009799 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009800 llvm::APFloat F(0.0);
9801 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009802 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009803 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009804 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009805 ComplexValue C;
9806 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009807 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009808 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009809 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009810 MemberPtr P;
9811 if (!EvaluateMemberPointer(E, P, Info))
9812 return false;
9813 P.moveInto(Result);
9814 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009815 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009816 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009817 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009818 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9819 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009820 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009821 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009822 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009823 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009824 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009825 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9826 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009827 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009828 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009829 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009830 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009831 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009832 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009833 if (!EvaluateVoid(E, Info))
9834 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009835 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009836 QualType Unqual = T.getAtomicUnqualifiedType();
9837 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9838 LValue LV;
9839 LV.set(E, Info.CurrentCall->Index);
9840 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9841 if (!EvaluateAtomic(E, &LV, Value, Info))
9842 return false;
9843 } else {
9844 if (!EvaluateAtomic(E, nullptr, Result, Info))
9845 return false;
9846 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009847 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009848 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009849 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009850 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009851 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009852 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009853 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009854
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009855 return true;
9856}
9857
Richard Smithb228a862012-02-15 02:18:13 +00009858/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9859/// cases, the in-place evaluation is essential, since later initializers for
9860/// an object can indirectly refer to subobjects which were initialized earlier.
9861static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009862 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009863 assert(!E->isValueDependent());
9864
Richard Smith7525ff62013-05-09 07:14:00 +00009865 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009866 return false;
9867
9868 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009869 // Evaluate arrays and record types in-place, so that later initializers can
9870 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009871 QualType T = E->getType();
9872 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009873 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009874 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009875 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009876 else if (T->isAtomicType()) {
9877 QualType Unqual = T.getAtomicUnqualifiedType();
9878 if (Unqual->isArrayType() || Unqual->isRecordType())
9879 return EvaluateAtomic(E, &This, Result, Info);
9880 }
Richard Smithed5165f2011-11-04 05:33:44 +00009881 }
9882
9883 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009884 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009885}
9886
Richard Smithf57d8cb2011-12-09 22:58:01 +00009887/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9888/// lvalue-to-rvalue cast if it is an lvalue.
9889static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009890 if (E->getType().isNull())
9891 return false;
9892
Richard Smithfddd3842011-12-30 21:15:51 +00009893 if (!CheckLiteralType(Info, E))
9894 return false;
9895
Richard Smith2e312c82012-03-03 22:46:17 +00009896 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009897 return false;
9898
9899 if (E->isGLValue()) {
9900 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009901 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009902 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009903 return false;
9904 }
9905
Richard Smith2e312c82012-03-03 22:46:17 +00009906 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009907 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009908}
Richard Smith11562c52011-10-28 17:51:58 +00009909
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009910static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9911 const ASTContext &Ctx, bool &IsConst) {
9912 // Fast-path evaluations of integer literals, since we sometimes see files
9913 // containing vast quantities of these.
9914 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9915 Result.Val = APValue(APSInt(L->getValue(),
9916 L->getType()->isUnsignedIntegerType()));
9917 IsConst = true;
9918 return true;
9919 }
James Dennett0492ef02014-03-14 17:44:10 +00009920
9921 // This case should be rare, but we need to check it before we check on
9922 // the type below.
9923 if (Exp->getType().isNull()) {
9924 IsConst = false;
9925 return true;
9926 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009927
9928 // FIXME: Evaluating values of large array and record types can cause
9929 // performance problems. Only do so in C++11 for now.
9930 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9931 Exp->getType()->isRecordType()) &&
9932 !Ctx.getLangOpts().CPlusPlus11) {
9933 IsConst = false;
9934 return true;
9935 }
9936 return false;
9937}
9938
9939
Richard Smith7b553f12011-10-29 00:50:52 +00009940/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009941/// any crazy technique (that has nothing to do with language standards) that
9942/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009943/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9944/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009945bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009946 bool IsConst;
9947 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9948 return IsConst;
9949
Richard Smith6d4c6582013-11-05 22:18:15 +00009950 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009951 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009952}
9953
Jay Foad39c79802011-01-12 09:06:06 +00009954bool Expr::EvaluateAsBooleanCondition(bool &Result,
9955 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009956 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009957 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009958 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009959}
9960
Richard Smithce8eca52015-12-08 03:21:47 +00009961static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9962 Expr::SideEffectsKind SEK) {
9963 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9964 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9965}
9966
Richard Smith5fab0c92011-12-28 19:48:30 +00009967bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9968 SideEffectsKind AllowSideEffects) const {
9969 if (!getType()->isIntegralOrEnumerationType())
9970 return false;
9971
Richard Smith11562c52011-10-28 17:51:58 +00009972 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009973 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009974 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009975 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009976
Richard Smith11562c52011-10-28 17:51:58 +00009977 Result = ExprResult.Val.getInt();
9978 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009979}
9980
Richard Trieube234c32016-04-21 21:04:55 +00009981bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9982 SideEffectsKind AllowSideEffects) const {
9983 if (!getType()->isRealFloatingType())
9984 return false;
9985
9986 EvalResult ExprResult;
9987 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9988 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9989 return false;
9990
9991 Result = ExprResult.Val.getFloat();
9992 return true;
9993}
9994
Jay Foad39c79802011-01-12 09:06:06 +00009995bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009996 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009997
John McCall45d55e42010-05-07 21:00:08 +00009998 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009999 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10000 !CheckLValueConstantExpression(Info, getExprLoc(),
10001 Ctx.getLValueReferenceType(getType()), LV))
10002 return false;
10003
Richard Smith2e312c82012-03-03 22:46:17 +000010004 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010005 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010006}
10007
Richard Smithd0b4dd62011-12-19 06:19:21 +000010008bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10009 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010010 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010011 // FIXME: Evaluating initializers for large array and record types can cause
10012 // performance problems. Only do so in C++11 for now.
10013 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010014 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010015 return false;
10016
Richard Smithd0b4dd62011-12-19 06:19:21 +000010017 Expr::EvalStatus EStatus;
10018 EStatus.Diag = &Notes;
10019
Richard Smith0c6124b2015-12-03 01:36:22 +000010020 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10021 ? EvalInfo::EM_ConstantExpression
10022 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010023 InitInfo.setEvaluatingDecl(VD, Value);
10024
10025 LValue LVal;
10026 LVal.set(VD);
10027
Richard Smithfddd3842011-12-30 21:15:51 +000010028 // C++11 [basic.start.init]p2:
10029 // Variables with static storage duration or thread storage duration shall be
10030 // zero-initialized before any other initialization takes place.
10031 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010032 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010033 !VD->getType()->isReferenceType()) {
10034 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010035 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010036 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010037 return false;
10038 }
10039
Richard Smith7525ff62013-05-09 07:14:00 +000010040 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10041 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010042 EStatus.HasSideEffects)
10043 return false;
10044
10045 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10046 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010047}
10048
Richard Smith7b553f12011-10-29 00:50:52 +000010049/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10050/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010051bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010052 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010053 return EvaluateAsRValue(Result, Ctx) &&
10054 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010055}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010056
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010057APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010058 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010059 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010060 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010061 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010062 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010063 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010064 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010065
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010066 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010067}
John McCall864e3962010-05-07 05:32:02 +000010068
Richard Smithe9ff7702013-11-05 22:23:30 +000010069void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010070 bool IsConst;
10071 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010072 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010073 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010074 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10075 }
10076}
10077
Richard Smithe6c01442013-06-05 00:46:14 +000010078bool Expr::EvalResult::isGlobalLValue() const {
10079 assert(Val.isLValue());
10080 return IsGlobalLValue(Val.getLValueBase());
10081}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010082
10083
John McCall864e3962010-05-07 05:32:02 +000010084/// isIntegerConstantExpr - this recursive routine will test if an expression is
10085/// an integer constant expression.
10086
10087/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10088/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010089
10090// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010091// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10092// and a (possibly null) SourceLocation indicating the location of the problem.
10093//
John McCall864e3962010-05-07 05:32:02 +000010094// Note that to reduce code duplication, this helper does no evaluation
10095// itself; the caller checks whether the expression is evaluatable, and
10096// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010097// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010098
Dan Gohman28ade552010-07-26 21:25:24 +000010099namespace {
10100
Richard Smith9e575da2012-12-28 13:25:52 +000010101enum ICEKind {
10102 /// This expression is an ICE.
10103 IK_ICE,
10104 /// This expression is not an ICE, but if it isn't evaluated, it's
10105 /// a legal subexpression for an ICE. This return value is used to handle
10106 /// the comma operator in C99 mode, and non-constant subexpressions.
10107 IK_ICEIfUnevaluated,
10108 /// This expression is not an ICE, and is not a legal subexpression for one.
10109 IK_NotICE
10110};
10111
John McCall864e3962010-05-07 05:32:02 +000010112struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010113 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010114 SourceLocation Loc;
10115
Richard Smith9e575da2012-12-28 13:25:52 +000010116 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010117};
10118
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010119}
Dan Gohman28ade552010-07-26 21:25:24 +000010120
Richard Smith9e575da2012-12-28 13:25:52 +000010121static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10122
10123static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010124
Craig Toppera31a8822013-08-22 07:09:37 +000010125static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010126 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010127 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010128 !EVResult.Val.isInt())
10129 return ICEDiag(IK_NotICE, E->getLocStart());
10130
John McCall864e3962010-05-07 05:32:02 +000010131 return NoDiag();
10132}
10133
Craig Toppera31a8822013-08-22 07:09:37 +000010134static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010135 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010136 if (!E->getType()->isIntegralOrEnumerationType())
10137 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010138
10139 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010140#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010141#define STMT(Node, Base) case Expr::Node##Class:
10142#define EXPR(Node, Base)
10143#include "clang/AST/StmtNodes.inc"
10144 case Expr::PredefinedExprClass:
10145 case Expr::FloatingLiteralClass:
10146 case Expr::ImaginaryLiteralClass:
10147 case Expr::StringLiteralClass:
10148 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010149 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010150 case Expr::MemberExprClass:
10151 case Expr::CompoundAssignOperatorClass:
10152 case Expr::CompoundLiteralExprClass:
10153 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010154 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010155 case Expr::ArrayInitLoopExprClass:
10156 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010157 case Expr::NoInitExprClass:
10158 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010159 case Expr::ImplicitValueInitExprClass:
10160 case Expr::ParenListExprClass:
10161 case Expr::VAArgExprClass:
10162 case Expr::AddrLabelExprClass:
10163 case Expr::StmtExprClass:
10164 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010165 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010166 case Expr::CXXDynamicCastExprClass:
10167 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010168 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010169 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010170 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010171 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010172 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010173 case Expr::CXXThisExprClass:
10174 case Expr::CXXThrowExprClass:
10175 case Expr::CXXNewExprClass:
10176 case Expr::CXXDeleteExprClass:
10177 case Expr::CXXPseudoDestructorExprClass:
10178 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010179 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010180 case Expr::DependentScopeDeclRefExprClass:
10181 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010182 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010183 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010184 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010185 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010186 case Expr::CXXTemporaryObjectExprClass:
10187 case Expr::CXXUnresolvedConstructExprClass:
10188 case Expr::CXXDependentScopeMemberExprClass:
10189 case Expr::UnresolvedMemberExprClass:
10190 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010191 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010192 case Expr::ObjCArrayLiteralClass:
10193 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010194 case Expr::ObjCEncodeExprClass:
10195 case Expr::ObjCMessageExprClass:
10196 case Expr::ObjCSelectorExprClass:
10197 case Expr::ObjCProtocolExprClass:
10198 case Expr::ObjCIvarRefExprClass:
10199 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010200 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010201 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010202 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010203 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010204 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010205 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010206 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010207 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010208 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010209 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010210 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010211 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010212 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010213 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010214 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010215 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010216 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010217 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010218 case Expr::CoawaitExprClass:
10219 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010220 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010221
Richard Smithf137f932014-01-25 20:50:08 +000010222 case Expr::InitListExprClass: {
10223 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10224 // form "T x = { a };" is equivalent to "T x = a;".
10225 // Unless we're initializing a reference, T is a scalar as it is known to be
10226 // of integral or enumeration type.
10227 if (E->isRValue())
10228 if (cast<InitListExpr>(E)->getNumInits() == 1)
10229 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10230 return ICEDiag(IK_NotICE, E->getLocStart());
10231 }
10232
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010233 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010234 case Expr::GNUNullExprClass:
10235 // GCC considers the GNU __null value to be an integral constant expression.
10236 return NoDiag();
10237
John McCall7c454bb2011-07-15 05:09:51 +000010238 case Expr::SubstNonTypeTemplateParmExprClass:
10239 return
10240 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10241
John McCall864e3962010-05-07 05:32:02 +000010242 case Expr::ParenExprClass:
10243 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010244 case Expr::GenericSelectionExprClass:
10245 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010246 case Expr::IntegerLiteralClass:
10247 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010248 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010249 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010250 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010251 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010252 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010253 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010254 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010255 return NoDiag();
10256 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010257 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010258 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10259 // constant expressions, but they can never be ICEs because an ICE cannot
10260 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010261 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010262 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010263 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010264 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010265 }
Richard Smith6365c912012-02-24 22:12:32 +000010266 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010267 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10268 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010269 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010270 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010271 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010272 // Parameter variables are never constants. Without this check,
10273 // getAnyInitializer() can find a default argument, which leads
10274 // to chaos.
10275 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010276 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010277
10278 // C++ 7.1.5.1p2
10279 // A variable of non-volatile const-qualified integral or enumeration
10280 // type initialized by an ICE can be used in ICEs.
10281 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010282 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010283 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010284
Richard Smithd0b4dd62011-12-19 06:19:21 +000010285 const VarDecl *VD;
10286 // Look for a declaration of this variable that has an initializer, and
10287 // check whether it is an ICE.
10288 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10289 return NoDiag();
10290 else
Richard Smith9e575da2012-12-28 13:25:52 +000010291 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010292 }
10293 }
Richard Smith9e575da2012-12-28 13:25:52 +000010294 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010295 }
John McCall864e3962010-05-07 05:32:02 +000010296 case Expr::UnaryOperatorClass: {
10297 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10298 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010299 case UO_PostInc:
10300 case UO_PostDec:
10301 case UO_PreInc:
10302 case UO_PreDec:
10303 case UO_AddrOf:
10304 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010305 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010306 // C99 6.6/3 allows increment and decrement within unevaluated
10307 // subexpressions of constant expressions, but they can never be ICEs
10308 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010309 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010310 case UO_Extension:
10311 case UO_LNot:
10312 case UO_Plus:
10313 case UO_Minus:
10314 case UO_Not:
10315 case UO_Real:
10316 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010317 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010318 }
Richard Smith9e575da2012-12-28 13:25:52 +000010319
John McCall864e3962010-05-07 05:32:02 +000010320 // OffsetOf falls through here.
10321 }
10322 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010323 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10324 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10325 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10326 // compliance: we should warn earlier for offsetof expressions with
10327 // array subscripts that aren't ICEs, and if the array subscripts
10328 // are ICEs, the value of the offsetof must be an integer constant.
10329 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010330 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010331 case Expr::UnaryExprOrTypeTraitExprClass: {
10332 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10333 if ((Exp->getKind() == UETT_SizeOf) &&
10334 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010335 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010336 return NoDiag();
10337 }
10338 case Expr::BinaryOperatorClass: {
10339 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10340 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010341 case BO_PtrMemD:
10342 case BO_PtrMemI:
10343 case BO_Assign:
10344 case BO_MulAssign:
10345 case BO_DivAssign:
10346 case BO_RemAssign:
10347 case BO_AddAssign:
10348 case BO_SubAssign:
10349 case BO_ShlAssign:
10350 case BO_ShrAssign:
10351 case BO_AndAssign:
10352 case BO_XorAssign:
10353 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010354 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10355 // constant expressions, but they can never be ICEs because an ICE cannot
10356 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010357 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010358
John McCalle3027922010-08-25 11:45:40 +000010359 case BO_Mul:
10360 case BO_Div:
10361 case BO_Rem:
10362 case BO_Add:
10363 case BO_Sub:
10364 case BO_Shl:
10365 case BO_Shr:
10366 case BO_LT:
10367 case BO_GT:
10368 case BO_LE:
10369 case BO_GE:
10370 case BO_EQ:
10371 case BO_NE:
10372 case BO_And:
10373 case BO_Xor:
10374 case BO_Or:
10375 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010376 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10377 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010378 if (Exp->getOpcode() == BO_Div ||
10379 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010380 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010381 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010382 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010383 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010384 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010385 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010386 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010387 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010388 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010389 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010390 }
10391 }
10392 }
John McCalle3027922010-08-25 11:45:40 +000010393 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010394 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010395 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10396 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010397 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10398 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010399 } else {
10400 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010401 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010402 }
10403 }
Richard Smith9e575da2012-12-28 13:25:52 +000010404 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010405 }
John McCalle3027922010-08-25 11:45:40 +000010406 case BO_LAnd:
10407 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010408 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10409 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010410 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010411 // Rare case where the RHS has a comma "side-effect"; we need
10412 // to actually check the condition to see whether the side
10413 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010414 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010415 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010416 return RHSResult;
10417 return NoDiag();
10418 }
10419
Richard Smith9e575da2012-12-28 13:25:52 +000010420 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010421 }
10422 }
10423 }
10424 case Expr::ImplicitCastExprClass:
10425 case Expr::CStyleCastExprClass:
10426 case Expr::CXXFunctionalCastExprClass:
10427 case Expr::CXXStaticCastExprClass:
10428 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010429 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010430 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010431 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010432 if (isa<ExplicitCastExpr>(E)) {
10433 if (const FloatingLiteral *FL
10434 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10435 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10436 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10437 APSInt IgnoredVal(DestWidth, !DestSigned);
10438 bool Ignored;
10439 // If the value does not fit in the destination type, the behavior is
10440 // undefined, so we are not required to treat it as a constant
10441 // expression.
10442 if (FL->getValue().convertToInteger(IgnoredVal,
10443 llvm::APFloat::rmTowardZero,
10444 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010445 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010446 return NoDiag();
10447 }
10448 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010449 switch (cast<CastExpr>(E)->getCastKind()) {
10450 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010451 case CK_AtomicToNonAtomic:
10452 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010453 case CK_NoOp:
10454 case CK_IntegralToBoolean:
10455 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010456 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010457 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010458 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010459 }
John McCall864e3962010-05-07 05:32:02 +000010460 }
John McCallc07a0c72011-02-17 10:25:35 +000010461 case Expr::BinaryConditionalOperatorClass: {
10462 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10463 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010464 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010465 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010466 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10467 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10468 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010469 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010470 return FalseResult;
10471 }
John McCall864e3962010-05-07 05:32:02 +000010472 case Expr::ConditionalOperatorClass: {
10473 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10474 // If the condition (ignoring parens) is a __builtin_constant_p call,
10475 // then only the true side is actually considered in an integer constant
10476 // expression, and it is fully evaluated. This is an important GNU
10477 // extension. See GCC PR38377 for discussion.
10478 if (const CallExpr *CallCE
10479 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010480 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010481 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010482 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010483 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010484 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010485
Richard Smithf57d8cb2011-12-09 22:58:01 +000010486 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10487 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010488
Richard Smith9e575da2012-12-28 13:25:52 +000010489 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010490 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010491 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010492 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010493 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010494 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010495 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010496 return NoDiag();
10497 // Rare case where the diagnostics depend on which side is evaluated
10498 // Note that if we get here, CondResult is 0, and at least one of
10499 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010500 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010501 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010502 return TrueResult;
10503 }
10504 case Expr::CXXDefaultArgExprClass:
10505 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010506 case Expr::CXXDefaultInitExprClass:
10507 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010508 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010509 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010510 }
10511 }
10512
David Blaikiee4d798f2012-01-20 21:50:17 +000010513 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010514}
10515
Richard Smithf57d8cb2011-12-09 22:58:01 +000010516/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010517static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010518 const Expr *E,
10519 llvm::APSInt *Value,
10520 SourceLocation *Loc) {
10521 if (!E->getType()->isIntegralOrEnumerationType()) {
10522 if (Loc) *Loc = E->getExprLoc();
10523 return false;
10524 }
10525
Richard Smith66e05fe2012-01-18 05:21:49 +000010526 APValue Result;
10527 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010528 return false;
10529
Richard Smith98710fc2014-11-13 23:03:19 +000010530 if (!Result.isInt()) {
10531 if (Loc) *Loc = E->getExprLoc();
10532 return false;
10533 }
10534
Richard Smith66e05fe2012-01-18 05:21:49 +000010535 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010536 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010537}
10538
Craig Toppera31a8822013-08-22 07:09:37 +000010539bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10540 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010541 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010542 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010543
Richard Smith9e575da2012-12-28 13:25:52 +000010544 ICEDiag D = CheckICE(this, Ctx);
10545 if (D.Kind != IK_ICE) {
10546 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010547 return false;
10548 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010549 return true;
10550}
10551
Craig Toppera31a8822013-08-22 07:09:37 +000010552bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010553 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010554 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010555 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10556
10557 if (!isIntegerConstantExpr(Ctx, Loc))
10558 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010559 // The only possible side-effects here are due to UB discovered in the
10560 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10561 // required to treat the expression as an ICE, so we produce the folded
10562 // value.
10563 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010564 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010565 return true;
10566}
Richard Smith66e05fe2012-01-18 05:21:49 +000010567
Craig Toppera31a8822013-08-22 07:09:37 +000010568bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010569 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010570}
10571
Craig Toppera31a8822013-08-22 07:09:37 +000010572bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010573 SourceLocation *Loc) const {
10574 // We support this checking in C++98 mode in order to diagnose compatibility
10575 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010576 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010577
Richard Smith98a0a492012-02-14 21:38:30 +000010578 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010579 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010580 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010581 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010582 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010583
10584 APValue Scratch;
10585 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10586
10587 if (!Diags.empty()) {
10588 IsConstExpr = false;
10589 if (Loc) *Loc = Diags[0].first;
10590 } else if (!IsConstExpr) {
10591 // FIXME: This shouldn't happen.
10592 if (Loc) *Loc = getExprLoc();
10593 }
10594
10595 return IsConstExpr;
10596}
Richard Smith253c2a32012-01-27 01:14:48 +000010597
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010598bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10599 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010600 ArrayRef<const Expr*> Args,
10601 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010602 Expr::EvalStatus Status;
10603 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10604
George Burgess IV177399e2017-01-09 04:12:14 +000010605 LValue ThisVal;
10606 const LValue *ThisPtr = nullptr;
10607 if (This) {
10608#ifndef NDEBUG
10609 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10610 assert(MD && "Don't provide `this` for non-methods.");
10611 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10612#endif
10613 if (EvaluateObjectArgument(Info, This, ThisVal))
10614 ThisPtr = &ThisVal;
10615 if (Info.EvalStatus.HasSideEffects)
10616 return false;
10617 }
10618
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010619 ArgVector ArgValues(Args.size());
10620 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10621 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010622 if ((*I)->isValueDependent() ||
10623 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010624 // If evaluation fails, throw away the argument entirely.
10625 ArgValues[I - Args.begin()] = APValue();
10626 if (Info.EvalStatus.HasSideEffects)
10627 return false;
10628 }
10629
10630 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010631 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010632 ArgValues.data());
10633 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10634}
10635
Richard Smith253c2a32012-01-27 01:14:48 +000010636bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010637 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010638 PartialDiagnosticAt> &Diags) {
10639 // FIXME: It would be useful to check constexpr function templates, but at the
10640 // moment the constant expression evaluator cannot cope with the non-rigorous
10641 // ASTs which we build for dependent expressions.
10642 if (FD->isDependentContext())
10643 return true;
10644
10645 Expr::EvalStatus Status;
10646 Status.Diag = &Diags;
10647
Richard Smith6d4c6582013-11-05 22:18:15 +000010648 EvalInfo Info(FD->getASTContext(), Status,
10649 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010650
10651 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010652 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010653
Richard Smith7525ff62013-05-09 07:14:00 +000010654 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010655 // is a temporary being used as the 'this' pointer.
10656 LValue This;
10657 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010658 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010659
Richard Smith253c2a32012-01-27 01:14:48 +000010660 ArrayRef<const Expr*> Args;
10661
Richard Smith2e312c82012-03-03 22:46:17 +000010662 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010663 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10664 // Evaluate the call as a constant initializer, to allow the construction
10665 // of objects of non-literal types.
10666 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010667 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10668 } else {
10669 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010670 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010671 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010672 }
Richard Smith253c2a32012-01-27 01:14:48 +000010673
10674 return Diags.empty();
10675}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010676
10677bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10678 const FunctionDecl *FD,
10679 SmallVectorImpl<
10680 PartialDiagnosticAt> &Diags) {
10681 Expr::EvalStatus Status;
10682 Status.Diag = &Diags;
10683
10684 EvalInfo Info(FD->getASTContext(), Status,
10685 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10686
10687 // Fabricate a call stack frame to give the arguments a plausible cover story.
10688 ArrayRef<const Expr*> Args;
10689 ArgVector ArgValues(0);
10690 bool Success = EvaluateArgs(Args, ArgValues, Info);
10691 (void)Success;
10692 assert(Success &&
10693 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010694 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010695
10696 APValue ResultScratch;
10697 Evaluate(ResultScratch, Info, E);
10698 return Diags.empty();
10699}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010700
10701bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10702 unsigned Type) const {
10703 if (!getType()->isPointerType())
10704 return false;
10705
10706 Expr::EvalStatus Status;
10707 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010708 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010709}