blob: fafd91dc7149f3c814ef14829b925aad5b0347ea [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
Richard Smithf6f003a2011-12-16 19:06:07 +0000428 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
429 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000430 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000431 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000432
433 APValue *getTemporary(const void *Key) {
434 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000435 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000436 }
437 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000438 };
439
Richard Smith852c9db2013-04-20 22:23:05 +0000440 /// Temporarily override 'this'.
441 class ThisOverrideRAII {
442 public:
443 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
444 : Frame(Frame), OldThis(Frame.This) {
445 if (Enable)
446 Frame.This = NewThis;
447 }
448 ~ThisOverrideRAII() {
449 Frame.This = OldThis;
450 }
451 private:
452 CallStackFrame &Frame;
453 const LValue *OldThis;
454 };
455
Richard Smith92b1ce02011-12-12 09:28:41 +0000456 /// A partial diagnostic which we might know in advance that we are not going
457 /// to emit.
458 class OptionalDiagnostic {
459 PartialDiagnostic *Diag;
460
461 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000462 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
463 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000464
465 template<typename T>
466 OptionalDiagnostic &operator<<(const T &v) {
467 if (Diag)
468 *Diag << v;
469 return *this;
470 }
Richard Smithfe800032012-01-31 04:08:20 +0000471
472 OptionalDiagnostic &operator<<(const APSInt &I) {
473 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000474 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000475 I.toString(Buffer);
476 *Diag << StringRef(Buffer.data(), Buffer.size());
477 }
478 return *this;
479 }
480
481 OptionalDiagnostic &operator<<(const APFloat &F) {
482 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000483 // FIXME: Force the precision of the source value down so we don't
484 // print digits which are usually useless (we don't really care here if
485 // we truncate a digit by accident in edge cases). Ideally,
486 // APFloat::toString would automatically print the shortest
487 // representation which rounds to the correct value, but it's a bit
488 // tricky to implement.
489 unsigned precision =
490 llvm::APFloat::semanticsPrecision(F.getSemantics());
491 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000492 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000493 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000494 *Diag << StringRef(Buffer.data(), Buffer.size());
495 }
496 return *this;
497 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000498 };
499
Richard Smith08d6a2c2013-07-24 07:11:57 +0000500 /// A cleanup, and a flag indicating whether it is lifetime-extended.
501 class Cleanup {
502 llvm::PointerIntPair<APValue*, 1, bool> Value;
503
504 public:
505 Cleanup(APValue *Val, bool IsLifetimeExtended)
506 : Value(Val, IsLifetimeExtended) {}
507
508 bool isLifetimeExtended() const { return Value.getInt(); }
509 void endLifetime() {
510 *Value.getPointer() = APValue();
511 }
512 };
513
Richard Smithb228a862012-02-15 02:18:13 +0000514 /// EvalInfo - This is a private struct used by the evaluator to capture
515 /// information about a subexpression as it is folded. It retains information
516 /// about the AST context, but also maintains information about the folded
517 /// expression.
518 ///
519 /// If an expression could be evaluated, it is still possible it is not a C
520 /// "integer constant expression" or constant expression. If not, this struct
521 /// captures information about how and why not.
522 ///
523 /// One bit of information passed *into* the request for constant folding
524 /// indicates whether the subexpression is "evaluated" or not according to C
525 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
526 /// evaluate the expression regardless of what the RHS is, but C only allows
527 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000528 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000529 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000530
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000531 /// EvalStatus - Contains information about the evaluation.
532 Expr::EvalStatus &EvalStatus;
533
534 /// CurrentCall - The top of the constexpr call stack.
535 CallStackFrame *CurrentCall;
536
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 /// CallStackDepth - The number of calls in the call stack right now.
538 unsigned CallStackDepth;
539
Richard Smithb228a862012-02-15 02:18:13 +0000540 /// NextCallIndex - The next call index to assign.
541 unsigned NextCallIndex;
542
Richard Smitha3d3bd22013-05-08 02:12:03 +0000543 /// StepsLeft - The remaining number of evaluation steps we're permitted
544 /// to perform. This is essentially a limit for the number of statements
545 /// we will evaluate.
546 unsigned StepsLeft;
547
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000548 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000549 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000550 CallStackFrame BottomFrame;
551
Richard Smith08d6a2c2013-07-24 07:11:57 +0000552 /// A stack of values whose lifetimes end at the end of some surrounding
553 /// evaluation frame.
554 llvm::SmallVector<Cleanup, 16> CleanupStack;
555
Richard Smithd62306a2011-11-10 06:34:14 +0000556 /// EvaluatingDecl - This is the declaration whose initializer is being
557 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000558 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000559
560 /// EvaluatingDeclValue - This is the value being constructed for the
561 /// declaration whose initializer is being evaluated, if any.
562 APValue *EvaluatingDeclValue;
563
Richard Smith410306b2016-12-12 02:53:20 +0000564 /// The current array initialization index, if we're performing array
565 /// initialization.
566 uint64_t ArrayInitIndex = -1;
567
Richard Smith357362d2011-12-13 06:39:58 +0000568 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
569 /// notes attached to it will also be stored, otherwise they will not be.
570 bool HasActiveDiagnostic;
571
Richard Smith0c6124b2015-12-03 01:36:22 +0000572 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
573 /// fold (not just why it's not strictly a constant expression)?
574 bool HasFoldFailureDiagnostic;
575
George Burgess IV8c892b52016-05-25 22:31:54 +0000576 /// \brief Whether or not we're currently speculatively evaluating.
577 bool IsSpeculativelyEvaluating;
578
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 enum EvaluationMode {
580 /// Evaluate as a constant expression. Stop if we find that the expression
581 /// is not a constant expression.
582 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000583
Richard Smith6d4c6582013-11-05 22:18:15 +0000584 /// Evaluate as a potential constant expression. Keep going if we hit a
585 /// construct that we can't evaluate yet (because we don't yet know the
586 /// value of something) but stop if we hit something that could never be
587 /// a constant expression.
588 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000589
Richard Smith6d4c6582013-11-05 22:18:15 +0000590 /// Fold the expression to a constant. Stop if we hit a side-effect that
591 /// we can't model.
592 EM_ConstantFold,
593
594 /// Evaluate the expression looking for integer overflow and similar
595 /// issues. Don't worry about side-effects, and try to visit all
596 /// subexpressions.
597 EM_EvaluateForOverflow,
598
599 /// Evaluate in any way we know how. Don't worry about side-effects that
600 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000601 EM_IgnoreSideEffects,
602
603 /// Evaluate as a constant expression. Stop if we find that the expression
604 /// is not a constant expression. Some expressions can be retried in the
605 /// optimizer if we don't constant fold them here, but in an unevaluated
606 /// context we try to fold them immediately since the optimizer never
607 /// gets a chance to look at it.
608 EM_ConstantExpressionUnevaluated,
609
610 /// Evaluate as a potential constant expression. Keep going if we hit a
611 /// construct that we can't evaluate yet (because we don't yet know the
612 /// value of something) but stop if we hit something that could never be
613 /// a constant expression. Some expressions can be retried in the
614 /// optimizer if we don't constant fold them here, but in an unevaluated
615 /// context we try to fold them immediately since the optimizer never
616 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000617 EM_PotentialConstantExpressionUnevaluated,
618
George Burgess IVe3763372016-12-22 02:50:20 +0000619 /// Evaluate as a constant expression. Continue evaluating if either:
620 /// - We find a MemberExpr with a base that can't be evaluated.
621 /// - We find a variable initialized with a call to a function that has
622 /// the alloc_size attribute on it.
623 /// In either case, the LValue returned shall have an invalid base; in the
624 /// former, the base will be the invalid MemberExpr, in the latter, the
625 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
626 /// said CallExpr.
627 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000628 } EvalMode;
629
630 /// Are we checking whether the expression is a potential constant
631 /// expression?
632 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000633 return EvalMode == EM_PotentialConstantExpression ||
634 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000635 }
636
637 /// Are we checking an expression for overflow?
638 // FIXME: We should check for any kind of undefined or suspicious behavior
639 // in such constructs, not just overflow.
640 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
641
642 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000643 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000644 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000645 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000646 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
647 EvaluatingDecl((const ValueDecl *)nullptr),
648 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000649 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
650 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000651
Richard Smith7525ff62013-05-09 07:14:00 +0000652 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
653 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000654 EvaluatingDeclValue = &Value;
655 }
656
David Blaikiebbafb8a2012-03-11 07:00:24 +0000657 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000658
Richard Smith357362d2011-12-13 06:39:58 +0000659 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000660 // Don't perform any constexpr calls (other than the call we're checking)
661 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000662 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000663 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000664 if (NextCallIndex == 0) {
665 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000666 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000667 return false;
668 }
Richard Smith357362d2011-12-13 06:39:58 +0000669 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
670 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000671 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000672 << getLangOpts().ConstexprCallDepth;
673 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000674 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000675
Richard Smithb228a862012-02-15 02:18:13 +0000676 CallStackFrame *getCallFrame(unsigned CallIndex) {
677 assert(CallIndex && "no call index in getCallFrame");
678 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
679 // be null in this loop.
680 CallStackFrame *Frame = CurrentCall;
681 while (Frame->Index > CallIndex)
682 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000683 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000684 }
685
Richard Smitha3d3bd22013-05-08 02:12:03 +0000686 bool nextStep(const Stmt *S) {
687 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000688 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000689 return false;
690 }
691 --StepsLeft;
692 return true;
693 }
694
Richard Smith357362d2011-12-13 06:39:58 +0000695 private:
696 /// Add a diagnostic to the diagnostics list.
697 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
698 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
699 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
700 return EvalStatus.Diag->back().second;
701 }
702
Richard Smithf6f003a2011-12-16 19:06:07 +0000703 /// Add notes containing a call stack to the current point of evaluation.
704 void addCallStack(unsigned Limit);
705
Faisal Valie690b7a2016-07-02 22:34:24 +0000706 private:
707 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
708 unsigned ExtraNotes, bool IsCCEDiag) {
709
Richard Smith92b1ce02011-12-12 09:28:41 +0000710 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 // If we have a prior diagnostic, it will be noting that the expression
712 // isn't a constant expression. This diagnostic is more important,
713 // unless we require this evaluation to produce a constant expression.
714 //
715 // FIXME: We might want to show both diagnostics to the user in
716 // EM_ConstantFold mode.
717 if (!EvalStatus.Diag->empty()) {
718 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000719 case EM_ConstantFold:
720 case EM_IgnoreSideEffects:
721 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000722 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000723 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000724 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 case EM_ConstantExpression:
726 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000727 case EM_ConstantExpressionUnevaluated:
728 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000729 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 HasActiveDiagnostic = false;
731 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000732 }
733 }
734
Richard Smithf6f003a2011-12-16 19:06:07 +0000735 unsigned CallStackNotes = CallStackDepth - 1;
736 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
737 if (Limit)
738 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000740 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000741
Richard Smith357362d2011-12-13 06:39:58 +0000742 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000743 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000744 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000745 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
746 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000748 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000749 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000750 }
Richard Smith357362d2011-12-13 06:39:58 +0000751 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000752 return OptionalDiagnostic();
753 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000754 public:
755 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
756 OptionalDiagnostic
757 FFDiag(SourceLocation Loc,
758 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
759 unsigned ExtraNotes = 0) {
760 return Diag(Loc, DiagId, ExtraNotes, false);
761 }
762
763 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000764 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000767 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000768 HasActiveDiagnostic = false;
769 return OptionalDiagnostic();
770 }
771
Richard Smith92b1ce02011-12-12 09:28:41 +0000772 /// Diagnose that the evaluation does not produce a C++11 core constant
773 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000774 ///
775 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
776 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000777 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000778 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000779 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000780 // Don't override a previous diagnostic. Don't bother collecting
781 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000782 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000783 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000784 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000785 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000786 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000787 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000788 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
789 = diag::note_invalid_subexpr_in_const_expr,
790 unsigned ExtraNotes = 0) {
791 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
792 }
Richard Smith357362d2011-12-13 06:39:58 +0000793 /// Add a note to a prior diagnostic.
794 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
795 if (!HasActiveDiagnostic)
796 return OptionalDiagnostic();
797 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000798 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000799
800 /// Add a stack of notes to a prior diagnostic.
801 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
802 if (HasActiveDiagnostic) {
803 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
804 Diags.begin(), Diags.end());
805 }
806 }
Richard Smith253c2a32012-01-27 01:14:48 +0000807
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 /// Should we continue evaluation after encountering a side-effect that we
809 /// couldn't model?
810 bool keepEvaluatingAfterSideEffect() {
811 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000812 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000813 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000814 case EM_EvaluateForOverflow:
815 case EM_IgnoreSideEffects:
816 return true;
817
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000819 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000820 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000821 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 return false;
823 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000824 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 }
826
827 /// Note that we have had a side-effect, and determine whether we should
828 /// keep evaluating.
829 bool noteSideEffect() {
830 EvalStatus.HasSideEffects = true;
831 return keepEvaluatingAfterSideEffect();
832 }
833
Richard Smithce8eca52015-12-08 03:21:47 +0000834 /// Should we continue evaluation after encountering undefined behavior?
835 bool keepEvaluatingAfterUndefinedBehavior() {
836 switch (EvalMode) {
837 case EM_EvaluateForOverflow:
838 case EM_IgnoreSideEffects:
839 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000840 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000841 return true;
842
843 case EM_PotentialConstantExpression:
844 case EM_PotentialConstantExpressionUnevaluated:
845 case EM_ConstantExpression:
846 case EM_ConstantExpressionUnevaluated:
847 return false;
848 }
849 llvm_unreachable("Missed EvalMode case");
850 }
851
852 /// Note that we hit something that was technically undefined behavior, but
853 /// that we can evaluate past it (such as signed overflow or floating-point
854 /// division by zero.)
855 bool noteUndefinedBehavior() {
856 EvalStatus.HasUndefinedBehavior = true;
857 return keepEvaluatingAfterUndefinedBehavior();
858 }
859
Richard Smith253c2a32012-01-27 01:14:48 +0000860 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000861 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000862 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000863 if (!StepsLeft)
864 return false;
865
866 switch (EvalMode) {
867 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000868 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000869 case EM_EvaluateForOverflow:
870 return true;
871
872 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000873 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 case EM_ConstantFold:
875 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000876 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000877 return false;
878 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000879 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000880 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000881
George Burgess IV8c892b52016-05-25 22:31:54 +0000882 /// Notes that we failed to evaluate an expression that other expressions
883 /// directly depend on, and determine if we should keep evaluating. This
884 /// should only be called if we actually intend to keep evaluating.
885 ///
886 /// Call noteSideEffect() instead if we may be able to ignore the value that
887 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
888 ///
889 /// (Foo(), 1) // use noteSideEffect
890 /// (Foo() || true) // use noteSideEffect
891 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000892 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000893 // Failure when evaluating some expression often means there is some
894 // subexpression whose evaluation was skipped. Therefore, (because we
895 // don't track whether we skipped an expression when unwinding after an
896 // evaluation failure) every evaluation failure that bubbles up from a
897 // subexpression implies that a side-effect has potentially happened. We
898 // skip setting the HasSideEffects flag to true until we decide to
899 // continue evaluating after that point, which happens here.
900 bool KeepGoing = keepEvaluatingAfterFailure();
901 EvalStatus.HasSideEffects |= KeepGoing;
902 return KeepGoing;
903 }
904
George Burgess IV3a03fab2015-09-04 21:28:13 +0000905 bool allowInvalidBaseExpr() const {
George Burgess IVe3763372016-12-22 02:50:20 +0000906 return EvalMode == EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000907 }
Richard Smith410306b2016-12-12 02:53:20 +0000908
909 class ArrayInitLoopIndex {
910 EvalInfo &Info;
911 uint64_t OuterIndex;
912
913 public:
914 ArrayInitLoopIndex(EvalInfo &Info)
915 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
916 Info.ArrayInitIndex = 0;
917 }
918 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
919
920 operator uint64_t&() { return Info.ArrayInitIndex; }
921 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000922 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000923
924 /// Object used to treat all foldable expressions as constant expressions.
925 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000926 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000927 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000928 bool HadNoPriorDiags;
929 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000930
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 explicit FoldConstant(EvalInfo &Info, bool Enabled)
932 : Info(Info),
933 Enabled(Enabled),
934 HadNoPriorDiags(Info.EvalStatus.Diag &&
935 Info.EvalStatus.Diag->empty() &&
936 !Info.EvalStatus.HasSideEffects),
937 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 if (Enabled &&
939 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
940 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000942 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 void keepDiagnostics() { Enabled = false; }
944 ~FoldConstant() {
945 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000946 !Info.EvalStatus.HasSideEffects)
947 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000948 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000949 }
950 };
Richard Smith17100ba2012-02-16 02:46:34 +0000951
George Burgess IV3a03fab2015-09-04 21:28:13 +0000952 /// RAII object used to treat the current evaluation as the correct pointer
953 /// offset fold for the current EvalMode
954 struct FoldOffsetRAII {
955 EvalInfo &Info;
956 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000957 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000958 : Info(Info), OldMode(Info.EvalMode) {
959 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000960 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000961 }
962
963 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
964 };
965
George Burgess IV8c892b52016-05-25 22:31:54 +0000966 /// RAII object used to optionally suppress diagnostics and side-effects from
967 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000968 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000969 /// Pair of EvalInfo, and a bit that stores whether or not we were
970 /// speculatively evaluating when we created this RAII.
971 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000972 Expr::EvalStatus Old;
973
George Burgess IV8c892b52016-05-25 22:31:54 +0000974 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
975 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
976 Old = Other.Old;
977 Other.InfoAndOldSpecEval.setPointer(nullptr);
978 }
979
980 void maybeRestoreState() {
981 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
982 if (!Info)
983 return;
984
985 Info->EvalStatus = Old;
986 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
987 }
988
Richard Smith17100ba2012-02-16 02:46:34 +0000989 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000990 SpeculativeEvaluationRAII() = default;
991
992 SpeculativeEvaluationRAII(
993 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
994 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
995 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000996 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000997 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000998 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000999
1000 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1001 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1002 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001003 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001004
1005 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1006 maybeRestoreState();
1007 moveFromAndCancel(std::move(Other));
1008 return *this;
1009 }
1010
1011 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001012 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001013
1014 /// RAII object wrapping a full-expression or block scope, and handling
1015 /// the ending of the lifetime of temporaries created within it.
1016 template<bool IsFullExpression>
1017 class ScopeRAII {
1018 EvalInfo &Info;
1019 unsigned OldStackSize;
1020 public:
1021 ScopeRAII(EvalInfo &Info)
1022 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1023 ~ScopeRAII() {
1024 // Body moved to a static method to encourage the compiler to inline away
1025 // instances of this class.
1026 cleanup(Info, OldStackSize);
1027 }
1028 private:
1029 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1030 unsigned NewEnd = OldStackSize;
1031 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1032 I != N; ++I) {
1033 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1034 // Full-expression cleanup of a lifetime-extended temporary: nothing
1035 // to do, just move this cleanup to the right place in the stack.
1036 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1037 ++NewEnd;
1038 } else {
1039 // End the lifetime of the object.
1040 Info.CleanupStack[I].endLifetime();
1041 }
1042 }
1043 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1044 Info.CleanupStack.end());
1045 }
1046 };
1047 typedef ScopeRAII<false> BlockScopeRAII;
1048 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001049}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001050
Richard Smitha8105bc2012-01-06 16:39:00 +00001051bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1052 CheckSubobjectKind CSK) {
1053 if (Invalid)
1054 return false;
1055 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001056 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001057 << CSK;
1058 setInvalid();
1059 return false;
1060 }
1061 return true;
1062}
1063
1064void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Richard Smithd6cc1982017-01-31 02:23:02 +00001065 const Expr *E, APSInt N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001066 // If we're complaining, we must be able to statically determine the size of
1067 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001068 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001069 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001070 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001071 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001072 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001073 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001074 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001075 setInvalid();
1076}
1077
Richard Smithf6f003a2011-12-16 19:06:07 +00001078CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1079 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001080 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001081 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1082 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001083 Info.CurrentCall = this;
1084 ++Info.CallStackDepth;
1085}
1086
1087CallStackFrame::~CallStackFrame() {
1088 assert(Info.CurrentCall == this && "calls retired out of order");
1089 --Info.CallStackDepth;
1090 Info.CurrentCall = Caller;
1091}
1092
Richard Smith08d6a2c2013-07-24 07:11:57 +00001093APValue &CallStackFrame::createTemporary(const void *Key,
1094 bool IsLifetimeExtended) {
1095 APValue &Result = Temporaries[Key];
1096 assert(Result.isUninit() && "temporary created multiple times");
1097 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1098 return Result;
1099}
1100
Richard Smith84401042013-06-03 05:03:02 +00001101static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001102
1103void EvalInfo::addCallStack(unsigned Limit) {
1104 // Determine which calls to skip, if any.
1105 unsigned ActiveCalls = CallStackDepth - 1;
1106 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1107 if (Limit && Limit < ActiveCalls) {
1108 SkipStart = Limit / 2 + Limit % 2;
1109 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001110 }
1111
Richard Smithf6f003a2011-12-16 19:06:07 +00001112 // Walk the call stack and add the diagnostics.
1113 unsigned CallIdx = 0;
1114 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1115 Frame = Frame->Caller, ++CallIdx) {
1116 // Skip this call?
1117 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1118 if (CallIdx == SkipStart) {
1119 // Note that we're skipping calls.
1120 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1121 << unsigned(ActiveCalls - Limit);
1122 }
1123 continue;
1124 }
1125
Richard Smith5179eb72016-06-28 19:03:57 +00001126 // Use a different note for an inheriting constructor, because from the
1127 // user's perspective it's not really a function at all.
1128 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1129 if (CD->isInheritingConstructor()) {
1130 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1131 << CD->getParent();
1132 continue;
1133 }
1134 }
1135
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001136 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001137 llvm::raw_svector_ostream Out(Buffer);
1138 describeCall(Frame, Out);
1139 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1140 }
1141}
1142
1143namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001144 struct ComplexValue {
1145 private:
1146 bool IsInt;
1147
1148 public:
1149 APSInt IntReal, IntImag;
1150 APFloat FloatReal, FloatImag;
1151
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001152 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001153
1154 void makeComplexFloat() { IsInt = false; }
1155 bool isComplexFloat() const { return !IsInt; }
1156 APFloat &getComplexFloatReal() { return FloatReal; }
1157 APFloat &getComplexFloatImag() { return FloatImag; }
1158
1159 void makeComplexInt() { IsInt = true; }
1160 bool isComplexInt() const { return IsInt; }
1161 APSInt &getComplexIntReal() { return IntReal; }
1162 APSInt &getComplexIntImag() { return IntImag; }
1163
Richard Smith2e312c82012-03-03 22:46:17 +00001164 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001165 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001166 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001167 else
Richard Smith2e312c82012-03-03 22:46:17 +00001168 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001169 }
Richard Smith2e312c82012-03-03 22:46:17 +00001170 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001171 assert(v.isComplexFloat() || v.isComplexInt());
1172 if (v.isComplexFloat()) {
1173 makeComplexFloat();
1174 FloatReal = v.getComplexFloatReal();
1175 FloatImag = v.getComplexFloatImag();
1176 } else {
1177 makeComplexInt();
1178 IntReal = v.getComplexIntReal();
1179 IntImag = v.getComplexIntImag();
1180 }
1181 }
John McCall93d91dc2010-05-07 17:22:02 +00001182 };
John McCall45d55e42010-05-07 21:00:08 +00001183
1184 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001185 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001186 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001187 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001188 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001189 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001190 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001191
Richard Smithce40ad62011-11-12 22:28:03 +00001192 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001193 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001194 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001195 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001196 SubobjectDesignator &getLValueDesignator() { return Designator; }
1197 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001198 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001199
Richard Smith2e312c82012-03-03 22:46:17 +00001200 void moveInto(APValue &V) const {
1201 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001202 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1203 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001204 else {
1205 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1206 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1207 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001208 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001210 }
John McCall45d55e42010-05-07 21:00:08 +00001211 }
Richard Smith2e312c82012-03-03 22:46:17 +00001212 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001213 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001214 Base = V.getLValueBase();
1215 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001216 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001217 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001218 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001219 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001220 }
1221
Yaxun Liu402804b2016-12-15 08:09:08 +00001222 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1223 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001224#ifndef NDEBUG
1225 // We only allow a few types of invalid bases. Enforce that here.
1226 if (BInvalid) {
1227 const auto *E = B.get<const Expr *>();
1228 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1229 "Unexpected type of invalid base");
1230 }
1231#endif
1232
Richard Smithce40ad62011-11-12 22:28:03 +00001233 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001234 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001235 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001236 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001237 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001238 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001239 }
1240
George Burgess IV3a03fab2015-09-04 21:28:13 +00001241 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1242 set(B, I, true);
1243 }
1244
Richard Smitha8105bc2012-01-06 16:39:00 +00001245 // Check that this LValue is not based on a null pointer. If it is, produce
1246 // a diagnostic and mark the designator as invalid.
1247 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1248 CheckSubobjectKind CSK) {
1249 if (Designator.Invalid)
1250 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001251 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001252 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001253 << CSK;
1254 Designator.setInvalid();
1255 return false;
1256 }
1257 return true;
1258 }
1259
1260 // Check this LValue refers to an object. If not, set the designator to be
1261 // invalid and emit a diagnostic.
1262 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001263 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 Designator.checkSubobject(Info, E, CSK);
1265 }
1266
1267 void addDecl(EvalInfo &Info, const Expr *E,
1268 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001269 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1270 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001271 }
George Burgess IVe3763372016-12-22 02:50:20 +00001272 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1273 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1274 assert(isBaseAnAllocSizeCall(Base) &&
1275 "Only alloc_size bases can have unsized arrays");
1276 Designator.FirstEntryIsAnUnsizedArray = true;
1277 Designator.addUnsizedArrayUnchecked(ElemTy);
1278 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001279 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001280 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1281 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001282 }
Richard Smith66c96992012-02-18 22:04:06 +00001283 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001284 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1285 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001286 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001287 void clearIsNullPointer() {
1288 IsNullPtr = false;
1289 }
Richard Smithd6cc1982017-01-31 02:23:02 +00001290 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
Yaxun Liu402804b2016-12-15 08:09:08 +00001291 CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001292 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1293 // but we're not required to diagnose it and it's valid in C++.)
1294 if (!Index)
1295 return;
1296
1297 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1298 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1299 // offsets.
1300 uint64_t Offset64 = Offset.getQuantity();
1301 uint64_t ElemSize64 = ElementSize.getQuantity();
1302 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1303 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1304
1305 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001306 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001307 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001308 }
1309 void adjustOffset(CharUnits N) {
1310 Offset += N;
1311 if (N.getQuantity())
1312 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001313 }
John McCall45d55e42010-05-07 21:00:08 +00001314 };
Richard Smith027bf112011-11-17 22:56:20 +00001315
1316 struct MemberPtr {
1317 MemberPtr() {}
1318 explicit MemberPtr(const ValueDecl *Decl) :
1319 DeclAndIsDerivedMember(Decl, false), Path() {}
1320
1321 /// The member or (direct or indirect) field referred to by this member
1322 /// pointer, or 0 if this is a null member pointer.
1323 const ValueDecl *getDecl() const {
1324 return DeclAndIsDerivedMember.getPointer();
1325 }
1326 /// Is this actually a member of some type derived from the relevant class?
1327 bool isDerivedMember() const {
1328 return DeclAndIsDerivedMember.getInt();
1329 }
1330 /// Get the class which the declaration actually lives in.
1331 const CXXRecordDecl *getContainingRecord() const {
1332 return cast<CXXRecordDecl>(
1333 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1334 }
1335
Richard Smith2e312c82012-03-03 22:46:17 +00001336 void moveInto(APValue &V) const {
1337 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001338 }
Richard Smith2e312c82012-03-03 22:46:17 +00001339 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001340 assert(V.isMemberPointer());
1341 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1342 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1343 Path.clear();
1344 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1345 Path.insert(Path.end(), P.begin(), P.end());
1346 }
1347
1348 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1349 /// whether the member is a member of some class derived from the class type
1350 /// of the member pointer.
1351 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1352 /// Path - The path of base/derived classes from the member declaration's
1353 /// class (exclusive) to the class type of the member pointer (inclusive).
1354 SmallVector<const CXXRecordDecl*, 4> Path;
1355
1356 /// Perform a cast towards the class of the Decl (either up or down the
1357 /// hierarchy).
1358 bool castBack(const CXXRecordDecl *Class) {
1359 assert(!Path.empty());
1360 const CXXRecordDecl *Expected;
1361 if (Path.size() >= 2)
1362 Expected = Path[Path.size() - 2];
1363 else
1364 Expected = getContainingRecord();
1365 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1366 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1367 // if B does not contain the original member and is not a base or
1368 // derived class of the class containing the original member, the result
1369 // of the cast is undefined.
1370 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1371 // (D::*). We consider that to be a language defect.
1372 return false;
1373 }
1374 Path.pop_back();
1375 return true;
1376 }
1377 /// Perform a base-to-derived member pointer cast.
1378 bool castToDerived(const CXXRecordDecl *Derived) {
1379 if (!getDecl())
1380 return true;
1381 if (!isDerivedMember()) {
1382 Path.push_back(Derived);
1383 return true;
1384 }
1385 if (!castBack(Derived))
1386 return false;
1387 if (Path.empty())
1388 DeclAndIsDerivedMember.setInt(false);
1389 return true;
1390 }
1391 /// Perform a derived-to-base member pointer cast.
1392 bool castToBase(const CXXRecordDecl *Base) {
1393 if (!getDecl())
1394 return true;
1395 if (Path.empty())
1396 DeclAndIsDerivedMember.setInt(true);
1397 if (isDerivedMember()) {
1398 Path.push_back(Base);
1399 return true;
1400 }
1401 return castBack(Base);
1402 }
1403 };
Richard Smith357362d2011-12-13 06:39:58 +00001404
Richard Smith7bb00672012-02-01 01:42:44 +00001405 /// Compare two member pointers, which are assumed to be of the same type.
1406 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1407 if (!LHS.getDecl() || !RHS.getDecl())
1408 return !LHS.getDecl() && !RHS.getDecl();
1409 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1410 return false;
1411 return LHS.Path == RHS.Path;
1412 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001413}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001414
Richard Smith2e312c82012-03-03 22:46:17 +00001415static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001416static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1417 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001418 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001419static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1420static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001421static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1422 EvalInfo &Info);
1423static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001424static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001425static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001426 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001427static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001428static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001429static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001430static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001431
1432//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001433// Misc utilities
1434//===----------------------------------------------------------------------===//
1435
Richard Smithd6cc1982017-01-31 02:23:02 +00001436/// Negate an APSInt in place, converting it to a signed form if necessary, and
1437/// preserving its value (by extending by up to one bit as needed).
1438static void negateAsSigned(APSInt &Int) {
1439 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1440 Int = Int.extend(Int.getBitWidth() + 1);
1441 Int.setIsSigned(true);
1442 }
1443 Int = -Int;
1444}
1445
Richard Smith84401042013-06-03 05:03:02 +00001446/// Produce a string describing the given constexpr call.
1447static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1448 unsigned ArgIndex = 0;
1449 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1450 !isa<CXXConstructorDecl>(Frame->Callee) &&
1451 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1452
1453 if (!IsMemberCall)
1454 Out << *Frame->Callee << '(';
1455
1456 if (Frame->This && IsMemberCall) {
1457 APValue Val;
1458 Frame->This->moveInto(Val);
1459 Val.printPretty(Out, Frame->Info.Ctx,
1460 Frame->This->Designator.MostDerivedType);
1461 // FIXME: Add parens around Val if needed.
1462 Out << "->" << *Frame->Callee << '(';
1463 IsMemberCall = false;
1464 }
1465
1466 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1467 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1468 if (ArgIndex > (unsigned)IsMemberCall)
1469 Out << ", ";
1470
1471 const ParmVarDecl *Param = *I;
1472 const APValue &Arg = Frame->Arguments[ArgIndex];
1473 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1474
1475 if (ArgIndex == 0 && IsMemberCall)
1476 Out << "->" << *Frame->Callee << '(';
1477 }
1478
1479 Out << ')';
1480}
1481
Richard Smithd9f663b2013-04-22 15:31:51 +00001482/// Evaluate an expression to see if it had side-effects, and discard its
1483/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001484/// \return \c true if the caller should keep evaluating.
1485static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001487 if (!Evaluate(Scratch, Info, E))
1488 // We don't need the value, but we might have skipped a side effect here.
1489 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001490 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001491}
1492
Richard Smithd62306a2011-11-10 06:34:14 +00001493/// Should this call expression be treated as a string literal?
1494static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001495 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001496 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1497 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1498}
1499
Richard Smithce40ad62011-11-12 22:28:03 +00001500static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001501 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1502 // constant expression of pointer type that evaluates to...
1503
1504 // ... a null pointer value, or a prvalue core constant expression of type
1505 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001506 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001507
Richard Smithce40ad62011-11-12 22:28:03 +00001508 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1509 // ... the address of an object with static storage duration,
1510 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1511 return VD->hasGlobalStorage();
1512 // ... the address of a function,
1513 return isa<FunctionDecl>(D);
1514 }
1515
1516 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001517 switch (E->getStmtClass()) {
1518 default:
1519 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001520 case Expr::CompoundLiteralExprClass: {
1521 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1522 return CLE->isFileScope() && CLE->isLValue();
1523 }
Richard Smithe6c01442013-06-05 00:46:14 +00001524 case Expr::MaterializeTemporaryExprClass:
1525 // A materialized temporary might have been lifetime-extended to static
1526 // storage duration.
1527 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001528 // A string literal has static storage duration.
1529 case Expr::StringLiteralClass:
1530 case Expr::PredefinedExprClass:
1531 case Expr::ObjCStringLiteralClass:
1532 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001533 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001534 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001535 return true;
1536 case Expr::CallExprClass:
1537 return IsStringLiteralCall(cast<CallExpr>(E));
1538 // For GCC compatibility, &&label has static storage duration.
1539 case Expr::AddrLabelExprClass:
1540 return true;
1541 // A Block literal expression may be used as the initialization value for
1542 // Block variables at global or local static scope.
1543 case Expr::BlockExprClass:
1544 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001545 case Expr::ImplicitValueInitExprClass:
1546 // FIXME:
1547 // We can never form an lvalue with an implicit value initialization as its
1548 // base through expression evaluation, so these only appear in one case: the
1549 // implicit variable declaration we invent when checking whether a constexpr
1550 // constructor can produce a constant expression. We must assume that such
1551 // an expression might be a global lvalue.
1552 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001553 }
John McCall95007602010-05-10 23:27:23 +00001554}
1555
Richard Smithb228a862012-02-15 02:18:13 +00001556static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1557 assert(Base && "no location for a null lvalue");
1558 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1559 if (VD)
1560 Info.Note(VD->getLocation(), diag::note_declared_at);
1561 else
Ted Kremenek28831752012-08-23 20:46:57 +00001562 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001563 diag::note_constexpr_temporary_here);
1564}
1565
Richard Smith80815602011-11-07 05:07:52 +00001566/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001567/// value for an address or reference constant expression. Return true if we
1568/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001569static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1570 QualType Type, const LValue &LVal) {
1571 bool IsReferenceType = Type->isReferenceType();
1572
Richard Smith357362d2011-12-13 06:39:58 +00001573 APValue::LValueBase Base = LVal.getLValueBase();
1574 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1575
Richard Smith0dea49e2012-02-18 04:58:18 +00001576 // Check that the object is a global. Note that the fake 'this' object we
1577 // manufacture when checking potential constant expressions is conservatively
1578 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001579 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001580 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001581 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001582 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001583 << IsReferenceType << !Designator.Entries.empty()
1584 << !!VD << VD;
1585 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001586 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001587 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001588 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001589 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001590 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001591 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001592 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001593 LVal.getLValueCallIndex() == 0) &&
1594 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001595
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001596 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1597 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001598 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001599 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001600 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001601
Hans Wennborg82dd8772014-06-25 22:19:48 +00001602 // A dllimport variable never acts like a constant.
1603 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001604 return false;
1605 }
1606 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1607 // __declspec(dllimport) must be handled very carefully:
1608 // We must never initialize an expression with the thunk in C++.
1609 // Doing otherwise would allow the same id-expression to yield
1610 // different addresses for the same function in different translation
1611 // units. However, this means that we must dynamically initialize the
1612 // expression with the contents of the import address table at runtime.
1613 //
1614 // The C language has no notion of ODR; furthermore, it has no notion of
1615 // dynamic initialization. This means that we are permitted to
1616 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001617 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001618 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001619 }
1620 }
1621
Richard Smitha8105bc2012-01-06 16:39:00 +00001622 // Allow address constant expressions to be past-the-end pointers. This is
1623 // an extension: the standard requires them to point to an object.
1624 if (!IsReferenceType)
1625 return true;
1626
1627 // A reference constant expression must refer to an object.
1628 if (!Base) {
1629 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001630 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001631 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001632 }
1633
Richard Smith357362d2011-12-13 06:39:58 +00001634 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001635 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001636 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001637 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001638 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001639 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001640 }
1641
Richard Smith80815602011-11-07 05:07:52 +00001642 return true;
1643}
1644
Richard Smithfddd3842011-12-30 21:15:51 +00001645/// Check that this core constant expression is of literal type, and if not,
1646/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001647static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001648 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001649 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001650 return true;
1651
Richard Smith7525ff62013-05-09 07:14:00 +00001652 // C++1y: A constant initializer for an object o [...] may also invoke
1653 // constexpr constructors for o and its subobjects even if those objects
1654 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001655 //
1656 // C++11 missed this detail for aggregates, so classes like this:
1657 // struct foo_t { union { int i; volatile int j; } u; };
1658 // are not (obviously) initializable like so:
1659 // __attribute__((__require_constant_initialization__))
1660 // static const foo_t x = {{0}};
1661 // because "i" is a subobject with non-literal initialization (due to the
1662 // volatile member of the union). See:
1663 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1664 // Therefore, we use the C++1y behavior.
1665 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001666 return true;
1667
Richard Smithfddd3842011-12-30 21:15:51 +00001668 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001669 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001670 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001671 << E->getType();
1672 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001673 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001674 return false;
1675}
1676
Richard Smith0b0a0b62011-10-29 20:57:55 +00001677/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001678/// constant expression. If not, report an appropriate diagnostic. Does not
1679/// check that the expression is of literal type.
1680static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1681 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001682 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001683 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001684 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001685 return false;
1686 }
1687
Richard Smith77be48a2014-07-31 06:31:19 +00001688 // We allow _Atomic(T) to be initialized from anything that T can be
1689 // initialized from.
1690 if (const AtomicType *AT = Type->getAs<AtomicType>())
1691 Type = AT->getValueType();
1692
Richard Smithb228a862012-02-15 02:18:13 +00001693 // Core issue 1454: For a literal constant expression of array or class type,
1694 // each subobject of its value shall have been initialized by a constant
1695 // expression.
1696 if (Value.isArray()) {
1697 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1698 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1699 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1700 Value.getArrayInitializedElt(I)))
1701 return false;
1702 }
1703 if (!Value.hasArrayFiller())
1704 return true;
1705 return CheckConstantExpression(Info, DiagLoc, EltTy,
1706 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001707 }
Richard Smithb228a862012-02-15 02:18:13 +00001708 if (Value.isUnion() && Value.getUnionField()) {
1709 return CheckConstantExpression(Info, DiagLoc,
1710 Value.getUnionField()->getType(),
1711 Value.getUnionValue());
1712 }
1713 if (Value.isStruct()) {
1714 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1715 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1716 unsigned BaseIndex = 0;
1717 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1718 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1719 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1720 Value.getStructBase(BaseIndex)))
1721 return false;
1722 }
1723 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001724 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001725 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1726 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001727 return false;
1728 }
1729 }
1730
1731 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001732 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001733 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001734 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1735 }
1736
1737 // Everything else is fine.
1738 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001739}
1740
Benjamin Kramer8407df72015-03-09 16:47:52 +00001741static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001742 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001743}
1744
1745static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001746 if (Value.CallIndex)
1747 return false;
1748 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1749 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001750}
1751
Richard Smithcecf1842011-11-01 21:06:14 +00001752static bool IsWeakLValue(const LValue &Value) {
1753 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001754 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001755}
1756
David Majnemerb5116032014-12-09 23:32:34 +00001757static bool isZeroSized(const LValue &Value) {
1758 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001759 if (Decl && isa<VarDecl>(Decl)) {
1760 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001761 if (Ty->isArrayType())
1762 return Ty->isIncompleteType() ||
1763 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001764 }
1765 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001766}
1767
Richard Smith2e312c82012-03-03 22:46:17 +00001768static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001769 // A null base expression indicates a null pointer. These are always
1770 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001771 if (!Value.getLValueBase()) {
1772 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001773 return true;
1774 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001775
Richard Smith027bf112011-11-17 22:56:20 +00001776 // We have a non-null base. These are generally known to be true, but if it's
1777 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001778 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001779 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001780 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001781}
1782
Richard Smith2e312c82012-03-03 22:46:17 +00001783static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001784 switch (Val.getKind()) {
1785 case APValue::Uninitialized:
1786 return false;
1787 case APValue::Int:
1788 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001789 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001790 case APValue::Float:
1791 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001792 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001793 case APValue::ComplexInt:
1794 Result = Val.getComplexIntReal().getBoolValue() ||
1795 Val.getComplexIntImag().getBoolValue();
1796 return true;
1797 case APValue::ComplexFloat:
1798 Result = !Val.getComplexFloatReal().isZero() ||
1799 !Val.getComplexFloatImag().isZero();
1800 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001801 case APValue::LValue:
1802 return EvalPointerValueAsBool(Val, Result);
1803 case APValue::MemberPointer:
1804 Result = Val.getMemberPointerDecl();
1805 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001806 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001807 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001808 case APValue::Struct:
1809 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001810 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001811 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001812 }
1813
Richard Smith11562c52011-10-28 17:51:58 +00001814 llvm_unreachable("unknown APValue kind");
1815}
1816
1817static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1818 EvalInfo &Info) {
1819 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001820 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001821 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001822 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001823 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001824}
1825
Richard Smith357362d2011-12-13 06:39:58 +00001826template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001827static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001828 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001829 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001830 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001831 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001832}
1833
1834static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1835 QualType SrcType, const APFloat &Value,
1836 QualType DestType, APSInt &Result) {
1837 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001838 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001839 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001840
Richard Smith357362d2011-12-13 06:39:58 +00001841 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001842 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001843 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1844 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001845 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001846 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001847}
1848
Richard Smith357362d2011-12-13 06:39:58 +00001849static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1850 QualType SrcType, QualType DestType,
1851 APFloat &Result) {
1852 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001853 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001854 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1855 APFloat::rmNearestTiesToEven, &ignored)
1856 & APFloat::opOverflow)
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 Smith911e1422012-01-30 22:27:01 +00001861static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1862 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001863 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001864 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001865 APSInt Result = Value;
1866 // Figure out if this is a truncate, extend or noop cast.
1867 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001868 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001869 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001870 return Result;
1871}
1872
Richard Smith357362d2011-12-13 06:39:58 +00001873static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1874 QualType SrcType, const APSInt &Value,
1875 QualType DestType, APFloat &Result) {
1876 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1877 if (Result.convertFromAPInt(Value, Value.isSigned(),
1878 APFloat::rmNearestTiesToEven)
1879 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001880 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001881 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001882}
1883
Richard Smith49ca8aa2013-08-06 07:09:20 +00001884static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1885 APValue &Value, const FieldDecl *FD) {
1886 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1887
1888 if (!Value.isInt()) {
1889 // Trying to store a pointer-cast-to-integer into a bitfield.
1890 // FIXME: In this case, we should provide the diagnostic for casting
1891 // a pointer to an integer.
1892 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001893 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001894 return false;
1895 }
1896
1897 APSInt &Int = Value.getInt();
1898 unsigned OldBitWidth = Int.getBitWidth();
1899 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1900 if (NewBitWidth < OldBitWidth)
1901 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1902 return true;
1903}
1904
Eli Friedman803acb32011-12-22 03:51:45 +00001905static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1906 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001907 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001908 if (!Evaluate(SVal, Info, E))
1909 return false;
1910 if (SVal.isInt()) {
1911 Res = SVal.getInt();
1912 return true;
1913 }
1914 if (SVal.isFloat()) {
1915 Res = SVal.getFloat().bitcastToAPInt();
1916 return true;
1917 }
1918 if (SVal.isVector()) {
1919 QualType VecTy = E->getType();
1920 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1921 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1922 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1923 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1924 Res = llvm::APInt::getNullValue(VecSize);
1925 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1926 APValue &Elt = SVal.getVectorElt(i);
1927 llvm::APInt EltAsInt;
1928 if (Elt.isInt()) {
1929 EltAsInt = Elt.getInt();
1930 } else if (Elt.isFloat()) {
1931 EltAsInt = Elt.getFloat().bitcastToAPInt();
1932 } else {
1933 // Don't try to handle vectors of anything other than int or float
1934 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001936 return false;
1937 }
1938 unsigned BaseEltSize = EltAsInt.getBitWidth();
1939 if (BigEndian)
1940 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1941 else
1942 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1943 }
1944 return true;
1945 }
1946 // Give up if the input isn't an int, float, or vector. For example, we
1947 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001948 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001949 return false;
1950}
1951
Richard Smith43e77732013-05-07 04:50:00 +00001952/// Perform the given integer operation, which is known to need at most BitWidth
1953/// bits, and check for overflow in the original type (if that type was not an
1954/// unsigned type).
1955template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001956static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1957 const APSInt &LHS, const APSInt &RHS,
1958 unsigned BitWidth, Operation Op,
1959 APSInt &Result) {
1960 if (LHS.isUnsigned()) {
1961 Result = Op(LHS, RHS);
1962 return true;
1963 }
Richard Smith43e77732013-05-07 04:50:00 +00001964
1965 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001966 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001967 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001968 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001969 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001970 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001971 << Result.toString(10) << E->getType();
1972 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001973 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001974 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001975 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001976}
1977
1978/// Perform the given binary integer operation.
1979static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1980 BinaryOperatorKind Opcode, APSInt RHS,
1981 APSInt &Result) {
1982 switch (Opcode) {
1983 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001984 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001985 return false;
1986 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001987 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1988 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001989 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001990 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1991 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001992 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001993 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1994 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001995 case BO_And: Result = LHS & RHS; return true;
1996 case BO_Xor: Result = LHS ^ RHS; return true;
1997 case BO_Or: Result = LHS | RHS; return true;
1998 case BO_Div:
1999 case BO_Rem:
2000 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002001 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002002 return false;
2003 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002004 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2005 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2006 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002007 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2008 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002009 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2010 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002011 return true;
2012 case BO_Shl: {
2013 if (Info.getLangOpts().OpenCL)
2014 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2015 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2016 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2017 RHS.isUnsigned());
2018 else if (RHS.isSigned() && RHS.isNegative()) {
2019 // During constant-folding, a negative shift is an opposite shift. Such
2020 // a shift is not a constant expression.
2021 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2022 RHS = -RHS;
2023 goto shift_right;
2024 }
2025 shift_left:
2026 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2027 // the shifted type.
2028 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2029 if (SA != RHS) {
2030 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2031 << RHS << E->getType() << LHS.getBitWidth();
2032 } else if (LHS.isSigned()) {
2033 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2034 // operand, and must not overflow the corresponding unsigned type.
2035 if (LHS.isNegative())
2036 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2037 else if (LHS.countLeadingZeros() < SA)
2038 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2039 }
2040 Result = LHS << SA;
2041 return true;
2042 }
2043 case BO_Shr: {
2044 if (Info.getLangOpts().OpenCL)
2045 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2046 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2047 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2048 RHS.isUnsigned());
2049 else if (RHS.isSigned() && RHS.isNegative()) {
2050 // During constant-folding, a negative shift is an opposite shift. Such a
2051 // shift is not a constant expression.
2052 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2053 RHS = -RHS;
2054 goto shift_left;
2055 }
2056 shift_right:
2057 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2058 // shifted type.
2059 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2060 if (SA != RHS)
2061 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2062 << RHS << E->getType() << LHS.getBitWidth();
2063 Result = LHS >> SA;
2064 return true;
2065 }
2066
2067 case BO_LT: Result = LHS < RHS; return true;
2068 case BO_GT: Result = LHS > RHS; return true;
2069 case BO_LE: Result = LHS <= RHS; return true;
2070 case BO_GE: Result = LHS >= RHS; return true;
2071 case BO_EQ: Result = LHS == RHS; return true;
2072 case BO_NE: Result = LHS != RHS; return true;
2073 }
2074}
2075
Richard Smith861b5b52013-05-07 23:34:45 +00002076/// Perform the given binary floating-point operation, in-place, on LHS.
2077static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2078 APFloat &LHS, BinaryOperatorKind Opcode,
2079 const APFloat &RHS) {
2080 switch (Opcode) {
2081 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002082 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002083 return false;
2084 case BO_Mul:
2085 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2086 break;
2087 case BO_Add:
2088 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2089 break;
2090 case BO_Sub:
2091 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2092 break;
2093 case BO_Div:
2094 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2095 break;
2096 }
2097
Richard Smith0c6124b2015-12-03 01:36:22 +00002098 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002099 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002100 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002101 }
Richard Smith861b5b52013-05-07 23:34:45 +00002102 return true;
2103}
2104
Richard Smitha8105bc2012-01-06 16:39:00 +00002105/// Cast an lvalue referring to a base subobject to a derived class, by
2106/// truncating the lvalue's path to the given length.
2107static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2108 const RecordDecl *TruncatedType,
2109 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002110 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002111
2112 // Check we actually point to a derived class object.
2113 if (TruncatedElements == D.Entries.size())
2114 return true;
2115 assert(TruncatedElements >= D.MostDerivedPathLength &&
2116 "not casting to a derived class");
2117 if (!Result.checkSubobject(Info, E, CSK_Derived))
2118 return false;
2119
2120 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002121 const RecordDecl *RD = TruncatedType;
2122 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002123 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002124 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2125 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002126 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002127 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002128 else
Richard Smithd62306a2011-11-10 06:34:14 +00002129 Result.Offset -= Layout.getBaseClassOffset(Base);
2130 RD = Base;
2131 }
Richard Smith027bf112011-11-17 22:56:20 +00002132 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002133 return true;
2134}
2135
John McCalld7bca762012-05-01 00:38:49 +00002136static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002137 const CXXRecordDecl *Derived,
2138 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002139 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002140 if (!RL) {
2141 if (Derived->isInvalidDecl()) return false;
2142 RL = &Info.Ctx.getASTRecordLayout(Derived);
2143 }
2144
Richard Smithd62306a2011-11-10 06:34:14 +00002145 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002146 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002147 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002148}
2149
Richard Smitha8105bc2012-01-06 16:39:00 +00002150static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002151 const CXXRecordDecl *DerivedDecl,
2152 const CXXBaseSpecifier *Base) {
2153 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2154
John McCalld7bca762012-05-01 00:38:49 +00002155 if (!Base->isVirtual())
2156 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002157
Richard Smitha8105bc2012-01-06 16:39:00 +00002158 SubobjectDesignator &D = Obj.Designator;
2159 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002160 return false;
2161
Richard Smitha8105bc2012-01-06 16:39:00 +00002162 // Extract most-derived object and corresponding type.
2163 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2164 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2165 return false;
2166
2167 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002168 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002169 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2170 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002171 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002172 return true;
2173}
2174
Richard Smith84401042013-06-03 05:03:02 +00002175static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2176 QualType Type, LValue &Result) {
2177 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2178 PathE = E->path_end();
2179 PathI != PathE; ++PathI) {
2180 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2181 *PathI))
2182 return false;
2183 Type = (*PathI)->getType();
2184 }
2185 return true;
2186}
2187
Richard Smithd62306a2011-11-10 06:34:14 +00002188/// Update LVal to refer to the given field, which must be a member of the type
2189/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002190static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002191 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002192 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002193 if (!RL) {
2194 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002195 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002196 }
Richard Smithd62306a2011-11-10 06:34:14 +00002197
2198 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002199 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002200 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002201 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002202}
2203
Richard Smith1b78b3d2012-01-25 22:15:11 +00002204/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002205static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002206 LValue &LVal,
2207 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002208 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002209 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002210 return false;
2211 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002212}
2213
Richard Smithd62306a2011-11-10 06:34:14 +00002214/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002215static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2216 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002217 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2218 // extension.
2219 if (Type->isVoidType() || Type->isFunctionType()) {
2220 Size = CharUnits::One();
2221 return true;
2222 }
2223
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002224 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002225 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002226 return false;
2227 }
2228
Richard Smithd62306a2011-11-10 06:34:14 +00002229 if (!Type->isConstantSizeType()) {
2230 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002231 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002232 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002233 return false;
2234 }
2235
2236 Size = Info.Ctx.getTypeSizeInChars(Type);
2237 return true;
2238}
2239
2240/// Update a pointer value to model pointer arithmetic.
2241/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002242/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002243/// \param LVal - The pointer value to be updated.
2244/// \param EltTy - The pointee type represented by LVal.
2245/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002246static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2247 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002248 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002249 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002250 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002251 return false;
2252
Yaxun Liu402804b2016-12-15 08:09:08 +00002253 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002254 return true;
2255}
2256
Richard Smithd6cc1982017-01-31 02:23:02 +00002257static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2258 LValue &LVal, QualType EltTy,
2259 int64_t Adjustment) {
2260 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2261 APSInt::get(Adjustment));
2262}
2263
Richard Smith66c96992012-02-18 22:04:06 +00002264/// Update an lvalue to refer to a component of a complex number.
2265/// \param Info - Information about the ongoing evaluation.
2266/// \param LVal - The lvalue to be updated.
2267/// \param EltTy - The complex number's component type.
2268/// \param Imag - False for the real component, true for the imaginary.
2269static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2270 LValue &LVal, QualType EltTy,
2271 bool Imag) {
2272 if (Imag) {
2273 CharUnits SizeOfComponent;
2274 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2275 return false;
2276 LVal.Offset += SizeOfComponent;
2277 }
2278 LVal.addComplex(Info, E, EltTy, Imag);
2279 return true;
2280}
2281
Richard Smith27908702011-10-24 17:54:18 +00002282/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002283///
2284/// \param Info Information about the ongoing evaluation.
2285/// \param E An expression to be used when printing diagnostics.
2286/// \param VD The variable whose initializer should be obtained.
2287/// \param Frame The frame in which the variable was created. Must be null
2288/// if this variable is not local to the evaluation.
2289/// \param Result Filled in with a pointer to the value of the variable.
2290static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2291 const VarDecl *VD, CallStackFrame *Frame,
2292 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002293 // If this is a parameter to an active constexpr function call, perform
2294 // argument substitution.
2295 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002296 // Assume arguments of a potential constant expression are unknown
2297 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002298 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002299 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002300 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002301 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002302 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002303 }
Richard Smith3229b742013-05-05 21:17:10 +00002304 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002305 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002306 }
Richard Smith27908702011-10-24 17:54:18 +00002307
Richard Smithd9f663b2013-04-22 15:31:51 +00002308 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002309 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002310 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002311 if (!Result) {
2312 // Assume variables referenced within a lambda's call operator that were
2313 // not declared within the call operator are captures and during checking
2314 // of a potential constant expression, assume they are unknown constant
2315 // expressions.
2316 assert(isLambdaCallOperator(Frame->Callee) &&
2317 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2318 "missing value for local variable");
2319 if (Info.checkingPotentialConstantExpression())
2320 return false;
2321 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002322 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002323 diag::note_unimplemented_constexpr_lambda_feature_ast)
2324 << "captures not currently allowed";
2325 return false;
2326 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002327 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002328 }
2329
Richard Smithd0b4dd62011-12-19 06:19:21 +00002330 // Dig out the initializer, and use the declaration which it's attached to.
2331 const Expr *Init = VD->getAnyInitializer(VD);
2332 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002333 // If we're checking a potential constant expression, the variable could be
2334 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002335 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002336 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002337 return false;
2338 }
2339
Richard Smithd62306a2011-11-10 06:34:14 +00002340 // If we're currently evaluating the initializer of this declaration, use that
2341 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002342 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002343 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002344 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002345 }
2346
Richard Smithcecf1842011-11-01 21:06:14 +00002347 // Never evaluate the initializer of a weak variable. We can't be sure that
2348 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002349 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002350 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002351 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002352 }
Richard Smithcecf1842011-11-01 21:06:14 +00002353
Richard Smithd0b4dd62011-12-19 06:19:21 +00002354 // Check that we can fold the initializer. In C++, we will have already done
2355 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002356 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002357 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002358 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002359 Notes.size() + 1) << VD;
2360 Info.Note(VD->getLocation(), diag::note_declared_at);
2361 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002362 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002363 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002364 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002365 Notes.size() + 1) << VD;
2366 Info.Note(VD->getLocation(), diag::note_declared_at);
2367 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002368 }
Richard Smith27908702011-10-24 17:54:18 +00002369
Richard Smith3229b742013-05-05 21:17:10 +00002370 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002371 return true;
Richard Smith27908702011-10-24 17:54:18 +00002372}
2373
Richard Smith11562c52011-10-28 17:51:58 +00002374static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002375 Qualifiers Quals = T.getQualifiers();
2376 return Quals.hasConst() && !Quals.hasVolatile();
2377}
2378
Richard Smithe97cbd72011-11-11 04:05:33 +00002379/// Get the base index of the given base class within an APValue representing
2380/// the given derived class.
2381static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2382 const CXXRecordDecl *Base) {
2383 Base = Base->getCanonicalDecl();
2384 unsigned Index = 0;
2385 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2386 E = Derived->bases_end(); I != E; ++I, ++Index) {
2387 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2388 return Index;
2389 }
2390
2391 llvm_unreachable("base class missing from derived class's bases list");
2392}
2393
Richard Smith3da88fa2013-04-26 14:36:30 +00002394/// Extract the value of a character from a string literal.
2395static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2396 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002397 // FIXME: Support MakeStringConstant
2398 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2399 std::string Str;
2400 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2401 assert(Index <= Str.size() && "Index too large");
2402 return APSInt::getUnsigned(Str.c_str()[Index]);
2403 }
2404
Alexey Bataevec474782014-10-09 08:45:04 +00002405 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2406 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002407 const StringLiteral *S = cast<StringLiteral>(Lit);
2408 const ConstantArrayType *CAT =
2409 Info.Ctx.getAsConstantArrayType(S->getType());
2410 assert(CAT && "string literal isn't an array");
2411 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002412 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002413
2414 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002415 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002416 if (Index < S->getLength())
2417 Value = S->getCodeUnit(Index);
2418 return Value;
2419}
2420
Richard Smith3da88fa2013-04-26 14:36:30 +00002421// Expand a string literal into an array of characters.
2422static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2423 APValue &Result) {
2424 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();
2429 assert(CharType->isIntegerType() && "unexpected character type");
2430
2431 unsigned Elts = CAT->getSize().getZExtValue();
2432 Result = APValue(APValue::UninitArray(),
2433 std::min(S->getLength(), Elts), Elts);
2434 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2435 CharType->isUnsignedIntegerType());
2436 if (Result.hasArrayFiller())
2437 Result.getArrayFiller() = APValue(Value);
2438 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2439 Value = S->getCodeUnit(I);
2440 Result.getArrayInitializedElt(I) = APValue(Value);
2441 }
2442}
2443
2444// Expand an array so that it has more than Index filled elements.
2445static void expandArray(APValue &Array, unsigned Index) {
2446 unsigned Size = Array.getArraySize();
2447 assert(Index < Size);
2448
2449 // Always at least double the number of elements for which we store a value.
2450 unsigned OldElts = Array.getArrayInitializedElts();
2451 unsigned NewElts = std::max(Index+1, OldElts * 2);
2452 NewElts = std::min(Size, std::max(NewElts, 8u));
2453
2454 // Copy the data across.
2455 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2456 for (unsigned I = 0; I != OldElts; ++I)
2457 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2458 for (unsigned I = OldElts; I != NewElts; ++I)
2459 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2460 if (NewValue.hasArrayFiller())
2461 NewValue.getArrayFiller() = Array.getArrayFiller();
2462 Array.swap(NewValue);
2463}
2464
Richard Smithb01fe402014-09-16 01:24:02 +00002465/// Determine whether a type would actually be read by an lvalue-to-rvalue
2466/// conversion. If it's of class type, we may assume that the copy operation
2467/// is trivial. Note that this is never true for a union type with fields
2468/// (because the copy always "reads" the active member) and always true for
2469/// a non-class type.
2470static bool isReadByLvalueToRvalueConversion(QualType T) {
2471 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2472 if (!RD || (RD->isUnion() && !RD->field_empty()))
2473 return true;
2474 if (RD->isEmpty())
2475 return false;
2476
2477 for (auto *Field : RD->fields())
2478 if (isReadByLvalueToRvalueConversion(Field->getType()))
2479 return true;
2480
2481 for (auto &BaseSpec : RD->bases())
2482 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2483 return true;
2484
2485 return false;
2486}
2487
2488/// Diagnose an attempt to read from any unreadable field within the specified
2489/// type, which might be a class type.
2490static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2491 QualType T) {
2492 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2493 if (!RD)
2494 return false;
2495
2496 if (!RD->hasMutableFields())
2497 return false;
2498
2499 for (auto *Field : RD->fields()) {
2500 // If we're actually going to read this field in some way, then it can't
2501 // be mutable. If we're in a union, then assigning to a mutable field
2502 // (even an empty one) can change the active member, so that's not OK.
2503 // FIXME: Add core issue number for the union case.
2504 if (Field->isMutable() &&
2505 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002506 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002507 Info.Note(Field->getLocation(), diag::note_declared_at);
2508 return true;
2509 }
2510
2511 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2512 return true;
2513 }
2514
2515 for (auto &BaseSpec : RD->bases())
2516 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2517 return true;
2518
2519 // All mutable fields were empty, and thus not actually read.
2520 return false;
2521}
2522
Richard Smith861b5b52013-05-07 23:34:45 +00002523/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002524enum AccessKinds {
2525 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002526 AK_Assign,
2527 AK_Increment,
2528 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002529};
2530
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002531namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002532/// A handle to a complete object (an object that is not a subobject of
2533/// another object).
2534struct CompleteObject {
2535 /// The value of the complete object.
2536 APValue *Value;
2537 /// The type of the complete object.
2538 QualType Type;
2539
Craig Topper36250ad2014-05-12 05:36:57 +00002540 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002541 CompleteObject(APValue *Value, QualType Type)
2542 : Value(Value), Type(Type) {
2543 assert(Value && "missing value for complete object");
2544 }
2545
Aaron Ballman67347662015-02-15 22:00:28 +00002546 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002547};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002548} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002549
Richard Smith3da88fa2013-04-26 14:36:30 +00002550/// Find the designated sub-object of an rvalue.
2551template<typename SubobjectHandler>
2552typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002553findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002554 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002555 if (Sub.Invalid)
2556 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002558 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002559 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002560 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002561 << handler.AccessKind;
2562 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002563 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002564 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002565 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002566
Richard Smith3229b742013-05-05 21:17:10 +00002567 APValue *O = Obj.Value;
2568 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002569 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002570
Richard Smithd62306a2011-11-10 06:34:14 +00002571 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002572 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2573 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002574 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002575 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002576 return handler.failed();
2577 }
2578
Richard Smith49ca8aa2013-08-06 07:09:20 +00002579 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002580 // If we are reading an object of class type, there may still be more
2581 // things we need to check: if there are any mutable subobjects, we
2582 // cannot perform this read. (This only happens when performing a trivial
2583 // copy or assignment.)
2584 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2585 diagnoseUnreadableFields(Info, E, ObjType))
2586 return handler.failed();
2587
Richard Smith49ca8aa2013-08-06 07:09:20 +00002588 if (!handler.found(*O, ObjType))
2589 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002590
Richard Smith49ca8aa2013-08-06 07:09:20 +00002591 // If we modified a bit-field, truncate it to the right width.
2592 if (handler.AccessKind != AK_Read &&
2593 LastField && LastField->isBitField() &&
2594 !truncateBitfieldValue(Info, E, *O, LastField))
2595 return false;
2596
2597 return true;
2598 }
2599
Craig Topper36250ad2014-05-12 05:36:57 +00002600 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002601 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002602 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002603 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002604 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002605 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002606 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002607 // Note, it should not be possible to form a pointer with a valid
2608 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002609 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002610 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002611 << handler.AccessKind;
2612 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002613 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002614 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002615 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002616
2617 ObjType = CAT->getElementType();
2618
Richard Smith14a94132012-02-17 03:35:37 +00002619 // An array object is represented as either an Array APValue or as an
2620 // LValue which refers to a string literal.
2621 if (O->isLValue()) {
2622 assert(I == N - 1 && "extracting subobject of character?");
2623 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002624 if (handler.AccessKind != AK_Read)
2625 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2626 *O);
2627 else
2628 return handler.foundString(*O, ObjType, Index);
2629 }
2630
2631 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002632 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002633 else if (handler.AccessKind != AK_Read) {
2634 expandArray(*O, Index);
2635 O = &O->getArrayInitializedElt(Index);
2636 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002637 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002638 } else if (ObjType->isAnyComplexType()) {
2639 // Next subobject is a complex number.
2640 uint64_t Index = Sub.Entries[I].ArrayIndex;
2641 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002642 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002643 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002644 << handler.AccessKind;
2645 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002646 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002647 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002648 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002649
2650 bool WasConstQualified = ObjType.isConstQualified();
2651 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2652 if (WasConstQualified)
2653 ObjType.addConst();
2654
Richard Smith66c96992012-02-18 22:04:06 +00002655 assert(I == N - 1 && "extracting subobject of scalar?");
2656 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 return handler.found(Index ? O->getComplexIntImag()
2658 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002659 } else {
2660 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 return handler.found(Index ? O->getComplexFloatImag()
2662 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002663 }
Richard Smithd62306a2011-11-10 06:34:14 +00002664 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002665 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002666 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002667 << Field;
2668 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002670 }
2671
Richard Smithd62306a2011-11-10 06:34:14 +00002672 // Next subobject is a class, struct or union field.
2673 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2674 if (RD->isUnion()) {
2675 const FieldDecl *UnionField = O->getUnionField();
2676 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002677 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002678 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 << handler.AccessKind << Field << !UnionField << UnionField;
2680 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002681 }
Richard Smithd62306a2011-11-10 06:34:14 +00002682 O = &O->getUnionValue();
2683 } else
2684 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002685
2686 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002687 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 if (WasConstQualified && !Field->isMutable())
2689 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002690
2691 if (ObjType.isVolatileQualified()) {
2692 if (Info.getLangOpts().CPlusPlus) {
2693 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002694 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002695 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002696 Info.Note(Field->getLocation(), diag::note_declared_at);
2697 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002699 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002700 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002701 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002702
2703 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002704 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002705 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002706 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2707 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2708 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002709
2710 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002711 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002712 if (WasConstQualified)
2713 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002714 }
2715 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002716}
2717
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002718namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002719struct ExtractSubobjectHandler {
2720 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002721 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002722
2723 static const AccessKinds AccessKind = AK_Read;
2724
2725 typedef bool result_type;
2726 bool failed() { return false; }
2727 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002728 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002729 return true;
2730 }
2731 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002732 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002733 return true;
2734 }
2735 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002736 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002737 return true;
2738 }
2739 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002740 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002741 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2742 return true;
2743 }
2744};
Richard Smith3229b742013-05-05 21:17:10 +00002745} // end anonymous namespace
2746
Richard Smith3da88fa2013-04-26 14:36:30 +00002747const AccessKinds ExtractSubobjectHandler::AccessKind;
2748
2749/// Extract the designated sub-object of an rvalue.
2750static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002751 const CompleteObject &Obj,
2752 const SubobjectDesignator &Sub,
2753 APValue &Result) {
2754 ExtractSubobjectHandler Handler = { Info, Result };
2755 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002756}
2757
Richard Smith3229b742013-05-05 21:17:10 +00002758namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002759struct ModifySubobjectHandler {
2760 EvalInfo &Info;
2761 APValue &NewVal;
2762 const Expr *E;
2763
2764 typedef bool result_type;
2765 static const AccessKinds AccessKind = AK_Assign;
2766
2767 bool checkConst(QualType QT) {
2768 // Assigning to a const object has undefined behavior.
2769 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002770 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002771 return false;
2772 }
2773 return true;
2774 }
2775
2776 bool failed() { return false; }
2777 bool found(APValue &Subobj, QualType SubobjType) {
2778 if (!checkConst(SubobjType))
2779 return false;
2780 // We've been given ownership of NewVal, so just swap it in.
2781 Subobj.swap(NewVal);
2782 return true;
2783 }
2784 bool found(APSInt &Value, QualType SubobjType) {
2785 if (!checkConst(SubobjType))
2786 return false;
2787 if (!NewVal.isInt()) {
2788 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002789 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return false;
2791 }
2792 Value = NewVal.getInt();
2793 return true;
2794 }
2795 bool found(APFloat &Value, QualType SubobjType) {
2796 if (!checkConst(SubobjType))
2797 return false;
2798 Value = NewVal.getFloat();
2799 return true;
2800 }
2801 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2802 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2803 }
2804};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002805} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002806
Richard Smith3229b742013-05-05 21:17:10 +00002807const AccessKinds ModifySubobjectHandler::AccessKind;
2808
Richard Smith3da88fa2013-04-26 14:36:30 +00002809/// Update the designated sub-object of an rvalue to the given value.
2810static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002811 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 const SubobjectDesignator &Sub,
2813 APValue &NewVal) {
2814 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002815 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002816}
2817
Richard Smith84f6dcf2012-02-02 01:16:57 +00002818/// Find the position where two subobject designators diverge, or equivalently
2819/// the length of the common initial subsequence.
2820static unsigned FindDesignatorMismatch(QualType ObjType,
2821 const SubobjectDesignator &A,
2822 const SubobjectDesignator &B,
2823 bool &WasArrayIndex) {
2824 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2825 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002826 if (!ObjType.isNull() &&
2827 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002828 // Next subobject is an array element.
2829 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2830 WasArrayIndex = true;
2831 return I;
2832 }
Richard Smith66c96992012-02-18 22:04:06 +00002833 if (ObjType->isAnyComplexType())
2834 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2835 else
2836 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002837 } else {
2838 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2839 WasArrayIndex = false;
2840 return I;
2841 }
2842 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2843 // Next subobject is a field.
2844 ObjType = FD->getType();
2845 else
2846 // Next subobject is a base class.
2847 ObjType = QualType();
2848 }
2849 }
2850 WasArrayIndex = false;
2851 return I;
2852}
2853
2854/// Determine whether the given subobject designators refer to elements of the
2855/// same array object.
2856static bool AreElementsOfSameArray(QualType ObjType,
2857 const SubobjectDesignator &A,
2858 const SubobjectDesignator &B) {
2859 if (A.Entries.size() != B.Entries.size())
2860 return false;
2861
George Burgess IVa51c4072015-10-16 01:49:01 +00002862 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002863 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2864 // A is a subobject of the array element.
2865 return false;
2866
2867 // If A (and B) designates an array element, the last entry will be the array
2868 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2869 // of length 1' case, and the entire path must match.
2870 bool WasArrayIndex;
2871 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2872 return CommonLength >= A.Entries.size() - IsArray;
2873}
2874
Richard Smith3229b742013-05-05 21:17:10 +00002875/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002876static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2877 AccessKinds AK, const LValue &LVal,
2878 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002879 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002880 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002881 return CompleteObject();
2882 }
2883
Craig Topper36250ad2014-05-12 05:36:57 +00002884 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002885 if (LVal.CallIndex) {
2886 Frame = Info.getCallFrame(LVal.CallIndex);
2887 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002888 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002889 << AK << LVal.Base.is<const ValueDecl*>();
2890 NoteLValueLocation(Info, LVal.Base);
2891 return CompleteObject();
2892 }
Richard Smith3229b742013-05-05 21:17:10 +00002893 }
2894
2895 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2896 // is not a constant expression (even if the object is non-volatile). We also
2897 // apply this rule to C++98, in order to conform to the expected 'volatile'
2898 // semantics.
2899 if (LValType.isVolatileQualified()) {
2900 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002901 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002902 << AK << LValType;
2903 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002904 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002905 return CompleteObject();
2906 }
2907
2908 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002909 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002910 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002911
2912 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2913 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2914 // In C++11, constexpr, non-volatile variables initialized with constant
2915 // expressions are constant expressions too. Inside constexpr functions,
2916 // parameters are constant expressions even if they're non-const.
2917 // In C++1y, objects local to a constant expression (those with a Frame) are
2918 // both readable and writable inside constant expressions.
2919 // In C, such things can also be folded, although they are not ICEs.
2920 const VarDecl *VD = dyn_cast<VarDecl>(D);
2921 if (VD) {
2922 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2923 VD = VDef;
2924 }
2925 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002926 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002927 return CompleteObject();
2928 }
2929
2930 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002931 if (BaseType.isVolatileQualified()) {
2932 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002933 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002934 << AK << 1 << VD;
2935 Info.Note(VD->getLocation(), diag::note_declared_at);
2936 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002937 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002938 }
2939 return CompleteObject();
2940 }
2941
2942 // Unless we're looking at a local variable or argument in a constexpr call,
2943 // the variable we're reading must be const.
2944 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002945 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002946 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2947 // OK, we can read and modify an object if we're in the process of
2948 // evaluating its initializer, because its lifetime began in this
2949 // evaluation.
2950 } else if (AK != AK_Read) {
2951 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002952 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002953 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002954 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002955 // OK, we can read this variable.
2956 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002957 // In OpenCL if a variable is in constant address space it is a const value.
2958 if (!(BaseType.isConstQualified() ||
2959 (Info.getLangOpts().OpenCL &&
2960 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002961 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002962 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002963 Info.Note(VD->getLocation(), diag::note_declared_at);
2964 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002965 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002966 }
2967 return CompleteObject();
2968 }
2969 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2970 // We support folding of const floating-point types, in order to make
2971 // static const data members of such types (supported as an extension)
2972 // more useful.
2973 if (Info.getLangOpts().CPlusPlus11) {
2974 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2975 Info.Note(VD->getLocation(), diag::note_declared_at);
2976 } else {
2977 Info.CCEDiag(E);
2978 }
George Burgess IVb5316982016-12-27 05:33:20 +00002979 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2980 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2981 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002982 } else {
2983 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002984 if (Info.checkingPotentialConstantExpression() &&
2985 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2986 // The definition of this variable could be constexpr. We can't
2987 // access it right now, but may be able to in future.
2988 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002989 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002990 Info.Note(VD->getLocation(), diag::note_declared_at);
2991 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002993 }
2994 return CompleteObject();
2995 }
2996 }
2997
2998 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2999 return CompleteObject();
3000 } else {
3001 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3002
3003 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003004 if (const MaterializeTemporaryExpr *MTE =
3005 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3006 assert(MTE->getStorageDuration() == SD_Static &&
3007 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003008
Richard Smithe6c01442013-06-05 00:46:14 +00003009 // Per C++1y [expr.const]p2:
3010 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3011 // - a [...] glvalue of integral or enumeration type that refers to
3012 // a non-volatile const object [...]
3013 // [...]
3014 // - a [...] glvalue of literal type that refers to a non-volatile
3015 // object whose lifetime began within the evaluation of e.
3016 //
3017 // C++11 misses the 'began within the evaluation of e' check and
3018 // instead allows all temporaries, including things like:
3019 // int &&r = 1;
3020 // int x = ++r;
3021 // constexpr int k = r;
3022 // Therefore we use the C++1y rules in C++11 too.
3023 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3024 const ValueDecl *ED = MTE->getExtendingDecl();
3025 if (!(BaseType.isConstQualified() &&
3026 BaseType->isIntegralOrEnumerationType()) &&
3027 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003028 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003029 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3030 return CompleteObject();
3031 }
3032
3033 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3034 assert(BaseVal && "got reference to unevaluated temporary");
3035 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003037 return CompleteObject();
3038 }
3039 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003040 BaseVal = Frame->getTemporary(Base);
3041 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003042 }
Richard Smith3229b742013-05-05 21:17:10 +00003043
3044 // Volatile temporary objects cannot be accessed in constant expressions.
3045 if (BaseType.isVolatileQualified()) {
3046 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003047 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003048 << AK << 0;
3049 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3050 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003051 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003052 }
3053 return CompleteObject();
3054 }
3055 }
3056
Richard Smith7525ff62013-05-09 07:14:00 +00003057 // During the construction of an object, it is not yet 'const'.
3058 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3059 // and this doesn't do quite the right thing for const subobjects of the
3060 // object under construction.
3061 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3062 BaseType = Info.Ctx.getCanonicalType(BaseType);
3063 BaseType.removeLocalConst();
3064 }
3065
Richard Smith6d4c6582013-11-05 22:18:15 +00003066 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003067 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003068 //
3069 // FIXME: Not all local state is mutable. Allow local constant subobjects
3070 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003071 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3072 Info.EvalStatus.HasSideEffects) ||
3073 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003074 return CompleteObject();
3075
3076 return CompleteObject(BaseVal, BaseType);
3077}
3078
Richard Smith243ef902013-05-05 23:31:59 +00003079/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3080/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3081/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003082///
3083/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003084/// \param Conv - The expression for which we are performing the conversion.
3085/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003086/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3087/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003088/// \param LVal - The glvalue on which we are attempting to perform this action.
3089/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003090static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003091 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003092 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003093 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003094 return false;
3095
Richard Smith3229b742013-05-05 21:17:10 +00003096 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003097 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003098 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003099 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3100 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3101 // initializer until now for such expressions. Such an expression can't be
3102 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003103 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003104 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003105 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003106 }
Richard Smith3229b742013-05-05 21:17:10 +00003107 APValue Lit;
3108 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3109 return false;
3110 CompleteObject LitObj(&Lit, Base->getType());
3111 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003112 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003113 // We represent a string literal array as an lvalue pointing at the
3114 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003115 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003116 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3117 CompleteObject StrObj(&Str, Base->getType());
3118 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003119 }
Richard Smith11562c52011-10-28 17:51:58 +00003120 }
3121
Richard Smith3229b742013-05-05 21:17:10 +00003122 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3123 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003124}
3125
3126/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003127static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003128 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003129 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003130 return false;
3131
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003132 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003133 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003134 return false;
3135 }
3136
Richard Smith3229b742013-05-05 21:17:10 +00003137 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3138 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003139}
3140
Richard Smith243ef902013-05-05 23:31:59 +00003141static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3142 return T->isSignedIntegerType() &&
3143 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3144}
3145
3146namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003147struct CompoundAssignSubobjectHandler {
3148 EvalInfo &Info;
3149 const Expr *E;
3150 QualType PromotedLHSType;
3151 BinaryOperatorKind Opcode;
3152 const APValue &RHS;
3153
3154 static const AccessKinds AccessKind = AK_Assign;
3155
3156 typedef bool result_type;
3157
3158 bool checkConst(QualType QT) {
3159 // Assigning to a const object has undefined behavior.
3160 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003162 return false;
3163 }
3164 return true;
3165 }
3166
3167 bool failed() { return false; }
3168 bool found(APValue &Subobj, QualType SubobjType) {
3169 switch (Subobj.getKind()) {
3170 case APValue::Int:
3171 return found(Subobj.getInt(), SubobjType);
3172 case APValue::Float:
3173 return found(Subobj.getFloat(), SubobjType);
3174 case APValue::ComplexInt:
3175 case APValue::ComplexFloat:
3176 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003178 return false;
3179 case APValue::LValue:
3180 return foundPointer(Subobj, SubobjType);
3181 default:
3182 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003183 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003184 return false;
3185 }
3186 }
3187 bool found(APSInt &Value, QualType SubobjType) {
3188 if (!checkConst(SubobjType))
3189 return false;
3190
3191 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3192 // We don't support compound assignment on integer-cast-to-pointer
3193 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003194 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003195 return false;
3196 }
3197
3198 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3199 SubobjType, Value);
3200 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3201 return false;
3202 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3203 return true;
3204 }
3205 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003206 return checkConst(SubobjType) &&
3207 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3208 Value) &&
3209 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3210 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003211 }
3212 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3213 if (!checkConst(SubobjType))
3214 return false;
3215
3216 QualType PointeeType;
3217 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3218 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003219
3220 if (PointeeType.isNull() || !RHS.isInt() ||
3221 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003222 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003223 return false;
3224 }
3225
Richard Smithd6cc1982017-01-31 02:23:02 +00003226 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003227 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003228 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003229
3230 LValue LVal;
3231 LVal.setFrom(Info.Ctx, Subobj);
3232 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3233 return false;
3234 LVal.moveInto(Subobj);
3235 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003236 }
3237 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3238 llvm_unreachable("shouldn't encounter string elements here");
3239 }
3240};
3241} // end anonymous namespace
3242
3243const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3244
3245/// Perform a compound assignment of LVal <op>= RVal.
3246static bool handleCompoundAssignment(
3247 EvalInfo &Info, const Expr *E,
3248 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3249 BinaryOperatorKind Opcode, const APValue &RVal) {
3250 if (LVal.Designator.Invalid)
3251 return false;
3252
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003253 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003254 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003255 return false;
3256 }
3257
3258 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3259 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3260 RVal };
3261 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3262}
3263
3264namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003265struct IncDecSubobjectHandler {
3266 EvalInfo &Info;
3267 const Expr *E;
3268 AccessKinds AccessKind;
3269 APValue *Old;
3270
3271 typedef bool result_type;
3272
3273 bool checkConst(QualType QT) {
3274 // Assigning to a const object has undefined behavior.
3275 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003276 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003277 return false;
3278 }
3279 return true;
3280 }
3281
3282 bool failed() { return false; }
3283 bool found(APValue &Subobj, QualType SubobjType) {
3284 // Stash the old value. Also clear Old, so we don't clobber it later
3285 // if we're post-incrementing a complex.
3286 if (Old) {
3287 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003288 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003289 }
3290
3291 switch (Subobj.getKind()) {
3292 case APValue::Int:
3293 return found(Subobj.getInt(), SubobjType);
3294 case APValue::Float:
3295 return found(Subobj.getFloat(), SubobjType);
3296 case APValue::ComplexInt:
3297 return found(Subobj.getComplexIntReal(),
3298 SubobjType->castAs<ComplexType>()->getElementType()
3299 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3300 case APValue::ComplexFloat:
3301 return found(Subobj.getComplexFloatReal(),
3302 SubobjType->castAs<ComplexType>()->getElementType()
3303 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3304 case APValue::LValue:
3305 return foundPointer(Subobj, SubobjType);
3306 default:
3307 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003308 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003309 return false;
3310 }
3311 }
3312 bool found(APSInt &Value, QualType SubobjType) {
3313 if (!checkConst(SubobjType))
3314 return false;
3315
3316 if (!SubobjType->isIntegerType()) {
3317 // We don't support increment / decrement on integer-cast-to-pointer
3318 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003319 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003320 return false;
3321 }
3322
3323 if (Old) *Old = APValue(Value);
3324
3325 // bool arithmetic promotes to int, and the conversion back to bool
3326 // doesn't reduce mod 2^n, so special-case it.
3327 if (SubobjType->isBooleanType()) {
3328 if (AccessKind == AK_Increment)
3329 Value = 1;
3330 else
3331 Value = !Value;
3332 return true;
3333 }
3334
3335 bool WasNegative = Value.isNegative();
3336 if (AccessKind == AK_Increment) {
3337 ++Value;
3338
3339 if (!WasNegative && Value.isNegative() &&
3340 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3341 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003342 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003343 }
3344 } else {
3345 --Value;
3346
3347 if (WasNegative && !Value.isNegative() &&
3348 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3349 unsigned BitWidth = Value.getBitWidth();
3350 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3351 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003352 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003353 }
3354 }
3355 return true;
3356 }
3357 bool found(APFloat &Value, QualType SubobjType) {
3358 if (!checkConst(SubobjType))
3359 return false;
3360
3361 if (Old) *Old = APValue(Value);
3362
3363 APFloat One(Value.getSemantics(), 1);
3364 if (AccessKind == AK_Increment)
3365 Value.add(One, APFloat::rmNearestTiesToEven);
3366 else
3367 Value.subtract(One, APFloat::rmNearestTiesToEven);
3368 return true;
3369 }
3370 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3371 if (!checkConst(SubobjType))
3372 return false;
3373
3374 QualType PointeeType;
3375 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3376 PointeeType = PT->getPointeeType();
3377 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003378 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003379 return false;
3380 }
3381
3382 LValue LVal;
3383 LVal.setFrom(Info.Ctx, Subobj);
3384 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3385 AccessKind == AK_Increment ? 1 : -1))
3386 return false;
3387 LVal.moveInto(Subobj);
3388 return true;
3389 }
3390 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3391 llvm_unreachable("shouldn't encounter string elements here");
3392 }
3393};
3394} // end anonymous namespace
3395
3396/// Perform an increment or decrement on LVal.
3397static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3398 QualType LValType, bool IsIncrement, APValue *Old) {
3399 if (LVal.Designator.Invalid)
3400 return false;
3401
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003402 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003403 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003404 return false;
3405 }
3406
3407 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3408 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3409 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3410 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3411}
3412
Richard Smithe97cbd72011-11-11 04:05:33 +00003413/// Build an lvalue for the object argument of a member function call.
3414static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3415 LValue &This) {
3416 if (Object->getType()->isPointerType())
3417 return EvaluatePointer(Object, This, Info);
3418
3419 if (Object->isGLValue())
3420 return EvaluateLValue(Object, This, Info);
3421
Richard Smithd9f663b2013-04-22 15:31:51 +00003422 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003423 return EvaluateTemporary(Object, This, Info);
3424
Faisal Valie690b7a2016-07-02 22:34:24 +00003425 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003426 return false;
3427}
3428
3429/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3430/// lvalue referring to the result.
3431///
3432/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003433/// \param LV - An lvalue referring to the base of the member pointer.
3434/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003435/// \param IncludeMember - Specifies whether the member itself is included in
3436/// the resulting LValue subobject designator. This is not possible when
3437/// creating a bound member function.
3438/// \return The field or method declaration to which the member pointer refers,
3439/// or 0 if evaluation fails.
3440static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003441 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003442 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003443 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003444 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003445 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003446 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003447 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003448
3449 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3450 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003451 if (!MemPtr.getDecl()) {
3452 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003453 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003454 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003455 }
Richard Smith253c2a32012-01-27 01:14:48 +00003456
Richard Smith027bf112011-11-17 22:56:20 +00003457 if (MemPtr.isDerivedMember()) {
3458 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003459 // The end of the derived-to-base path for the base object must match the
3460 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003461 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003462 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003463 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003464 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003465 }
Richard Smith027bf112011-11-17 22:56:20 +00003466 unsigned PathLengthToMember =
3467 LV.Designator.Entries.size() - MemPtr.Path.size();
3468 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3469 const CXXRecordDecl *LVDecl = getAsBaseClass(
3470 LV.Designator.Entries[PathLengthToMember + I]);
3471 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003472 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003473 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003474 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003475 }
Richard Smith027bf112011-11-17 22:56:20 +00003476 }
3477
3478 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003479 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003480 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003481 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003482 } else if (!MemPtr.Path.empty()) {
3483 // Extend the LValue path with the member pointer's path.
3484 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3485 MemPtr.Path.size() + IncludeMember);
3486
3487 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003488 if (const PointerType *PT = LVType->getAs<PointerType>())
3489 LVType = PT->getPointeeType();
3490 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3491 assert(RD && "member pointer access on non-class-type expression");
3492 // The first class in the path is that of the lvalue.
3493 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3494 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003495 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003496 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003497 RD = Base;
3498 }
3499 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003500 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3501 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003502 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003503 }
3504
3505 // Add the member. Note that we cannot build bound member functions here.
3506 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003507 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003508 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003509 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003510 } else if (const IndirectFieldDecl *IFD =
3511 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003512 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003513 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003514 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003515 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003516 }
Richard Smith027bf112011-11-17 22:56:20 +00003517 }
3518
3519 return MemPtr.getDecl();
3520}
3521
Richard Smith84401042013-06-03 05:03:02 +00003522static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3523 const BinaryOperator *BO,
3524 LValue &LV,
3525 bool IncludeMember = true) {
3526 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3527
3528 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003529 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003530 MemberPtr MemPtr;
3531 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3532 }
Craig Topper36250ad2014-05-12 05:36:57 +00003533 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003534 }
3535
3536 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3537 BO->getRHS(), IncludeMember);
3538}
3539
Richard Smith027bf112011-11-17 22:56:20 +00003540/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3541/// the provided lvalue, which currently refers to the base object.
3542static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3543 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003544 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003545 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003546 return false;
3547
Richard Smitha8105bc2012-01-06 16:39:00 +00003548 QualType TargetQT = E->getType();
3549 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3550 TargetQT = PT->getPointeeType();
3551
3552 // Check this cast lands within the final derived-to-base subobject path.
3553 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003554 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003555 << D.MostDerivedType << TargetQT;
3556 return false;
3557 }
3558
Richard Smith027bf112011-11-17 22:56:20 +00003559 // Check the type of the final cast. We don't need to check the path,
3560 // since a cast can only be formed if the path is unique.
3561 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003562 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3563 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003564 if (NewEntriesSize == D.MostDerivedPathLength)
3565 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3566 else
Richard Smith027bf112011-11-17 22:56:20 +00003567 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003568 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003569 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003570 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003571 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003572 }
Richard Smith027bf112011-11-17 22:56:20 +00003573
3574 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003575 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003576}
3577
Mike Stump876387b2009-10-27 22:09:17 +00003578namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003579enum EvalStmtResult {
3580 /// Evaluation failed.
3581 ESR_Failed,
3582 /// Hit a 'return' statement.
3583 ESR_Returned,
3584 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003585 ESR_Succeeded,
3586 /// Hit a 'continue' statement.
3587 ESR_Continue,
3588 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003589 ESR_Break,
3590 /// Still scanning for 'case' or 'default' statement.
3591 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003592};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003593}
Richard Smith254a73d2011-10-28 22:34:42 +00003594
Richard Smith97fcf4b2016-08-14 23:15:52 +00003595static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3596 // We don't need to evaluate the initializer for a static local.
3597 if (!VD->hasLocalStorage())
3598 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003599
Richard Smith97fcf4b2016-08-14 23:15:52 +00003600 LValue Result;
3601 Result.set(VD, Info.CurrentCall->Index);
3602 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003603
Richard Smith97fcf4b2016-08-14 23:15:52 +00003604 const Expr *InitE = VD->getInit();
3605 if (!InitE) {
3606 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3607 << false << VD->getType();
3608 Val = APValue();
3609 return false;
3610 }
Richard Smith51f03172013-06-20 03:00:05 +00003611
Richard Smith97fcf4b2016-08-14 23:15:52 +00003612 if (InitE->isValueDependent())
3613 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003614
Richard Smith97fcf4b2016-08-14 23:15:52 +00003615 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3616 // Wipe out any partially-computed value, to allow tracking that this
3617 // evaluation failed.
3618 Val = APValue();
3619 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003620 }
3621
3622 return true;
3623}
3624
Richard Smith97fcf4b2016-08-14 23:15:52 +00003625static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3626 bool OK = true;
3627
3628 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3629 OK &= EvaluateVarDecl(Info, VD);
3630
3631 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3632 for (auto *BD : DD->bindings())
3633 if (auto *VD = BD->getHoldingVar())
3634 OK &= EvaluateDecl(Info, VD);
3635
3636 return OK;
3637}
3638
3639
Richard Smith4e18ca52013-05-06 05:56:11 +00003640/// Evaluate a condition (either a variable declaration or an expression).
3641static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3642 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003643 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003644 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3645 return false;
3646 return EvaluateAsBooleanCondition(Cond, Result, Info);
3647}
3648
Richard Smith89210072016-04-04 23:29:43 +00003649namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003650/// \brief A location where the result (returned value) of evaluating a
3651/// statement should be stored.
3652struct StmtResult {
3653 /// The APValue that should be filled in with the returned value.
3654 APValue &Value;
3655 /// The location containing the result, if any (used to support RVO).
3656 const LValue *Slot;
3657};
Richard Smith89210072016-04-04 23:29:43 +00003658}
Richard Smith52a980a2015-08-28 02:43:42 +00003659
3660static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003661 const Stmt *S,
3662 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003663
3664/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003665static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003666 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003667 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003668 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003669 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003670 case ESR_Break:
3671 return ESR_Succeeded;
3672 case ESR_Succeeded:
3673 case ESR_Continue:
3674 return ESR_Continue;
3675 case ESR_Failed:
3676 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003677 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003678 return ESR;
3679 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003680 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003681}
3682
Richard Smith496ddcf2013-05-12 17:32:42 +00003683/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003684static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003685 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 BlockScopeRAII Scope(Info);
3687
Richard Smith496ddcf2013-05-12 17:32:42 +00003688 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003689 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003690 {
3691 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003692 if (const Stmt *Init = SS->getInit()) {
3693 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3694 if (ESR != ESR_Succeeded)
3695 return ESR;
3696 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003697 if (SS->getConditionVariable() &&
3698 !EvaluateDecl(Info, SS->getConditionVariable()))
3699 return ESR_Failed;
3700 if (!EvaluateInteger(SS->getCond(), Value, Info))
3701 return ESR_Failed;
3702 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003703
3704 // Find the switch case corresponding to the value of the condition.
3705 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003706 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003707 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3708 SC = SC->getNextSwitchCase()) {
3709 if (isa<DefaultStmt>(SC)) {
3710 Found = SC;
3711 continue;
3712 }
3713
3714 const CaseStmt *CS = cast<CaseStmt>(SC);
3715 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3716 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3717 : LHS;
3718 if (LHS <= Value && Value <= RHS) {
3719 Found = SC;
3720 break;
3721 }
3722 }
3723
3724 if (!Found)
3725 return ESR_Succeeded;
3726
3727 // Search the switch body for the switch case and evaluate it from there.
3728 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3729 case ESR_Break:
3730 return ESR_Succeeded;
3731 case ESR_Succeeded:
3732 case ESR_Continue:
3733 case ESR_Failed:
3734 case ESR_Returned:
3735 return ESR;
3736 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003737 // This can only happen if the switch case is nested within a statement
3738 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003739 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003740 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003741 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003742 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003743}
3744
Richard Smith254a73d2011-10-28 22:34:42 +00003745// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003746static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003747 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003748 if (!Info.nextStep(S))
3749 return ESR_Failed;
3750
Richard Smith496ddcf2013-05-12 17:32:42 +00003751 // If we're hunting down a 'case' or 'default' label, recurse through
3752 // substatements until we hit the label.
3753 if (Case) {
3754 // FIXME: We don't start the lifetime of objects whose initialization we
3755 // jump over. However, such objects must be of class type with a trivial
3756 // default constructor that initialize all subobjects, so must be empty,
3757 // so this almost never matters.
3758 switch (S->getStmtClass()) {
3759 case Stmt::CompoundStmtClass:
3760 // FIXME: Precompute which substatement of a compound statement we
3761 // would jump to, and go straight there rather than performing a
3762 // linear scan each time.
3763 case Stmt::LabelStmtClass:
3764 case Stmt::AttributedStmtClass:
3765 case Stmt::DoStmtClass:
3766 break;
3767
3768 case Stmt::CaseStmtClass:
3769 case Stmt::DefaultStmtClass:
3770 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003771 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003772 break;
3773
3774 case Stmt::IfStmtClass: {
3775 // FIXME: Precompute which side of an 'if' we would jump to, and go
3776 // straight there rather than scanning both sides.
3777 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003778
3779 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3780 // preceded by our switch label.
3781 BlockScopeRAII Scope(Info);
3782
Richard Smith496ddcf2013-05-12 17:32:42 +00003783 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3784 if (ESR != ESR_CaseNotFound || !IS->getElse())
3785 return ESR;
3786 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3787 }
3788
3789 case Stmt::WhileStmtClass: {
3790 EvalStmtResult ESR =
3791 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3792 if (ESR != ESR_Continue)
3793 return ESR;
3794 break;
3795 }
3796
3797 case Stmt::ForStmtClass: {
3798 const ForStmt *FS = cast<ForStmt>(S);
3799 EvalStmtResult ESR =
3800 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3801 if (ESR != ESR_Continue)
3802 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003803 if (FS->getInc()) {
3804 FullExpressionRAII IncScope(Info);
3805 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3806 return ESR_Failed;
3807 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003808 break;
3809 }
3810
3811 case Stmt::DeclStmtClass:
3812 // FIXME: If the variable has initialization that can't be jumped over,
3813 // bail out of any immediately-surrounding compound-statement too.
3814 default:
3815 return ESR_CaseNotFound;
3816 }
3817 }
3818
Richard Smith254a73d2011-10-28 22:34:42 +00003819 switch (S->getStmtClass()) {
3820 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003821 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003822 // Don't bother evaluating beyond an expression-statement which couldn't
3823 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003824 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003825 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003826 return ESR_Failed;
3827 return ESR_Succeeded;
3828 }
3829
Faisal Valie690b7a2016-07-02 22:34:24 +00003830 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003831 return ESR_Failed;
3832
3833 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003834 return ESR_Succeeded;
3835
Richard Smithd9f663b2013-04-22 15:31:51 +00003836 case Stmt::DeclStmtClass: {
3837 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003838 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003839 // Each declaration initialization is its own full-expression.
3840 // FIXME: This isn't quite right; if we're performing aggregate
3841 // initialization, each braced subexpression is its own full-expression.
3842 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003843 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003844 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003845 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003846 return ESR_Succeeded;
3847 }
3848
Richard Smith357362d2011-12-13 06:39:58 +00003849 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003850 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003851 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003852 if (RetExpr &&
3853 !(Result.Slot
3854 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3855 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003856 return ESR_Failed;
3857 return ESR_Returned;
3858 }
Richard Smith254a73d2011-10-28 22:34:42 +00003859
3860 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003861 BlockScopeRAII Scope(Info);
3862
Richard Smith254a73d2011-10-28 22:34:42 +00003863 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003864 for (const auto *BI : CS->body()) {
3865 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003866 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003867 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003868 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003869 return ESR;
3870 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003871 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003872 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003873
3874 case Stmt::IfStmtClass: {
3875 const IfStmt *IS = cast<IfStmt>(S);
3876
3877 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003878 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003879 if (const Stmt *Init = IS->getInit()) {
3880 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3881 if (ESR != ESR_Succeeded)
3882 return ESR;
3883 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003884 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003885 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003886 return ESR_Failed;
3887
3888 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3889 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3890 if (ESR != ESR_Succeeded)
3891 return ESR;
3892 }
3893 return ESR_Succeeded;
3894 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003895
3896 case Stmt::WhileStmtClass: {
3897 const WhileStmt *WS = cast<WhileStmt>(S);
3898 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003899 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003900 bool Continue;
3901 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3902 Continue))
3903 return ESR_Failed;
3904 if (!Continue)
3905 break;
3906
3907 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3908 if (ESR != ESR_Continue)
3909 return ESR;
3910 }
3911 return ESR_Succeeded;
3912 }
3913
3914 case Stmt::DoStmtClass: {
3915 const DoStmt *DS = cast<DoStmt>(S);
3916 bool Continue;
3917 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003918 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003919 if (ESR != ESR_Continue)
3920 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003921 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003922
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003924 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3925 return ESR_Failed;
3926 } while (Continue);
3927 return ESR_Succeeded;
3928 }
3929
3930 case Stmt::ForStmtClass: {
3931 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003932 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003933 if (FS->getInit()) {
3934 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3935 if (ESR != ESR_Succeeded)
3936 return ESR;
3937 }
3938 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003939 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003940 bool Continue = true;
3941 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3942 FS->getCond(), Continue))
3943 return ESR_Failed;
3944 if (!Continue)
3945 break;
3946
3947 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3948 if (ESR != ESR_Continue)
3949 return ESR;
3950
Richard Smith08d6a2c2013-07-24 07:11:57 +00003951 if (FS->getInc()) {
3952 FullExpressionRAII IncScope(Info);
3953 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3954 return ESR_Failed;
3955 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003956 }
3957 return ESR_Succeeded;
3958 }
3959
Richard Smith896e0d72013-05-06 06:51:17 +00003960 case Stmt::CXXForRangeStmtClass: {
3961 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003962 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003963
3964 // Initialize the __range variable.
3965 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3966 if (ESR != ESR_Succeeded)
3967 return ESR;
3968
3969 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003970 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3971 if (ESR != ESR_Succeeded)
3972 return ESR;
3973 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003974 if (ESR != ESR_Succeeded)
3975 return ESR;
3976
3977 while (true) {
3978 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 {
3980 bool Continue = true;
3981 FullExpressionRAII CondExpr(Info);
3982 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3983 return ESR_Failed;
3984 if (!Continue)
3985 break;
3986 }
Richard Smith896e0d72013-05-06 06:51:17 +00003987
3988 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003990 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3991 if (ESR != ESR_Succeeded)
3992 return ESR;
3993
3994 // Loop body.
3995 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3996 if (ESR != ESR_Continue)
3997 return ESR;
3998
3999 // Increment: ++__begin
4000 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4001 return ESR_Failed;
4002 }
4003
4004 return ESR_Succeeded;
4005 }
4006
Richard Smith496ddcf2013-05-12 17:32:42 +00004007 case Stmt::SwitchStmtClass:
4008 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4009
Richard Smith4e18ca52013-05-06 05:56:11 +00004010 case Stmt::ContinueStmtClass:
4011 return ESR_Continue;
4012
4013 case Stmt::BreakStmtClass:
4014 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004015
4016 case Stmt::LabelStmtClass:
4017 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4018
4019 case Stmt::AttributedStmtClass:
4020 // As a general principle, C++11 attributes can be ignored without
4021 // any semantic impact.
4022 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4023 Case);
4024
4025 case Stmt::CaseStmtClass:
4026 case Stmt::DefaultStmtClass:
4027 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004028 }
4029}
4030
Richard Smithcc36f692011-12-22 02:22:31 +00004031/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4032/// default constructor. If so, we'll fold it whether or not it's marked as
4033/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4034/// so we need special handling.
4035static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004036 const CXXConstructorDecl *CD,
4037 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004038 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4039 return false;
4040
Richard Smith66e05fe2012-01-18 05:21:49 +00004041 // Value-initialization does not call a trivial default constructor, so such a
4042 // call is a core constant expression whether or not the constructor is
4043 // constexpr.
4044 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004045 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004046 // FIXME: If DiagDecl is an implicitly-declared special member function,
4047 // we should be much more explicit about why it's not constexpr.
4048 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4049 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4050 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004051 } else {
4052 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4053 }
4054 }
4055 return true;
4056}
4057
Richard Smith357362d2011-12-13 06:39:58 +00004058/// CheckConstexprFunction - Check that a function can be called in a constant
4059/// expression.
4060static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4061 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004062 const FunctionDecl *Definition,
4063 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004064 // Potential constant expressions can contain calls to declared, but not yet
4065 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004066 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004067 Declaration->isConstexpr())
4068 return false;
4069
Richard Smith0838f3a2013-05-14 05:18:44 +00004070 // Bail out with no diagnostic if the function declaration itself is invalid.
4071 // We will have produced a relevant diagnostic while parsing it.
4072 if (Declaration->isInvalidDecl())
4073 return false;
4074
Richard Smith357362d2011-12-13 06:39:58 +00004075 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004076 if (Definition && Definition->isConstexpr() &&
4077 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004078 return true;
4079
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004080 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004081 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004082
Richard Smith5179eb72016-06-28 19:03:57 +00004083 // If this function is not constexpr because it is an inherited
4084 // non-constexpr constructor, diagnose that directly.
4085 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4086 if (CD && CD->isInheritingConstructor()) {
4087 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4088 if (!Inherited->isConstexpr())
4089 DiagDecl = CD = Inherited;
4090 }
4091
4092 // FIXME: If DiagDecl is an implicitly-declared special member function
4093 // or an inheriting constructor, we should be much more explicit about why
4094 // it's not constexpr.
4095 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004096 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004097 << CD->getInheritedConstructor().getConstructor()->getParent();
4098 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004099 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004100 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004101 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4102 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004103 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004104 }
4105 return false;
4106}
4107
Richard Smithbe6dd812014-11-19 21:27:17 +00004108/// Determine if a class has any fields that might need to be copied by a
4109/// trivial copy or move operation.
4110static bool hasFields(const CXXRecordDecl *RD) {
4111 if (!RD || RD->isEmpty())
4112 return false;
4113 for (auto *FD : RD->fields()) {
4114 if (FD->isUnnamedBitfield())
4115 continue;
4116 return true;
4117 }
4118 for (auto &Base : RD->bases())
4119 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4120 return true;
4121 return false;
4122}
4123
Richard Smithd62306a2011-11-10 06:34:14 +00004124namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004125typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004126}
4127
4128/// EvaluateArgs - Evaluate the arguments to a function call.
4129static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4130 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004131 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004132 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004133 I != E; ++I) {
4134 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4135 // If we're checking for a potential constant expression, evaluate all
4136 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004137 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004138 return false;
4139 Success = false;
4140 }
4141 }
4142 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004143}
4144
Richard Smith254a73d2011-10-28 22:34:42 +00004145/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004146static bool HandleFunctionCall(SourceLocation CallLoc,
4147 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004148 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004149 EvalInfo &Info, APValue &Result,
4150 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004151 ArgVector ArgValues(Args.size());
4152 if (!EvaluateArgs(Args, ArgValues, Info))
4153 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004154
Richard Smith253c2a32012-01-27 01:14:48 +00004155 if (!Info.CheckCallLimit(CallLoc))
4156 return false;
4157
4158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004159
4160 // For a trivial copy or move assignment, perform an APValue copy. This is
4161 // essential for unions, where the operations performed by the assignment
4162 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004163 //
4164 // Skip this for non-union classes with no fields; in that case, the defaulted
4165 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004166 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004167 if (MD && MD->isDefaulted() &&
4168 (MD->getParent()->isUnion() ||
4169 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004170 assert(This &&
4171 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4172 LValue RHS;
4173 RHS.setFrom(Info.Ctx, ArgValues[0]);
4174 APValue RHSValue;
4175 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4176 RHS, RHSValue))
4177 return false;
4178 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4179 RHSValue))
4180 return false;
4181 This->moveInto(Result);
4182 return true;
4183 }
4184
Richard Smith52a980a2015-08-28 02:43:42 +00004185 StmtResult Ret = {Result, ResultSlot};
4186 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004187 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004188 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004189 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004190 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004191 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004192 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004193}
4194
Richard Smithd62306a2011-11-10 06:34:14 +00004195/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004196static bool HandleConstructorCall(const Expr *E, const LValue &This,
4197 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004198 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004199 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004200 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004201 if (!Info.CheckCallLimit(CallLoc))
4202 return false;
4203
Richard Smith3607ffe2012-02-13 03:54:03 +00004204 const CXXRecordDecl *RD = Definition->getParent();
4205 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004206 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004207 return false;
4208 }
4209
Richard Smith5179eb72016-06-28 19:03:57 +00004210 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004211
Richard Smith52a980a2015-08-28 02:43:42 +00004212 // FIXME: Creating an APValue just to hold a nonexistent return value is
4213 // wasteful.
4214 APValue RetVal;
4215 StmtResult Ret = {RetVal, nullptr};
4216
Richard Smith5179eb72016-06-28 19:03:57 +00004217 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004218 if (Definition->isDelegatingConstructor()) {
4219 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004220 {
4221 FullExpressionRAII InitScope(Info);
4222 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4223 return false;
4224 }
Richard Smith52a980a2015-08-28 02:43:42 +00004225 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004226 }
4227
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004228 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004229 // essential for unions (or classes with anonymous union members), where the
4230 // operations performed by the constructor cannot be represented by
4231 // ctor-initializers.
4232 //
4233 // Skip this for empty non-union classes; we should not perform an
4234 // lvalue-to-rvalue conversion on them because their copy constructor does not
4235 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004236 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004237 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004238 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004239 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004240 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004241 return handleLValueToRValueConversion(
4242 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4243 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004244 }
4245
4246 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004247 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004248 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004249 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004250
John McCalld7bca762012-05-01 00:38:49 +00004251 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004252 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4253
Richard Smith08d6a2c2013-07-24 07:11:57 +00004254 // A scope for temporaries lifetime-extended by reference members.
4255 BlockScopeRAII LifetimeExtendedScope(Info);
4256
Richard Smith253c2a32012-01-27 01:14:48 +00004257 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004258 unsigned BasesSeen = 0;
4259#ifndef NDEBUG
4260 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4261#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004262 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004263 LValue Subobject = This;
4264 APValue *Value = &Result;
4265
4266 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004267 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004268 if (I->isBaseInitializer()) {
4269 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004270#ifndef NDEBUG
4271 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004272 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004273 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4274 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4275 "base class initializers not in expected order");
4276 ++BaseIt;
4277#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004278 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004279 BaseType->getAsCXXRecordDecl(), &Layout))
4280 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004281 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004282 } else if ((FD = I->getMember())) {
4283 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004284 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004285 if (RD->isUnion()) {
4286 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004287 Value = &Result.getUnionValue();
4288 } else {
4289 Value = &Result.getStructField(FD->getFieldIndex());
4290 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004291 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004292 // Walk the indirect field decl's chain to find the object to initialize,
4293 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004294 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004295 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004296 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4297 // Switch the union field if it differs. This happens if we had
4298 // preceding zero-initialization, and we're now initializing a union
4299 // subobject other than the first.
4300 // FIXME: In this case, the values of the other subobjects are
4301 // specified, since zero-initialization sets all padding bits to zero.
4302 if (Value->isUninit() ||
4303 (Value->isUnion() && Value->getUnionField() != FD)) {
4304 if (CD->isUnion())
4305 *Value = APValue(FD);
4306 else
4307 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004308 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004309 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004310 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004311 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004312 if (CD->isUnion())
4313 Value = &Value->getUnionValue();
4314 else
4315 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004316 }
Richard Smithd62306a2011-11-10 06:34:14 +00004317 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004318 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004319 }
Richard Smith253c2a32012-01-27 01:14:48 +00004320
Richard Smith08d6a2c2013-07-24 07:11:57 +00004321 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004322 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4323 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004324 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004325 // If we're checking for a potential constant expression, evaluate all
4326 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004327 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004328 return false;
4329 Success = false;
4330 }
Richard Smithd62306a2011-11-10 06:34:14 +00004331 }
4332
Richard Smithd9f663b2013-04-22 15:31:51 +00004333 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004334 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004335}
4336
Richard Smith5179eb72016-06-28 19:03:57 +00004337static bool HandleConstructorCall(const Expr *E, const LValue &This,
4338 ArrayRef<const Expr*> Args,
4339 const CXXConstructorDecl *Definition,
4340 EvalInfo &Info, APValue &Result) {
4341 ArgVector ArgValues(Args.size());
4342 if (!EvaluateArgs(Args, ArgValues, Info))
4343 return false;
4344
4345 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4346 Info, Result);
4347}
4348
Eli Friedman9a156e52008-11-12 09:44:48 +00004349//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004350// Generic Evaluation
4351//===----------------------------------------------------------------------===//
4352namespace {
4353
Aaron Ballman68af21c2014-01-03 19:26:43 +00004354template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004355class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004356 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004357private:
Richard Smith52a980a2015-08-28 02:43:42 +00004358 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004359 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004360 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004361 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004362 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004363 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004364 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004365
Richard Smith17100ba2012-02-16 02:46:34 +00004366 // Check whether a conditional operator with a non-constant condition is a
4367 // potential constant expression. If neither arm is a potential constant
4368 // expression, then the conditional operator is not either.
4369 template<typename ConditionalOperator>
4370 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004371 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004372
4373 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004374 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004375 {
Richard Smith17100ba2012-02-16 02:46:34 +00004376 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004377 StmtVisitorTy::Visit(E->getFalseExpr());
4378 if (Diag.empty())
4379 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004380 }
Richard Smith17100ba2012-02-16 02:46:34 +00004381
George Burgess IV8c892b52016-05-25 22:31:54 +00004382 {
4383 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004384 Diag.clear();
4385 StmtVisitorTy::Visit(E->getTrueExpr());
4386 if (Diag.empty())
4387 return;
4388 }
4389
4390 Error(E, diag::note_constexpr_conditional_never_const);
4391 }
4392
4393
4394 template<typename ConditionalOperator>
4395 bool HandleConditionalOperator(const ConditionalOperator *E) {
4396 bool BoolResult;
4397 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004398 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004399 CheckPotentialConstantConditional(E);
4400 return false;
4401 }
4402
4403 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4404 return StmtVisitorTy::Visit(EvalExpr);
4405 }
4406
Peter Collingbournee9200682011-05-13 03:29:01 +00004407protected:
4408 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004409 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004410 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4411
Richard Smith92b1ce02011-12-12 09:28:41 +00004412 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004413 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004414 }
4415
Aaron Ballman68af21c2014-01-03 19:26:43 +00004416 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004417
4418public:
4419 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4420
4421 EvalInfo &getEvalInfo() { return Info; }
4422
Richard Smithf57d8cb2011-12-09 22:58:01 +00004423 /// Report an evaluation error. This should only be called when an error is
4424 /// first discovered. When propagating an error, just return false.
4425 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004426 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004427 return false;
4428 }
4429 bool Error(const Expr *E) {
4430 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4431 }
4432
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004434 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004435 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004437 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004438 }
4439
Aaron Ballman68af21c2014-01-03 19:26:43 +00004440 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004441 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004442 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004443 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004444 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004445 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004446 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004447 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004448 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004449 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004450 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004451 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004452 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004453 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004455 // The initializer may not have been parsed yet, or might be erroneous.
4456 if (!E->getExpr())
4457 return Error(E);
4458 return StmtVisitorTy::Visit(E->getExpr());
4459 }
Richard Smith5894a912011-12-19 22:12:41 +00004460 // We cannot create any objects for which cleanups are required, so there is
4461 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004464
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004466 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4467 return static_cast<Derived*>(this)->VisitCastExpr(E);
4468 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004470 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4471 return static_cast<Derived*>(this)->VisitCastExpr(E);
4472 }
4473
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004475 switch (E->getOpcode()) {
4476 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004477 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004478
4479 case BO_Comma:
4480 VisitIgnoredValue(E->getLHS());
4481 return StmtVisitorTy::Visit(E->getRHS());
4482
4483 case BO_PtrMemD:
4484 case BO_PtrMemI: {
4485 LValue Obj;
4486 if (!HandleMemberPointerAccess(Info, E, Obj))
4487 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004488 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004489 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004490 return false;
4491 return DerivedSuccess(Result, E);
4492 }
4493 }
4494 }
4495
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004497 // Evaluate and cache the common expression. We treat it as a temporary,
4498 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004499 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004500 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004501 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004502
Richard Smith17100ba2012-02-16 02:46:34 +00004503 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004504 }
4505
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004507 bool IsBcpCall = false;
4508 // If the condition (ignoring parens) is a __builtin_constant_p call,
4509 // the result is a constant expression if it can be folded without
4510 // side-effects. This is an important GNU extension. See GCC PR38377
4511 // for discussion.
4512 if (const CallExpr *CallCE =
4513 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004514 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004515 IsBcpCall = true;
4516
4517 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4518 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004519 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004520 return false;
4521
Richard Smith6d4c6582013-11-05 22:18:15 +00004522 FoldConstant Fold(Info, IsBcpCall);
4523 if (!HandleConditionalOperator(E)) {
4524 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004525 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004526 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004527
4528 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 }
4530
Aaron Ballman68af21c2014-01-03 19:26:43 +00004531 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004532 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4533 return DerivedSuccess(*Value, E);
4534
4535 const Expr *Source = E->getSourceExpr();
4536 if (!Source)
4537 return Error(E);
4538 if (Source == E) { // sanity checking.
4539 assert(0 && "OpaqueValueExpr recursively refers to itself");
4540 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004541 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004542 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004543 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004544
Aaron Ballman68af21c2014-01-03 19:26:43 +00004545 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004546 APValue Result;
4547 if (!handleCallExpr(E, Result, nullptr))
4548 return false;
4549 return DerivedSuccess(Result, E);
4550 }
4551
4552 bool handleCallExpr(const CallExpr *E, APValue &Result,
4553 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004554 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004555 QualType CalleeType = Callee->getType();
4556
Craig Topper36250ad2014-05-12 05:36:57 +00004557 const FunctionDecl *FD = nullptr;
4558 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004559 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004560 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004561
Richard Smithe97cbd72011-11-11 04:05:33 +00004562 // Extract function decl and 'this' pointer from the callee.
4563 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004564 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4566 // Explicit bound member calls, such as x.f() or p->g();
4567 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004568 return false;
4569 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004570 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004571 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004572 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4573 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004574 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4575 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004576 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004577 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004578 return Error(Callee);
4579
4580 FD = dyn_cast<FunctionDecl>(Member);
4581 if (!FD)
4582 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004583 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004584 LValue Call;
4585 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004586 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004587
Richard Smitha8105bc2012-01-06 16:39:00 +00004588 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004590 FD = dyn_cast_or_null<FunctionDecl>(
4591 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004592 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004593 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004594 // Don't call function pointers which have been cast to some other type.
4595 // Per DR (no number yet), the caller and callee can differ in noexcept.
4596 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4597 CalleeType->getPointeeType(), FD->getType())) {
4598 return Error(E);
4599 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004600
4601 // Overloaded operator calls to member functions are represented as normal
4602 // calls with '*this' as the first argument.
4603 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4604 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004605 // FIXME: When selecting an implicit conversion for an overloaded
4606 // operator delete, we sometimes try to evaluate calls to conversion
4607 // operators without a 'this' parameter!
4608 if (Args.empty())
4609 return Error(E);
4610
Richard Smithe97cbd72011-11-11 04:05:33 +00004611 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4612 return false;
4613 This = &ThisVal;
4614 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004615 } else if (MD && MD->isLambdaStaticInvoker()) {
4616 // Map the static invoker for the lambda back to the call operator.
4617 // Conveniently, we don't have to slice out the 'this' argument (as is
4618 // being done for the non-static case), since a static member function
4619 // doesn't have an implicit argument passed in.
4620 const CXXRecordDecl *ClosureClass = MD->getParent();
4621 assert(
4622 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4623 "Number of captures must be zero for conversion to function-ptr");
4624
4625 const CXXMethodDecl *LambdaCallOp =
4626 ClosureClass->getLambdaCallOperator();
4627
4628 // Set 'FD', the function that will be called below, to the call
4629 // operator. If the closure object represents a generic lambda, find
4630 // the corresponding specialization of the call operator.
4631
4632 if (ClosureClass->isGenericLambda()) {
4633 assert(MD->isFunctionTemplateSpecialization() &&
4634 "A generic lambda's static-invoker function must be a "
4635 "template specialization");
4636 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4637 FunctionTemplateDecl *CallOpTemplate =
4638 LambdaCallOp->getDescribedFunctionTemplate();
4639 void *InsertPos = nullptr;
4640 FunctionDecl *CorrespondingCallOpSpecialization =
4641 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4642 assert(CorrespondingCallOpSpecialization &&
4643 "We must always have a function call operator specialization "
4644 "that corresponds to our static invoker specialization");
4645 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4646 } else
4647 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004648 }
4649
Faisal Valid92e7492017-01-08 18:56:11 +00004650
Richard Smithe97cbd72011-11-11 04:05:33 +00004651 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004653
Richard Smith47b34932012-02-01 02:39:43 +00004654 if (This && !This->checkSubobject(Info, E, CSK_This))
4655 return false;
4656
Richard Smith3607ffe2012-02-13 03:54:03 +00004657 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4658 // calls to such functions in constant expressions.
4659 if (This && !HasQualifier &&
4660 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4661 return Error(E, diag::note_constexpr_virtual_call);
4662
Craig Topper36250ad2014-05-12 05:36:57 +00004663 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004664 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004665
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004666 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004667 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4668 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004669 return false;
4670
Richard Smith52a980a2015-08-28 02:43:42 +00004671 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004672 }
4673
Aaron Ballman68af21c2014-01-03 19:26:43 +00004674 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004675 return StmtVisitorTy::Visit(E->getInitializer());
4676 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004678 if (E->getNumInits() == 0)
4679 return DerivedZeroInitialization(E);
4680 if (E->getNumInits() == 1)
4681 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004682 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004683 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004684 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004685 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004686 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004687 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004688 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004689 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004690 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004691 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004692 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004693
Richard Smithd62306a2011-11-10 06:34:14 +00004694 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004695 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004696 assert(!E->isArrow() && "missing call to bound member function?");
4697
Richard Smith2e312c82012-03-03 22:46:17 +00004698 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004699 if (!Evaluate(Val, Info, E->getBase()))
4700 return false;
4701
4702 QualType BaseTy = E->getBase()->getType();
4703
4704 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004705 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004706 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004707 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004708 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4709
Richard Smith3229b742013-05-05 21:17:10 +00004710 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004711 SubobjectDesignator Designator(BaseTy);
4712 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004713
Richard Smith3229b742013-05-05 21:17:10 +00004714 APValue Result;
4715 return extractSubobject(Info, E, Obj, Designator, Result) &&
4716 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004717 }
4718
Aaron Ballman68af21c2014-01-03 19:26:43 +00004719 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004720 switch (E->getCastKind()) {
4721 default:
4722 break;
4723
Richard Smitha23ab512013-05-23 00:30:41 +00004724 case CK_AtomicToNonAtomic: {
4725 APValue AtomicVal;
4726 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4727 return false;
4728 return DerivedSuccess(AtomicVal, E);
4729 }
4730
Richard Smith11562c52011-10-28 17:51:58 +00004731 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004732 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004733 return StmtVisitorTy::Visit(E->getSubExpr());
4734
4735 case CK_LValueToRValue: {
4736 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004737 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4738 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004739 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004740 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004741 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004742 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004743 return false;
4744 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004745 }
4746 }
4747
Richard Smithf57d8cb2011-12-09 22:58:01 +00004748 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004749 }
4750
Aaron Ballman68af21c2014-01-03 19:26:43 +00004751 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004752 return VisitUnaryPostIncDec(UO);
4753 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004755 return VisitUnaryPostIncDec(UO);
4756 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004758 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004759 return Error(UO);
4760
4761 LValue LVal;
4762 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4763 return false;
4764 APValue RVal;
4765 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4766 UO->isIncrementOp(), &RVal))
4767 return false;
4768 return DerivedSuccess(RVal, UO);
4769 }
4770
Aaron Ballman68af21c2014-01-03 19:26:43 +00004771 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004772 // We will have checked the full-expressions inside the statement expression
4773 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004774 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004775 return Error(E);
4776
Richard Smith08d6a2c2013-07-24 07:11:57 +00004777 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004778 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004779 if (CS->body_empty())
4780 return true;
4781
Richard Smith51f03172013-06-20 03:00:05 +00004782 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4783 BE = CS->body_end();
4784 /**/; ++BI) {
4785 if (BI + 1 == BE) {
4786 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4787 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004788 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004789 diag::note_constexpr_stmt_expr_unsupported);
4790 return false;
4791 }
4792 return this->Visit(FinalExpr);
4793 }
4794
4795 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004796 StmtResult Result = { ReturnValue, nullptr };
4797 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004798 if (ESR != ESR_Succeeded) {
4799 // FIXME: If the statement-expression terminated due to 'return',
4800 // 'break', or 'continue', it would be nice to propagate that to
4801 // the outer statement evaluation rather than bailing out.
4802 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004803 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004804 diag::note_constexpr_stmt_expr_unsupported);
4805 return false;
4806 }
4807 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004808
4809 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004810 }
4811
Richard Smith4a678122011-10-24 18:44:57 +00004812 /// Visit a value which is evaluated, but whose value is ignored.
4813 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004814 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004815 }
David Majnemere9807b22016-02-26 04:23:19 +00004816
4817 /// Potentially visit a MemberExpr's base expression.
4818 void VisitIgnoredBaseExpression(const Expr *E) {
4819 // While MSVC doesn't evaluate the base expression, it does diagnose the
4820 // presence of side-effecting behavior.
4821 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4822 return;
4823 VisitIgnoredValue(E);
4824 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004825};
4826
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004827}
Peter Collingbournee9200682011-05-13 03:29:01 +00004828
4829//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004830// Common base class for lvalue and temporary evaluation.
4831//===----------------------------------------------------------------------===//
4832namespace {
4833template<class Derived>
4834class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004836protected:
4837 LValue &Result;
4838 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004839 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004840
4841 bool Success(APValue::LValueBase B) {
4842 Result.set(B);
4843 return true;
4844 }
4845
4846public:
4847 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4848 ExprEvaluatorBaseTy(Info), Result(Result) {}
4849
Richard Smith2e312c82012-03-03 22:46:17 +00004850 bool Success(const APValue &V, const Expr *E) {
4851 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004852 return true;
4853 }
Richard Smith027bf112011-11-17 22:56:20 +00004854
Richard Smith027bf112011-11-17 22:56:20 +00004855 bool VisitMemberExpr(const MemberExpr *E) {
4856 // Handle non-static data members.
4857 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004858 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004859 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004860 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004861 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004862 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004863 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004864 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004865 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004866 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004867 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004868 BaseTy = E->getBase()->getType();
4869 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004870 if (!EvalOK) {
4871 if (!this->Info.allowInvalidBaseExpr())
4872 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004873 Result.setInvalid(E);
4874 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004875 }
Richard Smith027bf112011-11-17 22:56:20 +00004876
Richard Smith1b78b3d2012-01-25 22:15:11 +00004877 const ValueDecl *MD = E->getMemberDecl();
4878 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4879 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4880 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4881 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004882 if (!HandleLValueMember(this->Info, E, Result, FD))
4883 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004884 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004885 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4886 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004887 } else
4888 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004889
Richard Smith1b78b3d2012-01-25 22:15:11 +00004890 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004891 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004892 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004893 RefValue))
4894 return false;
4895 return Success(RefValue, E);
4896 }
4897 return true;
4898 }
4899
4900 bool VisitBinaryOperator(const BinaryOperator *E) {
4901 switch (E->getOpcode()) {
4902 default:
4903 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4904
4905 case BO_PtrMemD:
4906 case BO_PtrMemI:
4907 return HandleMemberPointerAccess(this->Info, E, Result);
4908 }
4909 }
4910
4911 bool VisitCastExpr(const CastExpr *E) {
4912 switch (E->getCastKind()) {
4913 default:
4914 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4915
4916 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004917 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004918 if (!this->Visit(E->getSubExpr()))
4919 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004920
4921 // Now figure out the necessary offset to add to the base LV to get from
4922 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004923 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4924 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004925 }
4926 }
4927};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004928}
Richard Smith027bf112011-11-17 22:56:20 +00004929
4930//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004931// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004932//
4933// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4934// function designators (in C), decl references to void objects (in C), and
4935// temporaries (if building with -Wno-address-of-temporary).
4936//
4937// LValue evaluation produces values comprising a base expression of one of the
4938// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004939// - Declarations
4940// * VarDecl
4941// * FunctionDecl
4942// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004943// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004944// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004945// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004946// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004947// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004948// * ObjCEncodeExpr
4949// * AddrLabelExpr
4950// * BlockExpr
4951// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004952// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004953// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004954// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004955// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4956// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004957// * A MaterializeTemporaryExpr that has static storage duration, with no
4958// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004959// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004960//===----------------------------------------------------------------------===//
4961namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004962class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004963 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004964public:
Richard Smith027bf112011-11-17 22:56:20 +00004965 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4966 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004967
Richard Smith11562c52011-10-28 17:51:58 +00004968 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004969 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004970
Peter Collingbournee9200682011-05-13 03:29:01 +00004971 bool VisitDeclRefExpr(const DeclRefExpr *E);
4972 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004973 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004974 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4975 bool VisitMemberExpr(const MemberExpr *E);
4976 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4977 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004978 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004979 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004980 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4981 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004982 bool VisitUnaryReal(const UnaryOperator *E);
4983 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004984 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4985 return VisitUnaryPreIncDec(UO);
4986 }
4987 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4988 return VisitUnaryPreIncDec(UO);
4989 }
Richard Smith3229b742013-05-05 21:17:10 +00004990 bool VisitBinAssign(const BinaryOperator *BO);
4991 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004992
Peter Collingbournee9200682011-05-13 03:29:01 +00004993 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004994 switch (E->getCastKind()) {
4995 default:
Richard Smith027bf112011-11-17 22:56:20 +00004996 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004997
Eli Friedmance3e02a2011-10-11 00:13:24 +00004998 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004999 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005000 if (!Visit(E->getSubExpr()))
5001 return false;
5002 Result.Designator.setInvalid();
5003 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005004
Richard Smith027bf112011-11-17 22:56:20 +00005005 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005006 if (!Visit(E->getSubExpr()))
5007 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005008 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005009 }
5010 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005011};
5012} // end anonymous namespace
5013
Richard Smith11562c52011-10-28 17:51:58 +00005014/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005015/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005016/// * function designators in C, and
5017/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005018/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00005019static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
5020 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005021 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00005022 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005023}
5024
Peter Collingbournee9200682011-05-13 03:29:01 +00005025bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005026 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005027 return Success(FD);
5028 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005029 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005030 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005031 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005032 return Error(E);
5033}
Richard Smith733237d2011-10-24 23:14:33 +00005034
Faisal Vali0528a312016-11-13 06:09:16 +00005035
Richard Smith11562c52011-10-28 17:51:58 +00005036bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00005037 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005038 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5039 // Only if a local variable was declared in the function currently being
5040 // evaluated, do we expect to be able to find its value in the current
5041 // frame. (Otherwise it was likely declared in an enclosing context and
5042 // could either have a valid evaluatable value (for e.g. a constexpr
5043 // variable) or be ill-formed (and trigger an appropriate evaluation
5044 // diagnostic)).
5045 if (Info.CurrentCall->Callee &&
5046 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5047 Frame = Info.CurrentCall;
5048 }
5049 }
Richard Smith3229b742013-05-05 21:17:10 +00005050
Richard Smithfec09922011-11-01 16:57:24 +00005051 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005052 if (Frame) {
5053 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005054 return true;
5055 }
Richard Smithce40ad62011-11-12 22:28:03 +00005056 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005057 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005058
Richard Smith3229b742013-05-05 21:17:10 +00005059 APValue *V;
5060 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005061 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005062 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005063 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005064 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005065 return false;
5066 }
Richard Smith3229b742013-05-05 21:17:10 +00005067 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005068}
5069
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005070bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5071 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005072 // Walk through the expression to find the materialized temporary itself.
5073 SmallVector<const Expr *, 2> CommaLHSs;
5074 SmallVector<SubobjectAdjustment, 2> Adjustments;
5075 const Expr *Inner = E->GetTemporaryExpr()->
5076 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005077
Richard Smith84401042013-06-03 05:03:02 +00005078 // If we passed any comma operators, evaluate their LHSs.
5079 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5080 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5081 return false;
5082
Richard Smithe6c01442013-06-05 00:46:14 +00005083 // A materialized temporary with static storage duration can appear within the
5084 // result of a constant expression evaluation, so we need to preserve its
5085 // value for use outside this evaluation.
5086 APValue *Value;
5087 if (E->getStorageDuration() == SD_Static) {
5088 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005089 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005090 Result.set(E);
5091 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005092 Value = &Info.CurrentCall->
5093 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005094 Result.set(E, Info.CurrentCall->Index);
5095 }
5096
Richard Smithea4ad5d2013-06-06 08:19:16 +00005097 QualType Type = Inner->getType();
5098
Richard Smith84401042013-06-03 05:03:02 +00005099 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005100 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5101 (E->getStorageDuration() == SD_Static &&
5102 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5103 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005104 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005105 }
Richard Smith84401042013-06-03 05:03:02 +00005106
5107 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005108 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5109 --I;
5110 switch (Adjustments[I].Kind) {
5111 case SubobjectAdjustment::DerivedToBaseAdjustment:
5112 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5113 Type, Result))
5114 return false;
5115 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5116 break;
5117
5118 case SubobjectAdjustment::FieldAdjustment:
5119 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5120 return false;
5121 Type = Adjustments[I].Field->getType();
5122 break;
5123
5124 case SubobjectAdjustment::MemberPointerAdjustment:
5125 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5126 Adjustments[I].Ptr.RHS))
5127 return false;
5128 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5129 break;
5130 }
5131 }
5132
5133 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005134}
5135
Peter Collingbournee9200682011-05-13 03:29:01 +00005136bool
5137LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005138 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5139 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005140 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5141 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005142 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005143}
5144
Richard Smith6e525142011-12-27 12:18:28 +00005145bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005146 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005147 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005148
Faisal Valie690b7a2016-07-02 22:34:24 +00005149 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005150 << E->getExprOperand()->getType()
5151 << E->getExprOperand()->getSourceRange();
5152 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005153}
5154
Francois Pichet0066db92012-04-16 04:08:35 +00005155bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5156 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005157}
Francois Pichet0066db92012-04-16 04:08:35 +00005158
Peter Collingbournee9200682011-05-13 03:29:01 +00005159bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005160 // Handle static data members.
5161 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005162 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005163 return VisitVarDecl(E, VD);
5164 }
5165
Richard Smith254a73d2011-10-28 22:34:42 +00005166 // Handle static member functions.
5167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5168 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005169 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005170 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005171 }
5172 }
5173
Richard Smithd62306a2011-11-10 06:34:14 +00005174 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005175 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005176}
5177
Peter Collingbournee9200682011-05-13 03:29:01 +00005178bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005179 // FIXME: Deal with vectors as array subscript bases.
5180 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005181 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005182
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005183 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005184 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005185
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005186 APSInt Index;
5187 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005188 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005189
Richard Smithd6cc1982017-01-31 02:23:02 +00005190 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005191}
Eli Friedman9a156e52008-11-12 09:44:48 +00005192
Peter Collingbournee9200682011-05-13 03:29:01 +00005193bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005194 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005195}
5196
Richard Smith66c96992012-02-18 22:04:06 +00005197bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5198 if (!Visit(E->getSubExpr()))
5199 return false;
5200 // __real is a no-op on scalar lvalues.
5201 if (E->getSubExpr()->getType()->isAnyComplexType())
5202 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5203 return true;
5204}
5205
5206bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5207 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5208 "lvalue __imag__ on scalar?");
5209 if (!Visit(E->getSubExpr()))
5210 return false;
5211 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5212 return true;
5213}
5214
Richard Smith243ef902013-05-05 23:31:59 +00005215bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005216 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005217 return Error(UO);
5218
5219 if (!this->Visit(UO->getSubExpr()))
5220 return false;
5221
Richard Smith243ef902013-05-05 23:31:59 +00005222 return handleIncDec(
5223 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005224 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005225}
5226
5227bool LValueExprEvaluator::VisitCompoundAssignOperator(
5228 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005229 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005230 return Error(CAO);
5231
Richard Smith3229b742013-05-05 21:17:10 +00005232 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005233
5234 // The overall lvalue result is the result of evaluating the LHS.
5235 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005236 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005237 Evaluate(RHS, this->Info, CAO->getRHS());
5238 return false;
5239 }
5240
Richard Smith3229b742013-05-05 21:17:10 +00005241 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5242 return false;
5243
Richard Smith43e77732013-05-07 04:50:00 +00005244 return handleCompoundAssignment(
5245 this->Info, CAO,
5246 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5247 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005248}
5249
5250bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005251 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005252 return Error(E);
5253
Richard Smith3229b742013-05-05 21:17:10 +00005254 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005255
5256 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005257 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005258 Evaluate(NewVal, this->Info, E->getRHS());
5259 return false;
5260 }
5261
Richard Smith3229b742013-05-05 21:17:10 +00005262 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5263 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005264
5265 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005266 NewVal);
5267}
5268
Eli Friedman9a156e52008-11-12 09:44:48 +00005269//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005270// Pointer Evaluation
5271//===----------------------------------------------------------------------===//
5272
George Burgess IVe3763372016-12-22 02:50:20 +00005273/// \brief Attempts to compute the number of bytes available at the pointer
5274/// returned by a function with the alloc_size attribute. Returns true if we
5275/// were successful. Places an unsigned number into `Result`.
5276///
5277/// This expects the given CallExpr to be a call to a function with an
5278/// alloc_size attribute.
5279static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5280 const CallExpr *Call,
5281 llvm::APInt &Result) {
5282 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5283
5284 // alloc_size args are 1-indexed, 0 means not present.
5285 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5286 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5287 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5288 if (Call->getNumArgs() <= SizeArgNo)
5289 return false;
5290
5291 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5292 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5293 return false;
5294 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5295 return false;
5296 Into = Into.zextOrSelf(BitsInSizeT);
5297 return true;
5298 };
5299
5300 APSInt SizeOfElem;
5301 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5302 return false;
5303
5304 if (!AllocSize->getNumElemsParam()) {
5305 Result = std::move(SizeOfElem);
5306 return true;
5307 }
5308
5309 APSInt NumberOfElems;
5310 // Argument numbers start at 1
5311 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5312 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5313 return false;
5314
5315 bool Overflow;
5316 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5317 if (Overflow)
5318 return false;
5319
5320 Result = std::move(BytesAvailable);
5321 return true;
5322}
5323
5324/// \brief Convenience function. LVal's base must be a call to an alloc_size
5325/// function.
5326static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5327 const LValue &LVal,
5328 llvm::APInt &Result) {
5329 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5330 "Can't get the size of a non alloc_size function");
5331 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5332 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5333 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5334}
5335
5336/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5337/// a function with the alloc_size attribute. If it was possible to do so, this
5338/// function will return true, make Result's Base point to said function call,
5339/// and mark Result's Base as invalid.
5340static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5341 LValue &Result) {
5342 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5343 return false;
5344
5345 // Because we do no form of static analysis, we only support const variables.
5346 //
5347 // Additionally, we can't support parameters, nor can we support static
5348 // variables (in the latter case, use-before-assign isn't UB; in the former,
5349 // we have no clue what they'll be assigned to).
5350 const auto *VD =
5351 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5352 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5353 return false;
5354
5355 const Expr *Init = VD->getAnyInitializer();
5356 if (!Init)
5357 return false;
5358
5359 const Expr *E = Init->IgnoreParens();
5360 if (!tryUnwrapAllocSizeCall(E))
5361 return false;
5362
5363 // Store E instead of E unwrapped so that the type of the LValue's base is
5364 // what the user wanted.
5365 Result.setInvalid(E);
5366
5367 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5368 Result.addUnsizedArray(Info, Pointee);
5369 return true;
5370}
5371
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005372namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005373class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005374 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005375 LValue &Result;
5376
Peter Collingbournee9200682011-05-13 03:29:01 +00005377 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005378 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005379 return true;
5380 }
George Burgess IVe3763372016-12-22 02:50:20 +00005381
5382 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005383public:
Mike Stump11289f42009-09-09 15:08:12 +00005384
John McCall45d55e42010-05-07 21:00:08 +00005385 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005386 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005387
Richard Smith2e312c82012-03-03 22:46:17 +00005388 bool Success(const APValue &V, const Expr *E) {
5389 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005390 return true;
5391 }
Richard Smithfddd3842011-12-30 21:15:51 +00005392 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005393 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5394 Result.set((Expr*)nullptr, 0, false, true, Offset);
5395 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005396 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005397
John McCall45d55e42010-05-07 21:00:08 +00005398 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005399 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005400 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005401 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005402 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005403 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005404 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005405 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005406 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005407 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005408 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005409 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005410 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005411 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005412 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005413 }
Richard Smithd62306a2011-11-10 06:34:14 +00005414 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005415 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005416 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005417 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005418 if (!Info.CurrentCall->This) {
5419 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005420 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005421 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005422 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005423 return false;
5424 }
Richard Smithd62306a2011-11-10 06:34:14 +00005425 Result = *Info.CurrentCall->This;
5426 return true;
5427 }
John McCallc07a0c72011-02-17 10:25:35 +00005428
Eli Friedman449fe542009-03-23 04:56:01 +00005429 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005430};
Chris Lattner05706e882008-07-11 18:11:29 +00005431} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005432
John McCall45d55e42010-05-07 21:00:08 +00005433static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005434 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005435 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005436}
5437
John McCall45d55e42010-05-07 21:00:08 +00005438bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005439 if (E->getOpcode() != BO_Add &&
5440 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005441 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005442
Chris Lattner05706e882008-07-11 18:11:29 +00005443 const Expr *PExp = E->getLHS();
5444 const Expr *IExp = E->getRHS();
5445 if (IExp->getType()->isPointerType())
5446 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005447
Richard Smith253c2a32012-01-27 01:14:48 +00005448 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005449 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005450 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005451
John McCall45d55e42010-05-07 21:00:08 +00005452 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005453 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005454 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005455
Richard Smith96e0c102011-11-04 02:25:55 +00005456 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005457 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005458
Ted Kremenek28831752012-08-23 20:46:57 +00005459 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005460 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005461}
Eli Friedman9a156e52008-11-12 09:44:48 +00005462
John McCall45d55e42010-05-07 21:00:08 +00005463bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5464 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005465}
Mike Stump11289f42009-09-09 15:08:12 +00005466
Peter Collingbournee9200682011-05-13 03:29:01 +00005467bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5468 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005469
Eli Friedman847a2bc2009-12-27 05:43:15 +00005470 switch (E->getCastKind()) {
5471 default:
5472 break;
5473
John McCalle3027922010-08-25 11:45:40 +00005474 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005475 case CK_CPointerToObjCPointerCast:
5476 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005477 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005478 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005479 if (!Visit(SubExpr))
5480 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005481 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5482 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5483 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005484 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005485 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005486 if (SubExpr->getType()->isVoidPointerType())
5487 CCEDiag(E, diag::note_constexpr_invalid_cast)
5488 << 3 << SubExpr->getType();
5489 else
5490 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5491 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005492 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5493 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005494 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005495
Anders Carlsson18275092010-10-31 20:41:46 +00005496 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005497 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005498 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005499 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005500 if (!Result.Base && Result.Offset.isZero())
5501 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005502
Richard Smithd62306a2011-11-10 06:34:14 +00005503 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005504 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005505 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5506 castAs<PointerType>()->getPointeeType(),
5507 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005508
Richard Smith027bf112011-11-17 22:56:20 +00005509 case CK_BaseToDerived:
5510 if (!Visit(E->getSubExpr()))
5511 return false;
5512 if (!Result.Base && Result.Offset.isZero())
5513 return true;
5514 return HandleBaseToDerivedCast(Info, E, Result);
5515
Richard Smith0b0a0b62011-10-29 20:57:55 +00005516 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005517 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005518 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005519
John McCalle3027922010-08-25 11:45:40 +00005520 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005521 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5522
Richard Smith2e312c82012-03-03 22:46:17 +00005523 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005524 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005525 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005526
John McCall45d55e42010-05-07 21:00:08 +00005527 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005528 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5529 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005530 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005531 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005532 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005533 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005534 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005535 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005536 return true;
5537 } else {
5538 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005539 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005540 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005541 }
5542 }
John McCalle3027922010-08-25 11:45:40 +00005543 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005544 if (SubExpr->isGLValue()) {
5545 if (!EvaluateLValue(SubExpr, Result, Info))
5546 return false;
5547 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005548 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005549 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005550 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005551 return false;
5552 }
Richard Smith96e0c102011-11-04 02:25:55 +00005553 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005554 if (const ConstantArrayType *CAT
5555 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5556 Result.addArray(Info, E, CAT);
5557 else
5558 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005559 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005560
John McCalle3027922010-08-25 11:45:40 +00005561 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005562 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVe3763372016-12-22 02:50:20 +00005563
5564 case CK_LValueToRValue: {
5565 LValue LVal;
5566 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5567 return false;
5568
5569 APValue RVal;
5570 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5571 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5572 LVal, RVal))
5573 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5574 return Success(RVal, E);
5575 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005576 }
5577
Richard Smith11562c52011-10-28 17:51:58 +00005578 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005579}
Chris Lattner05706e882008-07-11 18:11:29 +00005580
Hal Finkel0dd05d42014-10-03 17:18:37 +00005581static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5582 // C++ [expr.alignof]p3:
5583 // When alignof is applied to a reference type, the result is the
5584 // alignment of the referenced type.
5585 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5586 T = Ref->getPointeeType();
5587
5588 // __alignof is defined to return the preferred alignment.
5589 return Info.Ctx.toCharUnitsFromBits(
5590 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5591}
5592
5593static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5594 E = E->IgnoreParens();
5595
5596 // The kinds of expressions that we have special-case logic here for
5597 // should be kept up to date with the special checks for those
5598 // expressions in Sema.
5599
5600 // alignof decl is always accepted, even if it doesn't make sense: we default
5601 // to 1 in those cases.
5602 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5603 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5604 /*RefAsPointee*/true);
5605
5606 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5607 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5608 /*RefAsPointee*/true);
5609
5610 return GetAlignOfType(Info, E->getType());
5611}
5612
George Burgess IVe3763372016-12-22 02:50:20 +00005613// To be clear: this happily visits unsupported builtins. Better name welcomed.
5614bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5615 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5616 return true;
5617
5618 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5619 return false;
5620
5621 Result.setInvalid(E);
5622 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5623 Result.addUnsizedArray(Info, PointeeTy);
5624 return true;
5625}
5626
Peter Collingbournee9200682011-05-13 03:29:01 +00005627bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005628 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005629 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005630
Richard Smith6328cbd2016-11-16 00:57:23 +00005631 if (unsigned BuiltinOp = E->getBuiltinCallee())
5632 return VisitBuiltinCallExpr(E, BuiltinOp);
5633
George Burgess IVe3763372016-12-22 02:50:20 +00005634 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005635}
5636
5637bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5638 unsigned BuiltinOp) {
5639 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005640 case Builtin::BI__builtin_addressof:
5641 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005642 case Builtin::BI__builtin_assume_aligned: {
5643 // We need to be very careful here because: if the pointer does not have the
5644 // asserted alignment, then the behavior is undefined, and undefined
5645 // behavior is non-constant.
5646 if (!EvaluatePointer(E->getArg(0), Result, Info))
5647 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005648
Hal Finkel0dd05d42014-10-03 17:18:37 +00005649 LValue OffsetResult(Result);
5650 APSInt Alignment;
5651 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5652 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005653 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005654
5655 if (E->getNumArgs() > 2) {
5656 APSInt Offset;
5657 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5658 return false;
5659
Richard Smith642a2362017-01-30 23:30:26 +00005660 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005661 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5662 }
5663
5664 // If there is a base object, then it must have the correct alignment.
5665 if (OffsetResult.Base) {
5666 CharUnits BaseAlignment;
5667 if (const ValueDecl *VD =
5668 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5669 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5670 } else {
5671 BaseAlignment =
5672 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5673 }
5674
5675 if (BaseAlignment < Align) {
5676 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005677 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005678 CCEDiag(E->getArg(0),
5679 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005680 << (unsigned)BaseAlignment.getQuantity()
5681 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005682 return false;
5683 }
5684 }
5685
5686 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005687 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005688 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005689
Richard Smith642a2362017-01-30 23:30:26 +00005690 (OffsetResult.Base
5691 ? CCEDiag(E->getArg(0),
5692 diag::note_constexpr_baa_insufficient_alignment) << 1
5693 : CCEDiag(E->getArg(0),
5694 diag::note_constexpr_baa_value_insufficient_alignment))
5695 << (int)OffsetResult.Offset.getQuantity()
5696 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005697 return false;
5698 }
5699
5700 return true;
5701 }
Richard Smithe9507952016-11-12 01:39:56 +00005702
5703 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005704 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005705 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005706 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005707 if (Info.getLangOpts().CPlusPlus11)
5708 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5709 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005710 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005711 else
5712 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5713 // Fall through.
5714 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005715 case Builtin::BI__builtin_wcschr:
5716 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005717 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005718 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005719 if (!Visit(E->getArg(0)))
5720 return false;
5721 APSInt Desired;
5722 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5723 return false;
5724 uint64_t MaxLength = uint64_t(-1);
5725 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005726 BuiltinOp != Builtin::BIwcschr &&
5727 BuiltinOp != Builtin::BI__builtin_strchr &&
5728 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005729 APSInt N;
5730 if (!EvaluateInteger(E->getArg(2), N, Info))
5731 return false;
5732 MaxLength = N.getExtValue();
5733 }
5734
Richard Smith8110c9d2016-11-29 19:45:17 +00005735 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005736
Richard Smith8110c9d2016-11-29 19:45:17 +00005737 // Figure out what value we're actually looking for (after converting to
5738 // the corresponding unsigned type if necessary).
5739 uint64_t DesiredVal;
5740 bool StopAtNull = false;
5741 switch (BuiltinOp) {
5742 case Builtin::BIstrchr:
5743 case Builtin::BI__builtin_strchr:
5744 // strchr compares directly to the passed integer, and therefore
5745 // always fails if given an int that is not a char.
5746 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5747 E->getArg(1)->getType(),
5748 Desired),
5749 Desired))
5750 return ZeroInitialization(E);
5751 StopAtNull = true;
5752 // Fall through.
5753 case Builtin::BImemchr:
5754 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005755 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005756 // memchr compares by converting both sides to unsigned char. That's also
5757 // correct for strchr if we get this far (to cope with plain char being
5758 // unsigned in the strchr case).
5759 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5760 break;
Richard Smithe9507952016-11-12 01:39:56 +00005761
Richard Smith8110c9d2016-11-29 19:45:17 +00005762 case Builtin::BIwcschr:
5763 case Builtin::BI__builtin_wcschr:
5764 StopAtNull = true;
5765 // Fall through.
5766 case Builtin::BIwmemchr:
5767 case Builtin::BI__builtin_wmemchr:
5768 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5769 DesiredVal = Desired.getZExtValue();
5770 break;
5771 }
Richard Smithe9507952016-11-12 01:39:56 +00005772
5773 for (; MaxLength; --MaxLength) {
5774 APValue Char;
5775 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5776 !Char.isInt())
5777 return false;
5778 if (Char.getInt().getZExtValue() == DesiredVal)
5779 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005780 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005781 break;
5782 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5783 return false;
5784 }
5785 // Not found: return nullptr.
5786 return ZeroInitialization(E);
5787 }
5788
Richard Smith6cbd65d2013-07-11 02:27:57 +00005789 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005790 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005791 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005792}
Chris Lattner05706e882008-07-11 18:11:29 +00005793
5794//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005795// Member Pointer Evaluation
5796//===----------------------------------------------------------------------===//
5797
5798namespace {
5799class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005800 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005801 MemberPtr &Result;
5802
5803 bool Success(const ValueDecl *D) {
5804 Result = MemberPtr(D);
5805 return true;
5806 }
5807public:
5808
5809 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5810 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5811
Richard Smith2e312c82012-03-03 22:46:17 +00005812 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005813 Result.setFrom(V);
5814 return true;
5815 }
Richard Smithfddd3842011-12-30 21:15:51 +00005816 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005817 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005818 }
5819
5820 bool VisitCastExpr(const CastExpr *E);
5821 bool VisitUnaryAddrOf(const UnaryOperator *E);
5822};
5823} // end anonymous namespace
5824
5825static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5826 EvalInfo &Info) {
5827 assert(E->isRValue() && E->getType()->isMemberPointerType());
5828 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5829}
5830
5831bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5832 switch (E->getCastKind()) {
5833 default:
5834 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5835
5836 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005837 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005838 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005839
5840 case CK_BaseToDerivedMemberPointer: {
5841 if (!Visit(E->getSubExpr()))
5842 return false;
5843 if (E->path_empty())
5844 return true;
5845 // Base-to-derived member pointer casts store the path in derived-to-base
5846 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5847 // the wrong end of the derived->base arc, so stagger the path by one class.
5848 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5849 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5850 PathI != PathE; ++PathI) {
5851 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5852 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5853 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005854 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005855 }
5856 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5857 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005858 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005859 return true;
5860 }
5861
5862 case CK_DerivedToBaseMemberPointer:
5863 if (!Visit(E->getSubExpr()))
5864 return false;
5865 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5866 PathE = E->path_end(); PathI != PathE; ++PathI) {
5867 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5868 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5869 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005870 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005871 }
5872 return true;
5873 }
5874}
5875
5876bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5877 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5878 // member can be formed.
5879 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5880}
5881
5882//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005883// Record Evaluation
5884//===----------------------------------------------------------------------===//
5885
5886namespace {
5887 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005888 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005889 const LValue &This;
5890 APValue &Result;
5891 public:
5892
5893 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5894 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5895
Richard Smith2e312c82012-03-03 22:46:17 +00005896 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005897 Result = V;
5898 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005899 }
Richard Smithb8348f52016-05-12 22:16:28 +00005900 bool ZeroInitialization(const Expr *E) {
5901 return ZeroInitialization(E, E->getType());
5902 }
5903 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005904
Richard Smith52a980a2015-08-28 02:43:42 +00005905 bool VisitCallExpr(const CallExpr *E) {
5906 return handleCallExpr(E, Result, &This);
5907 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005908 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005909 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005910 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5911 return VisitCXXConstructExpr(E, E->getType());
5912 }
Faisal Valic72a08c2017-01-09 03:02:53 +00005913 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00005914 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005915 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005916 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005917 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005918}
Richard Smithd62306a2011-11-10 06:34:14 +00005919
Richard Smithfddd3842011-12-30 21:15:51 +00005920/// Perform zero-initialization on an object of non-union class type.
5921/// C++11 [dcl.init]p5:
5922/// To zero-initialize an object or reference of type T means:
5923/// [...]
5924/// -- if T is a (possibly cv-qualified) non-union class type,
5925/// each non-static data member and each base-class subobject is
5926/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005927static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5928 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005929 const LValue &This, APValue &Result) {
5930 assert(!RD->isUnion() && "Expected non-union class type");
5931 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5932 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005933 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005934
John McCalld7bca762012-05-01 00:38:49 +00005935 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005936 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5937
5938 if (CD) {
5939 unsigned Index = 0;
5940 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005941 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005942 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5943 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005944 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5945 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005946 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005947 Result.getStructBase(Index)))
5948 return false;
5949 }
5950 }
5951
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005952 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005953 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005954 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005955 continue;
5956
5957 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005958 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005959 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005960
David Blaikie2d7c57e2012-04-30 02:36:29 +00005961 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005962 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005963 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005964 return false;
5965 }
5966
5967 return true;
5968}
5969
Richard Smithb8348f52016-05-12 22:16:28 +00005970bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5971 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005972 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005973 if (RD->isUnion()) {
5974 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5975 // object's first non-static named data member is zero-initialized
5976 RecordDecl::field_iterator I = RD->field_begin();
5977 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005978 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005979 return true;
5980 }
5981
5982 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005983 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005984 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005985 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005986 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005987 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005988 }
5989
Richard Smith5d108602012-02-17 00:44:16 +00005990 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005991 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005992 return false;
5993 }
5994
Richard Smitha8105bc2012-01-06 16:39:00 +00005995 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005996}
5997
Richard Smithe97cbd72011-11-11 04:05:33 +00005998bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5999 switch (E->getCastKind()) {
6000 default:
6001 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6002
6003 case CK_ConstructorConversion:
6004 return Visit(E->getSubExpr());
6005
6006 case CK_DerivedToBase:
6007 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006008 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006009 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006010 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006011 if (!DerivedObject.isStruct())
6012 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006013
6014 // Derived-to-base rvalue conversion: just slice off the derived part.
6015 APValue *Value = &DerivedObject;
6016 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6017 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6018 PathE = E->path_end(); PathI != PathE; ++PathI) {
6019 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6020 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6021 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6022 RD = Base;
6023 }
6024 Result = *Value;
6025 return true;
6026 }
6027 }
6028}
6029
Richard Smithd62306a2011-11-10 06:34:14 +00006030bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006031 if (E->isTransparent())
6032 return Visit(E->getInit(0));
6033
Richard Smithd62306a2011-11-10 06:34:14 +00006034 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006035 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006036 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6037
6038 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006039 const FieldDecl *Field = E->getInitializedFieldInUnion();
6040 Result = APValue(Field);
6041 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006042 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006043
6044 // If the initializer list for a union does not contain any elements, the
6045 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006046 // FIXME: The element should be initialized from an initializer list.
6047 // Is this difference ever observable for initializer lists which
6048 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006049 ImplicitValueInitExpr VIE(Field->getType());
6050 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6051
Richard Smithd62306a2011-11-10 06:34:14 +00006052 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006053 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6054 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006055
6056 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6057 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6058 isa<CXXDefaultInitExpr>(InitExpr));
6059
Richard Smithb228a862012-02-15 02:18:13 +00006060 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006061 }
6062
Richard Smith872307e2016-03-08 22:17:41 +00006063 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006064 if (Result.isUninit())
6065 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6066 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006067 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006068 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006069
6070 // Initialize base classes.
6071 if (CXXRD) {
6072 for (const auto &Base : CXXRD->bases()) {
6073 assert(ElementNo < E->getNumInits() && "missing init for base class");
6074 const Expr *Init = E->getInit(ElementNo);
6075
6076 LValue Subobject = This;
6077 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6078 return false;
6079
6080 APValue &FieldVal = Result.getStructBase(ElementNo);
6081 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006082 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006083 return false;
6084 Success = false;
6085 }
6086 ++ElementNo;
6087 }
6088 }
6089
6090 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006091 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006092 // Anonymous bit-fields are not considered members of the class for
6093 // purposes of aggregate initialization.
6094 if (Field->isUnnamedBitfield())
6095 continue;
6096
6097 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006098
Richard Smith253c2a32012-01-27 01:14:48 +00006099 bool HaveInit = ElementNo < E->getNumInits();
6100
6101 // FIXME: Diagnostics here should point to the end of the initializer
6102 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006103 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006104 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006105 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006106
6107 // Perform an implicit value-initialization for members beyond the end of
6108 // the initializer list.
6109 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006110 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006111
Richard Smith852c9db2013-04-20 22:23:05 +00006112 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6113 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6114 isa<CXXDefaultInitExpr>(Init));
6115
Richard Smith49ca8aa2013-08-06 07:09:20 +00006116 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6117 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6118 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006119 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006120 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006121 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006122 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006123 }
6124 }
6125
Richard Smith253c2a32012-01-27 01:14:48 +00006126 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006127}
6128
Richard Smithb8348f52016-05-12 22:16:28 +00006129bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6130 QualType T) {
6131 // Note that E's type is not necessarily the type of our class here; we might
6132 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006133 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006134 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6135
Richard Smithfddd3842011-12-30 21:15:51 +00006136 bool ZeroInit = E->requiresZeroInitialization();
6137 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006138 // If we've already performed zero-initialization, we're already done.
6139 if (!Result.isUninit())
6140 return true;
6141
Richard Smithda3f4fd2014-03-05 23:32:50 +00006142 // We can get here in two different ways:
6143 // 1) We're performing value-initialization, and should zero-initialize
6144 // the object, or
6145 // 2) We're performing default-initialization of an object with a trivial
6146 // constexpr default constructor, in which case we should start the
6147 // lifetimes of all the base subobjects (there can be no data member
6148 // subobjects in this case) per [basic.life]p1.
6149 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006150 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006151 }
6152
Craig Topper36250ad2014-05-12 05:36:57 +00006153 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006154 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006155
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006156 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006157 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006158
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006159 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006160 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006161 if (const MaterializeTemporaryExpr *ME
6162 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6163 return Visit(ME->GetTemporaryExpr());
6164
Richard Smithb8348f52016-05-12 22:16:28 +00006165 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006166 return false;
6167
Craig Topper5fc8fc22014-08-27 06:28:36 +00006168 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006169 return HandleConstructorCall(E, This, Args,
6170 cast<CXXConstructorDecl>(Definition), Info,
6171 Result);
6172}
6173
6174bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6175 const CXXInheritedCtorInitExpr *E) {
6176 if (!Info.CurrentCall) {
6177 assert(Info.checkingPotentialConstantExpression());
6178 return false;
6179 }
6180
6181 const CXXConstructorDecl *FD = E->getConstructor();
6182 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6183 return false;
6184
6185 const FunctionDecl *Definition = nullptr;
6186 auto Body = FD->getBody(Definition);
6187
6188 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6189 return false;
6190
6191 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006192 cast<CXXConstructorDecl>(Definition), Info,
6193 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006194}
6195
Richard Smithcc1b96d2013-06-12 22:31:48 +00006196bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6197 const CXXStdInitializerListExpr *E) {
6198 const ConstantArrayType *ArrayType =
6199 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6200
6201 LValue Array;
6202 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6203 return false;
6204
6205 // Get a pointer to the first element of the array.
6206 Array.addArray(Info, E, ArrayType);
6207
6208 // FIXME: Perform the checks on the field types in SemaInit.
6209 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6210 RecordDecl::field_iterator Field = Record->field_begin();
6211 if (Field == Record->field_end())
6212 return Error(E);
6213
6214 // Start pointer.
6215 if (!Field->getType()->isPointerType() ||
6216 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6217 ArrayType->getElementType()))
6218 return Error(E);
6219
6220 // FIXME: What if the initializer_list type has base classes, etc?
6221 Result = APValue(APValue::UninitStruct(), 0, 2);
6222 Array.moveInto(Result.getStructField(0));
6223
6224 if (++Field == Record->field_end())
6225 return Error(E);
6226
6227 if (Field->getType()->isPointerType() &&
6228 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6229 ArrayType->getElementType())) {
6230 // End pointer.
6231 if (!HandleLValueArrayAdjustment(Info, E, Array,
6232 ArrayType->getElementType(),
6233 ArrayType->getSize().getZExtValue()))
6234 return false;
6235 Array.moveInto(Result.getStructField(1));
6236 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6237 // Length.
6238 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6239 else
6240 return Error(E);
6241
6242 if (++Field != Record->field_end())
6243 return Error(E);
6244
6245 return true;
6246}
6247
Faisal Valic72a08c2017-01-09 03:02:53 +00006248bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6249 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6250 if (ClosureClass->isInvalidDecl()) return false;
6251
6252 if (Info.checkingPotentialConstantExpression()) return true;
6253 if (E->capture_size()) {
6254 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6255 << "can not evaluate lambda expressions with captures";
6256 return false;
6257 }
6258 // FIXME: Implement captures.
6259 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6260 return true;
6261}
6262
Richard Smithd62306a2011-11-10 06:34:14 +00006263static bool EvaluateRecord(const Expr *E, const LValue &This,
6264 APValue &Result, EvalInfo &Info) {
6265 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006266 "can't evaluate expression as a record rvalue");
6267 return RecordExprEvaluator(Info, This, Result).Visit(E);
6268}
6269
6270//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006271// Temporary Evaluation
6272//
6273// Temporaries are represented in the AST as rvalues, but generally behave like
6274// lvalues. The full-object of which the temporary is a subobject is implicitly
6275// materialized so that a reference can bind to it.
6276//===----------------------------------------------------------------------===//
6277namespace {
6278class TemporaryExprEvaluator
6279 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6280public:
6281 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6282 LValueExprEvaluatorBaseTy(Info, Result) {}
6283
6284 /// Visit an expression which constructs the value of this temporary.
6285 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006286 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006287 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6288 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006289 }
6290
6291 bool VisitCastExpr(const CastExpr *E) {
6292 switch (E->getCastKind()) {
6293 default:
6294 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6295
6296 case CK_ConstructorConversion:
6297 return VisitConstructExpr(E->getSubExpr());
6298 }
6299 }
6300 bool VisitInitListExpr(const InitListExpr *E) {
6301 return VisitConstructExpr(E);
6302 }
6303 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6304 return VisitConstructExpr(E);
6305 }
6306 bool VisitCallExpr(const CallExpr *E) {
6307 return VisitConstructExpr(E);
6308 }
Richard Smith513955c2014-12-17 19:24:30 +00006309 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6310 return VisitConstructExpr(E);
6311 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006312 bool VisitLambdaExpr(const LambdaExpr *E) {
6313 return VisitConstructExpr(E);
6314 }
Richard Smith027bf112011-11-17 22:56:20 +00006315};
6316} // end anonymous namespace
6317
6318/// Evaluate an expression of record type as a temporary.
6319static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006320 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006321 return TemporaryExprEvaluator(Info, Result).Visit(E);
6322}
6323
6324//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006325// Vector Evaluation
6326//===----------------------------------------------------------------------===//
6327
6328namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006329 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006330 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006331 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006332 public:
Mike Stump11289f42009-09-09 15:08:12 +00006333
Richard Smith2d406342011-10-22 21:10:00 +00006334 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6335 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006336
Craig Topper9798b932015-09-29 04:30:05 +00006337 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006338 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6339 // FIXME: remove this APValue copy.
6340 Result = APValue(V.data(), V.size());
6341 return true;
6342 }
Richard Smith2e312c82012-03-03 22:46:17 +00006343 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006344 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006345 Result = V;
6346 return true;
6347 }
Richard Smithfddd3842011-12-30 21:15:51 +00006348 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006349
Richard Smith2d406342011-10-22 21:10:00 +00006350 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006351 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006352 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006353 bool VisitInitListExpr(const InitListExpr *E);
6354 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006355 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006356 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006357 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006358 };
6359} // end anonymous namespace
6360
6361static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006362 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006363 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006364}
6365
George Burgess IV533ff002015-12-11 00:23:35 +00006366bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006367 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006368 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006369
Richard Smith161f09a2011-12-06 22:44:34 +00006370 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006371 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006372
Eli Friedmanc757de22011-03-25 00:43:55 +00006373 switch (E->getCastKind()) {
6374 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006375 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006376 if (SETy->isIntegerType()) {
6377 APSInt IntResult;
6378 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006379 return false;
6380 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006381 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006382 APFloat FloatResult(0.0);
6383 if (!EvaluateFloat(SE, FloatResult, Info))
6384 return false;
6385 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006386 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006387 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006388 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006389
6390 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006391 SmallVector<APValue, 4> Elts(NElts, Val);
6392 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006393 }
Eli Friedman803acb32011-12-22 03:51:45 +00006394 case CK_BitCast: {
6395 // Evaluate the operand into an APInt we can extract from.
6396 llvm::APInt SValInt;
6397 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6398 return false;
6399 // Extract the elements
6400 QualType EltTy = VTy->getElementType();
6401 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6402 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6403 SmallVector<APValue, 4> Elts;
6404 if (EltTy->isRealFloatingType()) {
6405 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006406 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006407 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006408 FloatEltSize = 80;
6409 for (unsigned i = 0; i < NElts; i++) {
6410 llvm::APInt Elt;
6411 if (BigEndian)
6412 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6413 else
6414 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006415 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006416 }
6417 } else if (EltTy->isIntegerType()) {
6418 for (unsigned i = 0; i < NElts; i++) {
6419 llvm::APInt Elt;
6420 if (BigEndian)
6421 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6422 else
6423 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6424 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6425 }
6426 } else {
6427 return Error(E);
6428 }
6429 return Success(Elts, E);
6430 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006431 default:
Richard Smith11562c52011-10-28 17:51:58 +00006432 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006433 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006434}
6435
Richard Smith2d406342011-10-22 21:10:00 +00006436bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006437VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006438 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006439 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006440 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006441
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006442 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006443 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006444
Eli Friedmanb9c71292012-01-03 23:24:20 +00006445 // The number of initializers can be less than the number of
6446 // vector elements. For OpenCL, this can be due to nested vector
6447 // initialization. For GCC compatibility, missing trailing elements
6448 // should be initialized with zeroes.
6449 unsigned CountInits = 0, CountElts = 0;
6450 while (CountElts < NumElements) {
6451 // Handle nested vector initialization.
6452 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006453 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006454 APValue v;
6455 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6456 return Error(E);
6457 unsigned vlen = v.getVectorLength();
6458 for (unsigned j = 0; j < vlen; j++)
6459 Elements.push_back(v.getVectorElt(j));
6460 CountElts += vlen;
6461 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006462 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006463 if (CountInits < NumInits) {
6464 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006465 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006466 } else // trailing integer zero.
6467 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6468 Elements.push_back(APValue(sInt));
6469 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006470 } else {
6471 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006472 if (CountInits < NumInits) {
6473 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006474 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006475 } else // trailing float zero.
6476 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6477 Elements.push_back(APValue(f));
6478 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006479 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006480 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006481 }
Richard Smith2d406342011-10-22 21:10:00 +00006482 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006483}
6484
Richard Smith2d406342011-10-22 21:10:00 +00006485bool
Richard Smithfddd3842011-12-30 21:15:51 +00006486VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006487 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006488 QualType EltTy = VT->getElementType();
6489 APValue ZeroElement;
6490 if (EltTy->isIntegerType())
6491 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6492 else
6493 ZeroElement =
6494 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6495
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006496 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006497 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006498}
6499
Richard Smith2d406342011-10-22 21:10:00 +00006500bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006501 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006502 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006503}
6504
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006505//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006506// Array Evaluation
6507//===----------------------------------------------------------------------===//
6508
6509namespace {
6510 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006511 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006512 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006513 APValue &Result;
6514 public:
6515
Richard Smithd62306a2011-11-10 06:34:14 +00006516 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6517 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006518
6519 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006520 assert((V.isArray() || V.isLValue()) &&
6521 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006522 Result = V;
6523 return true;
6524 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006525
Richard Smithfddd3842011-12-30 21:15:51 +00006526 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006527 const ConstantArrayType *CAT =
6528 Info.Ctx.getAsConstantArrayType(E->getType());
6529 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006530 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006531
6532 Result = APValue(APValue::UninitArray(), 0,
6533 CAT->getSize().getZExtValue());
6534 if (!Result.hasArrayFiller()) return true;
6535
Richard Smithfddd3842011-12-30 21:15:51 +00006536 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006537 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006538 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006539 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006540 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006541 }
6542
Richard Smith52a980a2015-08-28 02:43:42 +00006543 bool VisitCallExpr(const CallExpr *E) {
6544 return handleCallExpr(E, Result, &This);
6545 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006546 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006547 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006548 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006549 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6550 const LValue &Subobject,
6551 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006552 };
6553} // end anonymous namespace
6554
Richard Smithd62306a2011-11-10 06:34:14 +00006555static bool EvaluateArray(const Expr *E, const LValue &This,
6556 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006557 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006558 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006559}
6560
6561bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6562 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6563 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006564 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006565
Richard Smithca2cfbf2011-12-22 01:07:19 +00006566 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6567 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006568 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006569 LValue LV;
6570 if (!EvaluateLValue(E->getInit(0), LV, Info))
6571 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006572 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006573 LV.moveInto(Val);
6574 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006575 }
6576
Richard Smith253c2a32012-01-27 01:14:48 +00006577 bool Success = true;
6578
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006579 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6580 "zero-initialized array shouldn't have any initialized elts");
6581 APValue Filler;
6582 if (Result.isArray() && Result.hasArrayFiller())
6583 Filler = Result.getArrayFiller();
6584
Richard Smith9543c5e2013-04-22 14:44:29 +00006585 unsigned NumEltsToInit = E->getNumInits();
6586 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006587 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006588
6589 // If the initializer might depend on the array index, run it for each
6590 // array element. For now, just whitelist non-class value-initialization.
6591 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6592 NumEltsToInit = NumElts;
6593
6594 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006595
6596 // If the array was previously zero-initialized, preserve the
6597 // zero-initialized values.
6598 if (!Filler.isUninit()) {
6599 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6600 Result.getArrayInitializedElt(I) = Filler;
6601 if (Result.hasArrayFiller())
6602 Result.getArrayFiller() = Filler;
6603 }
6604
Richard Smithd62306a2011-11-10 06:34:14 +00006605 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006606 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006607 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6608 const Expr *Init =
6609 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006610 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006611 Info, Subobject, Init) ||
6612 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006613 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006614 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006615 return false;
6616 Success = false;
6617 }
Richard Smithd62306a2011-11-10 06:34:14 +00006618 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006619
Richard Smith9543c5e2013-04-22 14:44:29 +00006620 if (!Result.hasArrayFiller())
6621 return Success;
6622
6623 // If we get here, we have a trivial filler, which we can just evaluate
6624 // once and splat over the rest of the array elements.
6625 assert(FillerExpr && "no array filler for incomplete init list");
6626 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6627 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006628}
6629
Richard Smith410306b2016-12-12 02:53:20 +00006630bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6631 if (E->getCommonExpr() &&
6632 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6633 Info, E->getCommonExpr()->getSourceExpr()))
6634 return false;
6635
6636 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6637
6638 uint64_t Elements = CAT->getSize().getZExtValue();
6639 Result = APValue(APValue::UninitArray(), Elements, Elements);
6640
6641 LValue Subobject = This;
6642 Subobject.addArray(Info, E, CAT);
6643
6644 bool Success = true;
6645 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6646 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6647 Info, Subobject, E->getSubExpr()) ||
6648 !HandleLValueArrayAdjustment(Info, E, Subobject,
6649 CAT->getElementType(), 1)) {
6650 if (!Info.noteFailure())
6651 return false;
6652 Success = false;
6653 }
6654 }
6655
6656 return Success;
6657}
6658
Richard Smith027bf112011-11-17 22:56:20 +00006659bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006660 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6661}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006662
Richard Smith9543c5e2013-04-22 14:44:29 +00006663bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6664 const LValue &Subobject,
6665 APValue *Value,
6666 QualType Type) {
6667 bool HadZeroInit = !Value->isUninit();
6668
6669 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6670 unsigned N = CAT->getSize().getZExtValue();
6671
6672 // Preserve the array filler if we had prior zero-initialization.
6673 APValue Filler =
6674 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6675 : APValue();
6676
6677 *Value = APValue(APValue::UninitArray(), N, N);
6678
6679 if (HadZeroInit)
6680 for (unsigned I = 0; I != N; ++I)
6681 Value->getArrayInitializedElt(I) = Filler;
6682
6683 // Initialize the elements.
6684 LValue ArrayElt = Subobject;
6685 ArrayElt.addArray(Info, E, CAT);
6686 for (unsigned I = 0; I != N; ++I)
6687 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6688 CAT->getElementType()) ||
6689 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6690 CAT->getElementType(), 1))
6691 return false;
6692
6693 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006694 }
Richard Smith027bf112011-11-17 22:56:20 +00006695
Richard Smith9543c5e2013-04-22 14:44:29 +00006696 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006697 return Error(E);
6698
Richard Smithb8348f52016-05-12 22:16:28 +00006699 return RecordExprEvaluator(Info, Subobject, *Value)
6700 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006701}
6702
Richard Smithf3e9e432011-11-07 09:22:26 +00006703//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006704// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006705//
6706// As a GNU extension, we support casting pointers to sufficiently-wide integer
6707// types and back in constant folding. Integer values are thus represented
6708// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006709//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006710
6711namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006712class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006713 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006714 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006715public:
Richard Smith2e312c82012-03-03 22:46:17 +00006716 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006717 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006718
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006719 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006720 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006721 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006722 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006723 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006724 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006725 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006726 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006727 return true;
6728 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006729 bool Success(const llvm::APSInt &SI, const Expr *E) {
6730 return Success(SI, E, Result);
6731 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006732
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006733 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006734 assert(E->getType()->isIntegralOrEnumerationType() &&
6735 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006736 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006737 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006738 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006739 Result.getInt().setIsUnsigned(
6740 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006741 return true;
6742 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006743 bool Success(const llvm::APInt &I, const Expr *E) {
6744 return Success(I, E, Result);
6745 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006746
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006747 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006748 assert(E->getType()->isIntegralOrEnumerationType() &&
6749 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006750 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006751 return true;
6752 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006753 bool Success(uint64_t Value, const Expr *E) {
6754 return Success(Value, E, Result);
6755 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006756
Ken Dyckdbc01912011-03-11 02:13:43 +00006757 bool Success(CharUnits Size, const Expr *E) {
6758 return Success(Size.getQuantity(), E);
6759 }
6760
Richard Smith2e312c82012-03-03 22:46:17 +00006761 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006762 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006763 Result = V;
6764 return true;
6765 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006766 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768
Richard Smithfddd3842011-12-30 21:15:51 +00006769 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006770
Peter Collingbournee9200682011-05-13 03:29:01 +00006771 //===--------------------------------------------------------------------===//
6772 // Visitor Methods
6773 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006774
Chris Lattner7174bf32008-07-12 00:38:25 +00006775 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006776 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006777 }
6778 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006779 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006780 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006781
6782 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6783 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006784 if (CheckReferencedDecl(E, E->getDecl()))
6785 return true;
6786
6787 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006788 }
6789 bool VisitMemberExpr(const MemberExpr *E) {
6790 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006791 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006792 return true;
6793 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006794
6795 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006796 }
6797
Peter Collingbournee9200682011-05-13 03:29:01 +00006798 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006799 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006800 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006801 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006802 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006803
Peter Collingbournee9200682011-05-13 03:29:01 +00006804 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006805 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006806
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006807 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006808 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006809 }
Mike Stump11289f42009-09-09 15:08:12 +00006810
Ted Kremeneke65b0862012-03-06 20:05:56 +00006811 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6812 return Success(E->getValue(), E);
6813 }
Richard Smith410306b2016-12-12 02:53:20 +00006814
6815 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6816 if (Info.ArrayInitIndex == uint64_t(-1)) {
6817 // We were asked to evaluate this subexpression independent of the
6818 // enclosing ArrayInitLoopExpr. We can't do that.
6819 Info.FFDiag(E);
6820 return false;
6821 }
6822 return Success(Info.ArrayInitIndex, E);
6823 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006824
Richard Smith4ce706a2011-10-11 21:43:33 +00006825 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006826 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006827 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006828 }
6829
Douglas Gregor29c42f22012-02-24 07:38:34 +00006830 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6831 return Success(E->getValue(), E);
6832 }
6833
John Wiegley6242b6a2011-04-28 00:16:57 +00006834 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6835 return Success(E->getValue(), E);
6836 }
6837
John Wiegleyf9f65842011-04-25 06:54:41 +00006838 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6839 return Success(E->getValue(), E);
6840 }
6841
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006842 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006843 bool VisitUnaryImag(const UnaryOperator *E);
6844
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006845 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006846 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006847
Eli Friedman4e7a2412009-02-27 04:45:43 +00006848 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006849};
Chris Lattner05706e882008-07-11 18:11:29 +00006850} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006851
Richard Smith11562c52011-10-28 17:51:58 +00006852/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6853/// produce either the integer value or a pointer.
6854///
6855/// GCC has a heinous extension which folds casts between pointer types and
6856/// pointer-sized integral types. We support this by allowing the evaluation of
6857/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6858/// Some simple arithmetic on such values is supported (they are treated much
6859/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006860static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006861 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006862 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006863 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006864}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006865
Richard Smithf57d8cb2011-12-09 22:58:01 +00006866static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006867 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006868 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006869 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006870 if (!Val.isInt()) {
6871 // FIXME: It would be better to produce the diagnostic for casting
6872 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006873 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006874 return false;
6875 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006876 Result = Val.getInt();
6877 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006878}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006879
Richard Smithf57d8cb2011-12-09 22:58:01 +00006880/// Check whether the given declaration can be directly converted to an integral
6881/// rvalue. If not, no diagnostic is produced; there are other things we can
6882/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006883bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006884 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006885 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006886 // Check for signedness/width mismatches between E type and ECD value.
6887 bool SameSign = (ECD->getInitVal().isSigned()
6888 == E->getType()->isSignedIntegerOrEnumerationType());
6889 bool SameWidth = (ECD->getInitVal().getBitWidth()
6890 == Info.Ctx.getIntWidth(E->getType()));
6891 if (SameSign && SameWidth)
6892 return Success(ECD->getInitVal(), E);
6893 else {
6894 // Get rid of mismatch (otherwise Success assertions will fail)
6895 // by computing a new value matching the type of E.
6896 llvm::APSInt Val = ECD->getInitVal();
6897 if (!SameSign)
6898 Val.setIsSigned(!ECD->getInitVal().isSigned());
6899 if (!SameWidth)
6900 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6901 return Success(Val, E);
6902 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006903 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006904 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006905}
6906
Chris Lattner86ee2862008-10-06 06:40:35 +00006907/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6908/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006909static int EvaluateBuiltinClassifyType(const CallExpr *E,
6910 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006911 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006912 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006913 enum gcc_type_class {
6914 no_type_class = -1,
6915 void_type_class, integer_type_class, char_type_class,
6916 enumeral_type_class, boolean_type_class,
6917 pointer_type_class, reference_type_class, offset_type_class,
6918 real_type_class, complex_type_class,
6919 function_type_class, method_type_class,
6920 record_type_class, union_type_class,
6921 array_type_class, string_type_class,
6922 lang_type_class
6923 };
Mike Stump11289f42009-09-09 15:08:12 +00006924
6925 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006926 // ideal, however it is what gcc does.
6927 if (E->getNumArgs() == 0)
6928 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006929
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006930 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6931 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6932
6933 switch (CanTy->getTypeClass()) {
6934#define TYPE(ID, BASE)
6935#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6936#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6937#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6938#include "clang/AST/TypeNodes.def"
6939 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6940
6941 case Type::Builtin:
6942 switch (BT->getKind()) {
6943#define BUILTIN_TYPE(ID, SINGLETON_ID)
6944#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6945#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6946#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6947#include "clang/AST/BuiltinTypes.def"
6948 case BuiltinType::Void:
6949 return void_type_class;
6950
6951 case BuiltinType::Bool:
6952 return boolean_type_class;
6953
6954 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6955 case BuiltinType::UChar:
6956 case BuiltinType::UShort:
6957 case BuiltinType::UInt:
6958 case BuiltinType::ULong:
6959 case BuiltinType::ULongLong:
6960 case BuiltinType::UInt128:
6961 return integer_type_class;
6962
6963 case BuiltinType::NullPtr:
6964 return pointer_type_class;
6965
6966 case BuiltinType::WChar_U:
6967 case BuiltinType::Char16:
6968 case BuiltinType::Char32:
6969 case BuiltinType::ObjCId:
6970 case BuiltinType::ObjCClass:
6971 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006972#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6973 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006974#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006975 case BuiltinType::OCLSampler:
6976 case BuiltinType::OCLEvent:
6977 case BuiltinType::OCLClkEvent:
6978 case BuiltinType::OCLQueue:
6979 case BuiltinType::OCLNDRange:
6980 case BuiltinType::OCLReserveID:
6981 case BuiltinType::Dependent:
6982 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6983 };
6984
6985 case Type::Enum:
6986 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6987 break;
6988
6989 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006990 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006991 break;
6992
6993 case Type::MemberPointer:
6994 if (CanTy->isMemberDataPointerType())
6995 return offset_type_class;
6996 else {
6997 // We expect member pointers to be either data or function pointers,
6998 // nothing else.
6999 assert(CanTy->isMemberFunctionPointerType());
7000 return method_type_class;
7001 }
7002
7003 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007004 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007005
7006 case Type::FunctionNoProto:
7007 case Type::FunctionProto:
7008 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7009
7010 case Type::Record:
7011 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7012 switch (RT->getDecl()->getTagKind()) {
7013 case TagTypeKind::TTK_Struct:
7014 case TagTypeKind::TTK_Class:
7015 case TagTypeKind::TTK_Interface:
7016 return record_type_class;
7017
7018 case TagTypeKind::TTK_Enum:
7019 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7020
7021 case TagTypeKind::TTK_Union:
7022 return union_type_class;
7023 }
7024 }
David Blaikie83d382b2011-09-23 05:06:16 +00007025 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007026
7027 case Type::ConstantArray:
7028 case Type::VariableArray:
7029 case Type::IncompleteArray:
7030 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7031
7032 case Type::BlockPointer:
7033 case Type::LValueReference:
7034 case Type::RValueReference:
7035 case Type::Vector:
7036 case Type::ExtVector:
7037 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007038 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007039 case Type::ObjCObject:
7040 case Type::ObjCInterface:
7041 case Type::ObjCObjectPointer:
7042 case Type::Pipe:
7043 case Type::Atomic:
7044 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7045 }
7046
7047 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007048}
7049
Richard Smith5fab0c92011-12-28 19:48:30 +00007050/// EvaluateBuiltinConstantPForLValue - Determine the result of
7051/// __builtin_constant_p when applied to the given lvalue.
7052///
7053/// An lvalue is only "constant" if it is a pointer or reference to the first
7054/// character of a string literal.
7055template<typename LValue>
7056static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007057 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007058 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7059}
7060
7061/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7062/// GCC as we can manage.
7063static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7064 QualType ArgType = Arg->getType();
7065
7066 // __builtin_constant_p always has one operand. The rules which gcc follows
7067 // are not precisely documented, but are as follows:
7068 //
7069 // - If the operand is of integral, floating, complex or enumeration type,
7070 // and can be folded to a known value of that type, it returns 1.
7071 // - If the operand and can be folded to a pointer to the first character
7072 // of a string literal (or such a pointer cast to an integral type), it
7073 // returns 1.
7074 //
7075 // Otherwise, it returns 0.
7076 //
7077 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7078 // its support for this does not currently work.
7079 if (ArgType->isIntegralOrEnumerationType()) {
7080 Expr::EvalResult Result;
7081 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7082 return false;
7083
7084 APValue &V = Result.Val;
7085 if (V.getKind() == APValue::Int)
7086 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007087 if (V.getKind() == APValue::LValue)
7088 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007089 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7090 return Arg->isEvaluatable(Ctx);
7091 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7092 LValue LV;
7093 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007094 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007095 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7096 : EvaluatePointer(Arg, LV, Info)) &&
7097 !Status.HasSideEffects)
7098 return EvaluateBuiltinConstantPForLValue(LV);
7099 }
7100
7101 // Anything else isn't considered to be sufficiently constant.
7102 return false;
7103}
7104
John McCall95007602010-05-10 23:27:23 +00007105/// Retrieves the "underlying object type" of the given expression,
7106/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007107static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007108 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7109 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007110 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007111 } else if (const Expr *E = B.get<const Expr*>()) {
7112 if (isa<CompoundLiteralExpr>(E))
7113 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007114 }
7115
7116 return QualType();
7117}
7118
George Burgess IV3a03fab2015-09-04 21:28:13 +00007119/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007120/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007121/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007122/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7123///
7124/// Always returns an RValue with a pointer representation.
7125static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7126 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7127
7128 auto *NoParens = E->IgnoreParens();
7129 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007130 if (Cast == nullptr)
7131 return NoParens;
7132
7133 // We only conservatively allow a few kinds of casts, because this code is
7134 // inherently a simple solution that seeks to support the common case.
7135 auto CastKind = Cast->getCastKind();
7136 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7137 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007138 return NoParens;
7139
7140 auto *SubExpr = Cast->getSubExpr();
7141 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7142 return NoParens;
7143 return ignorePointerCastsAndParens(SubExpr);
7144}
7145
George Burgess IVa51c4072015-10-16 01:49:01 +00007146/// Checks to see if the given LValue's Designator is at the end of the LValue's
7147/// record layout. e.g.
7148/// struct { struct { int a, b; } fst, snd; } obj;
7149/// obj.fst // no
7150/// obj.snd // yes
7151/// obj.fst.a // no
7152/// obj.fst.b // no
7153/// obj.snd.a // no
7154/// obj.snd.b // yes
7155///
7156/// Please note: this function is specialized for how __builtin_object_size
7157/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007158///
7159/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007160static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7161 assert(!LVal.Designator.Invalid);
7162
George Burgess IV4168d752016-06-27 19:40:41 +00007163 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7164 const RecordDecl *Parent = FD->getParent();
7165 Invalid = Parent->isInvalidDecl();
7166 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007167 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007168 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007169 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7170 };
7171
7172 auto &Base = LVal.getLValueBase();
7173 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7174 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007175 bool Invalid;
7176 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7177 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007178 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007179 for (auto *FD : IFD->chain()) {
7180 bool Invalid;
7181 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7182 return Invalid;
7183 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007184 }
7185 }
7186
George Burgess IVe3763372016-12-22 02:50:20 +00007187 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007188 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007189 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7190 assert(isBaseAnAllocSizeCall(Base) &&
7191 "Unsized array in non-alloc_size call?");
7192 // If this is an alloc_size base, we should ignore the initial array index
7193 ++I;
7194 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7195 }
7196
7197 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7198 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007199 if (BaseType->isArrayType()) {
7200 // Because __builtin_object_size treats arrays as objects, we can ignore
7201 // the index iff this is the last array in the Designator.
7202 if (I + 1 == E)
7203 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007204 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7205 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007206 if (Index + 1 != CAT->getSize())
7207 return false;
7208 BaseType = CAT->getElementType();
7209 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007210 const auto *CT = BaseType->castAs<ComplexType>();
7211 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007212 if (Index != 1)
7213 return false;
7214 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007215 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007216 bool Invalid;
7217 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7218 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007219 BaseType = FD->getType();
7220 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007221 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007222 return false;
7223 }
7224 }
7225 return true;
7226}
7227
George Burgess IVe3763372016-12-22 02:50:20 +00007228/// Tests to see if the LValue has a user-specified designator (that isn't
7229/// necessarily valid). Note that this always returns 'true' if the LValue has
7230/// an unsized array as its first designator entry, because there's currently no
7231/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007232static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007233 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007234 return false;
7235
George Burgess IVe3763372016-12-22 02:50:20 +00007236 if (!LVal.Designator.Entries.empty())
7237 return LVal.Designator.isMostDerivedAnUnsizedArray();
7238
George Burgess IVa51c4072015-10-16 01:49:01 +00007239 if (!LVal.InvalidBase)
7240 return true;
7241
George Burgess IVe3763372016-12-22 02:50:20 +00007242 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7243 // the LValueBase.
7244 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7245 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007246}
7247
George Burgess IVe3763372016-12-22 02:50:20 +00007248/// Attempts to detect a user writing into a piece of memory that's impossible
7249/// to figure out the size of by just using types.
7250static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7251 const SubobjectDesignator &Designator = LVal.Designator;
7252 // Notes:
7253 // - Users can only write off of the end when we have an invalid base. Invalid
7254 // bases imply we don't know where the memory came from.
7255 // - We used to be a bit more aggressive here; we'd only be conservative if
7256 // the array at the end was flexible, or if it had 0 or 1 elements. This
7257 // broke some common standard library extensions (PR30346), but was
7258 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7259 // with some sort of whitelist. OTOH, it seems that GCC is always
7260 // conservative with the last element in structs (if it's an array), so our
7261 // current behavior is more compatible than a whitelisting approach would
7262 // be.
7263 return LVal.InvalidBase &&
7264 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7265 Designator.MostDerivedIsArrayElement &&
7266 isDesignatorAtObjectEnd(Ctx, LVal);
7267}
7268
7269/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7270/// Fails if the conversion would cause loss of precision.
7271static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7272 CharUnits &Result) {
7273 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7274 if (Int.ugt(CharUnitsMax))
7275 return false;
7276 Result = CharUnits::fromQuantity(Int.getZExtValue());
7277 return true;
7278}
7279
7280/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7281/// determine how many bytes exist from the beginning of the object to either
7282/// the end of the current subobject, or the end of the object itself, depending
7283/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007284///
George Burgess IVe3763372016-12-22 02:50:20 +00007285/// If this returns false, the value of Result is undefined.
7286static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7287 unsigned Type, const LValue &LVal,
7288 CharUnits &EndOffset) {
7289 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007290
George Burgess IV7fb7e362017-01-03 23:35:19 +00007291 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7292 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7293 return false;
7294 return HandleSizeof(Info, ExprLoc, Ty, Result);
7295 };
7296
George Burgess IVe3763372016-12-22 02:50:20 +00007297 // We want to evaluate the size of the entire object. This is a valid fallback
7298 // for when Type=1 and the designator is invalid, because we're asked for an
7299 // upper-bound.
7300 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7301 // Type=3 wants a lower bound, so we can't fall back to this.
7302 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007303 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007304
7305 llvm::APInt APEndOffset;
7306 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7307 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7308 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7309
7310 if (LVal.InvalidBase)
7311 return false;
7312
7313 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007314 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007315 }
7316
George Burgess IVe3763372016-12-22 02:50:20 +00007317 // We want to evaluate the size of a subobject.
7318 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007319
7320 // The following is a moderately common idiom in C:
7321 //
7322 // struct Foo { int a; char c[1]; };
7323 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7324 // strcpy(&F->c[0], Bar);
7325 //
George Burgess IVe3763372016-12-22 02:50:20 +00007326 // In order to not break too much legacy code, we need to support it.
7327 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7328 // If we can resolve this to an alloc_size call, we can hand that back,
7329 // because we know for certain how many bytes there are to write to.
7330 llvm::APInt APEndOffset;
7331 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7332 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7333 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7334
7335 // If we cannot determine the size of the initial allocation, then we can't
7336 // given an accurate upper-bound. However, we are still able to give
7337 // conservative lower-bounds for Type=3.
7338 if (Type == 1)
7339 return false;
7340 }
7341
7342 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007343 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007344 return false;
7345
George Burgess IVe3763372016-12-22 02:50:20 +00007346 // According to the GCC documentation, we want the size of the subobject
7347 // denoted by the pointer. But that's not quite right -- what we actually
7348 // want is the size of the immediately-enclosing array, if there is one.
7349 int64_t ElemsRemaining;
7350 if (Designator.MostDerivedIsArrayElement &&
7351 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7352 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7353 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7354 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7355 } else {
7356 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7357 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007358
George Burgess IVe3763372016-12-22 02:50:20 +00007359 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7360 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007361}
7362
George Burgess IVe3763372016-12-22 02:50:20 +00007363/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7364/// returns true and stores the result in @p Size.
7365///
7366/// If @p WasError is non-null, this will report whether the failure to evaluate
7367/// is to be treated as an Error in IntExprEvaluator.
7368static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7369 EvalInfo &Info, uint64_t &Size) {
7370 // Determine the denoted object.
7371 LValue LVal;
7372 {
7373 // The operand of __builtin_object_size is never evaluated for side-effects.
7374 // If there are any, but we can determine the pointed-to object anyway, then
7375 // ignore the side-effects.
7376 SpeculativeEvaluationRAII SpeculativeEval(Info);
7377 FoldOffsetRAII Fold(Info);
7378
7379 if (E->isGLValue()) {
7380 // It's possible for us to be given GLValues if we're called via
7381 // Expr::tryEvaluateObjectSize.
7382 APValue RVal;
7383 if (!EvaluateAsRValue(Info, E, RVal))
7384 return false;
7385 LVal.setFrom(Info.Ctx, RVal);
7386 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7387 return false;
7388 }
7389
7390 // If we point to before the start of the object, there are no accessible
7391 // bytes.
7392 if (LVal.getLValueOffset().isNegative()) {
7393 Size = 0;
7394 return true;
7395 }
7396
7397 CharUnits EndOffset;
7398 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7399 return false;
7400
7401 // If we've fallen outside of the end offset, just pretend there's nothing to
7402 // write to/read from.
7403 if (EndOffset <= LVal.getLValueOffset())
7404 Size = 0;
7405 else
7406 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7407 return true;
John McCall95007602010-05-10 23:27:23 +00007408}
7409
Peter Collingbournee9200682011-05-13 03:29:01 +00007410bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007411 if (unsigned BuiltinOp = E->getBuiltinCallee())
7412 return VisitBuiltinCallExpr(E, BuiltinOp);
7413
7414 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7415}
7416
7417bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7418 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007419 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007420 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007421 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007422
7423 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007424 // The type was checked when we built the expression.
7425 unsigned Type =
7426 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7427 assert(Type <= 3 && "unexpected type");
7428
George Burgess IVe3763372016-12-22 02:50:20 +00007429 uint64_t Size;
7430 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7431 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007432
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007433 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007434 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007435
Richard Smith01ade172012-05-23 04:13:20 +00007436 // Expression had no side effects, but we couldn't statically determine the
7437 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007438 switch (Info.EvalMode) {
7439 case EvalInfo::EM_ConstantExpression:
7440 case EvalInfo::EM_PotentialConstantExpression:
7441 case EvalInfo::EM_ConstantFold:
7442 case EvalInfo::EM_EvaluateForOverflow:
7443 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007444 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007445 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007446 return Error(E);
7447 case EvalInfo::EM_ConstantExpressionUnevaluated:
7448 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007449 // Reduce it to a constant now.
7450 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007451 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007452
7453 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007454 }
7455
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007456 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007457 case Builtin::BI__builtin_bswap32:
7458 case Builtin::BI__builtin_bswap64: {
7459 APSInt Val;
7460 if (!EvaluateInteger(E->getArg(0), Val, Info))
7461 return false;
7462
7463 return Success(Val.byteSwap(), E);
7464 }
7465
Richard Smith8889a3d2013-06-13 06:26:32 +00007466 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007467 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007468
7469 // FIXME: BI__builtin_clrsb
7470 // FIXME: BI__builtin_clrsbl
7471 // FIXME: BI__builtin_clrsbll
7472
Richard Smith80b3c8e2013-06-13 05:04:16 +00007473 case Builtin::BI__builtin_clz:
7474 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007475 case Builtin::BI__builtin_clzll:
7476 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007477 APSInt Val;
7478 if (!EvaluateInteger(E->getArg(0), Val, Info))
7479 return false;
7480 if (!Val)
7481 return Error(E);
7482
7483 return Success(Val.countLeadingZeros(), E);
7484 }
7485
Richard Smith8889a3d2013-06-13 06:26:32 +00007486 case Builtin::BI__builtin_constant_p:
7487 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7488
Richard Smith80b3c8e2013-06-13 05:04:16 +00007489 case Builtin::BI__builtin_ctz:
7490 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007491 case Builtin::BI__builtin_ctzll:
7492 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007493 APSInt Val;
7494 if (!EvaluateInteger(E->getArg(0), Val, Info))
7495 return false;
7496 if (!Val)
7497 return Error(E);
7498
7499 return Success(Val.countTrailingZeros(), E);
7500 }
7501
Richard Smith8889a3d2013-06-13 06:26:32 +00007502 case Builtin::BI__builtin_eh_return_data_regno: {
7503 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7504 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7505 return Success(Operand, E);
7506 }
7507
7508 case Builtin::BI__builtin_expect:
7509 return Visit(E->getArg(0));
7510
7511 case Builtin::BI__builtin_ffs:
7512 case Builtin::BI__builtin_ffsl:
7513 case Builtin::BI__builtin_ffsll: {
7514 APSInt Val;
7515 if (!EvaluateInteger(E->getArg(0), Val, Info))
7516 return false;
7517
7518 unsigned N = Val.countTrailingZeros();
7519 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7520 }
7521
7522 case Builtin::BI__builtin_fpclassify: {
7523 APFloat Val(0.0);
7524 if (!EvaluateFloat(E->getArg(5), Val, Info))
7525 return false;
7526 unsigned Arg;
7527 switch (Val.getCategory()) {
7528 case APFloat::fcNaN: Arg = 0; break;
7529 case APFloat::fcInfinity: Arg = 1; break;
7530 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7531 case APFloat::fcZero: Arg = 4; break;
7532 }
7533 return Visit(E->getArg(Arg));
7534 }
7535
7536 case Builtin::BI__builtin_isinf_sign: {
7537 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007538 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007539 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7540 }
7541
Richard Smithea3019d2013-10-15 19:07:14 +00007542 case Builtin::BI__builtin_isinf: {
7543 APFloat Val(0.0);
7544 return EvaluateFloat(E->getArg(0), Val, Info) &&
7545 Success(Val.isInfinity() ? 1 : 0, E);
7546 }
7547
7548 case Builtin::BI__builtin_isfinite: {
7549 APFloat Val(0.0);
7550 return EvaluateFloat(E->getArg(0), Val, Info) &&
7551 Success(Val.isFinite() ? 1 : 0, E);
7552 }
7553
7554 case Builtin::BI__builtin_isnan: {
7555 APFloat Val(0.0);
7556 return EvaluateFloat(E->getArg(0), Val, Info) &&
7557 Success(Val.isNaN() ? 1 : 0, E);
7558 }
7559
7560 case Builtin::BI__builtin_isnormal: {
7561 APFloat Val(0.0);
7562 return EvaluateFloat(E->getArg(0), Val, Info) &&
7563 Success(Val.isNormal() ? 1 : 0, E);
7564 }
7565
Richard Smith8889a3d2013-06-13 06:26:32 +00007566 case Builtin::BI__builtin_parity:
7567 case Builtin::BI__builtin_parityl:
7568 case Builtin::BI__builtin_parityll: {
7569 APSInt Val;
7570 if (!EvaluateInteger(E->getArg(0), Val, Info))
7571 return false;
7572
7573 return Success(Val.countPopulation() % 2, E);
7574 }
7575
Richard Smith80b3c8e2013-06-13 05:04:16 +00007576 case Builtin::BI__builtin_popcount:
7577 case Builtin::BI__builtin_popcountl:
7578 case Builtin::BI__builtin_popcountll: {
7579 APSInt Val;
7580 if (!EvaluateInteger(E->getArg(0), Val, Info))
7581 return false;
7582
7583 return Success(Val.countPopulation(), E);
7584 }
7585
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007586 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007587 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007588 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007589 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007590 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007591 << /*isConstexpr*/0 << /*isConstructor*/0
7592 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007593 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007594 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007595 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007596 case Builtin::BI__builtin_strlen:
7597 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007598 // As an extension, we support __builtin_strlen() as a constant expression,
7599 // and support folding strlen() to a constant.
7600 LValue String;
7601 if (!EvaluatePointer(E->getArg(0), String, Info))
7602 return false;
7603
Richard Smith8110c9d2016-11-29 19:45:17 +00007604 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7605
Richard Smithe6c19f22013-11-15 02:10:04 +00007606 // Fast path: if it's a string literal, search the string value.
7607 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7608 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007609 // The string literal may have embedded null characters. Find the first
7610 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007611 StringRef Str = S->getBytes();
7612 int64_t Off = String.Offset.getQuantity();
7613 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007614 S->getCharByteWidth() == 1 &&
7615 // FIXME: Add fast-path for wchar_t too.
7616 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007617 Str = Str.substr(Off);
7618
7619 StringRef::size_type Pos = Str.find(0);
7620 if (Pos != StringRef::npos)
7621 Str = Str.substr(0, Pos);
7622
7623 return Success(Str.size(), E);
7624 }
7625
7626 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007627 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007628
7629 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007630 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7631 APValue Char;
7632 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7633 !Char.isInt())
7634 return false;
7635 if (!Char.getInt())
7636 return Success(Strlen, E);
7637 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7638 return false;
7639 }
7640 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007641
Richard Smithe151bab2016-11-11 23:43:35 +00007642 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007643 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007644 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007645 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007646 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007647 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007648 // A call to strlen is not a constant expression.
7649 if (Info.getLangOpts().CPlusPlus11)
7650 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7651 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007652 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007653 else
7654 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7655 // Fall through.
7656 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007657 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007658 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007659 case Builtin::BI__builtin_wcsncmp:
7660 case Builtin::BI__builtin_memcmp:
7661 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007662 LValue String1, String2;
7663 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7664 !EvaluatePointer(E->getArg(1), String2, Info))
7665 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007666
7667 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7668
Richard Smithe151bab2016-11-11 23:43:35 +00007669 uint64_t MaxLength = uint64_t(-1);
7670 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007671 BuiltinOp != Builtin::BIwcscmp &&
7672 BuiltinOp != Builtin::BI__builtin_strcmp &&
7673 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007674 APSInt N;
7675 if (!EvaluateInteger(E->getArg(2), N, Info))
7676 return false;
7677 MaxLength = N.getExtValue();
7678 }
7679 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007680 BuiltinOp != Builtin::BIwmemcmp &&
7681 BuiltinOp != Builtin::BI__builtin_memcmp &&
7682 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007683 for (; MaxLength; --MaxLength) {
7684 APValue Char1, Char2;
7685 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7686 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7687 !Char1.isInt() || !Char2.isInt())
7688 return false;
7689 if (Char1.getInt() != Char2.getInt())
7690 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7691 if (StopAtNull && !Char1.getInt())
7692 return Success(0, E);
7693 assert(!(StopAtNull && !Char2.getInt()));
7694 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7695 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7696 return false;
7697 }
7698 // We hit the strncmp / memcmp limit.
7699 return Success(0, E);
7700 }
7701
Richard Smith01ba47d2012-04-13 00:45:38 +00007702 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007703 case Builtin::BI__atomic_is_lock_free:
7704 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007705 APSInt SizeVal;
7706 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7707 return false;
7708
7709 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7710 // of two less than the maximum inline atomic width, we know it is
7711 // lock-free. If the size isn't a power of two, or greater than the
7712 // maximum alignment where we promote atomics, we know it is not lock-free
7713 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7714 // the answer can only be determined at runtime; for example, 16-byte
7715 // atomics have lock-free implementations on some, but not all,
7716 // x86-64 processors.
7717
7718 // Check power-of-two.
7719 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007720 if (Size.isPowerOfTwo()) {
7721 // Check against inlining width.
7722 unsigned InlineWidthBits =
7723 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7724 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7725 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7726 Size == CharUnits::One() ||
7727 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7728 Expr::NPC_NeverValueDependent))
7729 // OK, we will inline appropriately-aligned operations of this size,
7730 // and _Atomic(T) is appropriately-aligned.
7731 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007732
Richard Smith01ba47d2012-04-13 00:45:38 +00007733 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7734 castAs<PointerType>()->getPointeeType();
7735 if (!PointeeType->isIncompleteType() &&
7736 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7737 // OK, we will inline operations on this object.
7738 return Success(1, E);
7739 }
7740 }
7741 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007742
Richard Smith01ba47d2012-04-13 00:45:38 +00007743 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7744 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007745 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007746 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007747}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007748
Richard Smith8b3497e2011-10-31 01:37:14 +00007749static bool HasSameBase(const LValue &A, const LValue &B) {
7750 if (!A.getLValueBase())
7751 return !B.getLValueBase();
7752 if (!B.getLValueBase())
7753 return false;
7754
Richard Smithce40ad62011-11-12 22:28:03 +00007755 if (A.getLValueBase().getOpaqueValue() !=
7756 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007757 const Decl *ADecl = GetLValueBaseDecl(A);
7758 if (!ADecl)
7759 return false;
7760 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007761 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007762 return false;
7763 }
7764
7765 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007766 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007767}
7768
Richard Smithd20f1e62014-10-21 23:01:04 +00007769/// \brief Determine whether this is a pointer past the end of the complete
7770/// object referred to by the lvalue.
7771static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7772 const LValue &LV) {
7773 // A null pointer can be viewed as being "past the end" but we don't
7774 // choose to look at it that way here.
7775 if (!LV.getLValueBase())
7776 return false;
7777
7778 // If the designator is valid and refers to a subobject, we're not pointing
7779 // past the end.
7780 if (!LV.getLValueDesignator().Invalid &&
7781 !LV.getLValueDesignator().isOnePastTheEnd())
7782 return false;
7783
David Majnemerc378ca52015-08-29 08:32:55 +00007784 // A pointer to an incomplete type might be past-the-end if the type's size is
7785 // zero. We cannot tell because the type is incomplete.
7786 QualType Ty = getType(LV.getLValueBase());
7787 if (Ty->isIncompleteType())
7788 return true;
7789
Richard Smithd20f1e62014-10-21 23:01:04 +00007790 // We're a past-the-end pointer if we point to the byte after the object,
7791 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007792 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007793 return LV.getLValueOffset() == Size;
7794}
7795
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007796namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007797
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007798/// \brief Data recursive integer evaluator of certain binary operators.
7799///
7800/// We use a data recursive algorithm for binary operators so that we are able
7801/// to handle extreme cases of chained binary operators without causing stack
7802/// overflow.
7803class DataRecursiveIntBinOpEvaluator {
7804 struct EvalResult {
7805 APValue Val;
7806 bool Failed;
7807
7808 EvalResult() : Failed(false) { }
7809
7810 void swap(EvalResult &RHS) {
7811 Val.swap(RHS.Val);
7812 Failed = RHS.Failed;
7813 RHS.Failed = false;
7814 }
7815 };
7816
7817 struct Job {
7818 const Expr *E;
7819 EvalResult LHSResult; // meaningful only for binary operator expression.
7820 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007821
David Blaikie73726062015-08-12 23:09:24 +00007822 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007823 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007824
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007825 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007826 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007827 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007828
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007829 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007830 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007831 };
7832
7833 SmallVector<Job, 16> Queue;
7834
7835 IntExprEvaluator &IntEval;
7836 EvalInfo &Info;
7837 APValue &FinalResult;
7838
7839public:
7840 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7841 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7842
7843 /// \brief True if \param E is a binary operator that we are going to handle
7844 /// data recursively.
7845 /// We handle binary operators that are comma, logical, or that have operands
7846 /// with integral or enumeration type.
7847 static bool shouldEnqueue(const BinaryOperator *E) {
7848 return E->getOpcode() == BO_Comma ||
7849 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007850 (E->isRValue() &&
7851 E->getType()->isIntegralOrEnumerationType() &&
7852 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007853 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007854 }
7855
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007856 bool Traverse(const BinaryOperator *E) {
7857 enqueue(E);
7858 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007859 while (!Queue.empty())
7860 process(PrevResult);
7861
7862 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007863
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007864 FinalResult.swap(PrevResult.Val);
7865 return true;
7866 }
7867
7868private:
7869 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7870 return IntEval.Success(Value, E, Result);
7871 }
7872 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7873 return IntEval.Success(Value, E, Result);
7874 }
7875 bool Error(const Expr *E) {
7876 return IntEval.Error(E);
7877 }
7878 bool Error(const Expr *E, diag::kind D) {
7879 return IntEval.Error(E, D);
7880 }
7881
7882 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7883 return Info.CCEDiag(E, D);
7884 }
7885
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007886 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7887 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007888 bool &SuppressRHSDiags);
7889
7890 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7891 const BinaryOperator *E, APValue &Result);
7892
7893 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7894 Result.Failed = !Evaluate(Result.Val, Info, E);
7895 if (Result.Failed)
7896 Result.Val = APValue();
7897 }
7898
Richard Trieuba4d0872012-03-21 23:30:30 +00007899 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007900
7901 void enqueue(const Expr *E) {
7902 E = E->IgnoreParens();
7903 Queue.resize(Queue.size()+1);
7904 Queue.back().E = E;
7905 Queue.back().Kind = Job::AnyExprKind;
7906 }
7907};
7908
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007909}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007910
7911bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007912 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007913 bool &SuppressRHSDiags) {
7914 if (E->getOpcode() == BO_Comma) {
7915 // Ignore LHS but note if we could not evaluate it.
7916 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007917 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007918 return true;
7919 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007920
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007921 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007922 bool LHSAsBool;
7923 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007924 // We were able to evaluate the LHS, see if we can get away with not
7925 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007926 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7927 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007928 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007929 }
7930 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007931 LHSResult.Failed = true;
7932
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007933 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007934 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007935 if (!Info.noteSideEffect())
7936 return false;
7937
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007938 // We can't evaluate the LHS; however, sometimes the result
7939 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7940 // Don't ignore RHS and suppress diagnostics from this arm.
7941 SuppressRHSDiags = true;
7942 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007943
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007944 return true;
7945 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007946
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007947 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7948 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007949
George Burgess IVa145e252016-05-25 22:38:36 +00007950 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007951 return false; // Ignore RHS;
7952
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007953 return true;
7954}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007955
Richard Smithd6cc1982017-01-31 02:23:02 +00007956static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) {
7957 // Compute the new offset in the appropriate width, wrapping at 64 bits.
7958 // FIXME: When compiling for a 32-bit target, we should use 32-bit
7959 // offsets.
7960 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
7961 CharUnits &Offset = LVal.getLValueOffset();
7962 uint64_t Offset64 = Offset.getQuantity();
7963 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
7964 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
7965 : Offset64 + Index64);
7966}
7967
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007968bool DataRecursiveIntBinOpEvaluator::
7969 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7970 const BinaryOperator *E, APValue &Result) {
7971 if (E->getOpcode() == BO_Comma) {
7972 if (RHSResult.Failed)
7973 return false;
7974 Result = RHSResult.Val;
7975 return true;
7976 }
7977
7978 if (E->isLogicalOp()) {
7979 bool lhsResult, rhsResult;
7980 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7981 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7982
7983 if (LHSIsOK) {
7984 if (RHSIsOK) {
7985 if (E->getOpcode() == BO_LOr)
7986 return Success(lhsResult || rhsResult, E, Result);
7987 else
7988 return Success(lhsResult && rhsResult, E, Result);
7989 }
7990 } else {
7991 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007992 // We can't evaluate the LHS; however, sometimes the result
7993 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7994 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007995 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007996 }
7997 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007998
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007999 return false;
8000 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008001
8002 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8003 E->getRHS()->getType()->isIntegralOrEnumerationType());
8004
8005 if (LHSResult.Failed || RHSResult.Failed)
8006 return false;
8007
8008 const APValue &LHSVal = LHSResult.Val;
8009 const APValue &RHSVal = RHSResult.Val;
8010
8011 // Handle cases like (unsigned long)&a + 4.
8012 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8013 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008014 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008015 return true;
8016 }
8017
8018 // Handle cases like 4 + (unsigned long)&a
8019 if (E->getOpcode() == BO_Add &&
8020 RHSVal.isLValue() && LHSVal.isInt()) {
8021 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008022 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023 return true;
8024 }
8025
8026 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8027 // Handle (intptr_t)&&A - (intptr_t)&&B.
8028 if (!LHSVal.getLValueOffset().isZero() ||
8029 !RHSVal.getLValueOffset().isZero())
8030 return false;
8031 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8032 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8033 if (!LHSExpr || !RHSExpr)
8034 return false;
8035 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8036 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8037 if (!LHSAddrExpr || !RHSAddrExpr)
8038 return false;
8039 // Make sure both labels come from the same function.
8040 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8041 RHSAddrExpr->getLabel()->getDeclContext())
8042 return false;
8043 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8044 return true;
8045 }
Richard Smith43e77732013-05-07 04:50:00 +00008046
8047 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008048 if (!LHSVal.isInt() || !RHSVal.isInt())
8049 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008050
8051 // Set up the width and signedness manually, in case it can't be deduced
8052 // from the operation we're performing.
8053 // FIXME: Don't do this in the cases where we can deduce it.
8054 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8055 E->getType()->isUnsignedIntegerOrEnumerationType());
8056 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8057 RHSVal.getInt(), Value))
8058 return false;
8059 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008060}
8061
Richard Trieuba4d0872012-03-21 23:30:30 +00008062void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008063 Job &job = Queue.back();
8064
8065 switch (job.Kind) {
8066 case Job::AnyExprKind: {
8067 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8068 if (shouldEnqueue(Bop)) {
8069 job.Kind = Job::BinOpKind;
8070 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008071 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008072 }
8073 }
8074
8075 EvaluateExpr(job.E, Result);
8076 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008077 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008078 }
8079
8080 case Job::BinOpKind: {
8081 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008082 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008083 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008084 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008085 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008086 }
8087 if (SuppressRHSDiags)
8088 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008089 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008090 job.Kind = Job::BinOpVisitedLHSKind;
8091 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008092 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008093 }
8094
8095 case Job::BinOpVisitedLHSKind: {
8096 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8097 EvalResult RHS;
8098 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008099 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008100 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008101 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008102 }
8103 }
8104
8105 llvm_unreachable("Invalid Job::Kind!");
8106}
8107
George Burgess IV8c892b52016-05-25 22:31:54 +00008108namespace {
8109/// Used when we determine that we should fail, but can keep evaluating prior to
8110/// noting that we had a failure.
8111class DelayedNoteFailureRAII {
8112 EvalInfo &Info;
8113 bool NoteFailure;
8114
8115public:
8116 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8117 : Info(Info), NoteFailure(NoteFailure) {}
8118 ~DelayedNoteFailureRAII() {
8119 if (NoteFailure) {
8120 bool ContinueAfterFailure = Info.noteFailure();
8121 (void)ContinueAfterFailure;
8122 assert(ContinueAfterFailure &&
8123 "Shouldn't have kept evaluating on failure.");
8124 }
8125 }
8126};
8127}
8128
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008129bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008130 // We don't call noteFailure immediately because the assignment happens after
8131 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008132 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008133 return Error(E);
8134
George Burgess IV8c892b52016-05-25 22:31:54 +00008135 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008136 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8137 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008138
Anders Carlssonacc79812008-11-16 07:17:21 +00008139 QualType LHSTy = E->getLHS()->getType();
8140 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008141
Chandler Carruthb29a7432014-10-11 11:03:30 +00008142 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008143 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008144 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008145 if (E->isAssignmentOp()) {
8146 LValue LV;
8147 EvaluateLValue(E->getLHS(), LV, Info);
8148 LHSOK = false;
8149 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008150 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8151 if (LHSOK) {
8152 LHS.makeComplexFloat();
8153 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8154 }
8155 } else {
8156 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8157 }
George Burgess IVa145e252016-05-25 22:38:36 +00008158 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008159 return false;
8160
Chandler Carruthb29a7432014-10-11 11:03:30 +00008161 if (E->getRHS()->getType()->isRealFloatingType()) {
8162 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8163 return false;
8164 RHS.makeComplexFloat();
8165 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8166 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008167 return false;
8168
8169 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008170 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008171 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008172 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008173 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8174
John McCalle3027922010-08-25 11:45:40 +00008175 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008176 return Success((CR_r == APFloat::cmpEqual &&
8177 CR_i == APFloat::cmpEqual), E);
8178 else {
John McCalle3027922010-08-25 11:45:40 +00008179 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008180 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008181 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008182 CR_r == APFloat::cmpLessThan ||
8183 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008184 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008185 CR_i == APFloat::cmpLessThan ||
8186 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008187 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008188 } else {
John McCalle3027922010-08-25 11:45:40 +00008189 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008190 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8191 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8192 else {
John McCalle3027922010-08-25 11:45:40 +00008193 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008194 "Invalid compex comparison.");
8195 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8196 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8197 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008198 }
8199 }
Mike Stump11289f42009-09-09 15:08:12 +00008200
Anders Carlssonacc79812008-11-16 07:17:21 +00008201 if (LHSTy->isRealFloatingType() &&
8202 RHSTy->isRealFloatingType()) {
8203 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008204
Richard Smith253c2a32012-01-27 01:14:48 +00008205 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008206 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008207 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008208
Richard Smith253c2a32012-01-27 01:14:48 +00008209 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008210 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008211
Anders Carlssonacc79812008-11-16 07:17:21 +00008212 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008213
Anders Carlssonacc79812008-11-16 07:17:21 +00008214 switch (E->getOpcode()) {
8215 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008216 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008217 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008218 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008219 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008220 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008221 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008222 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008223 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008224 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008225 E);
John McCalle3027922010-08-25 11:45:40 +00008226 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008227 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008228 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008229 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008230 || CR == APFloat::cmpLessThan
8231 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008232 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008233 }
Mike Stump11289f42009-09-09 15:08:12 +00008234
Eli Friedmana38da572009-04-28 19:17:36 +00008235 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008236 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008237 LValue LHSValue, RHSValue;
8238
8239 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008240 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008241 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008242
Richard Smith253c2a32012-01-27 01:14:48 +00008243 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008244 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008245
Richard Smith8b3497e2011-10-31 01:37:14 +00008246 // Reject differing bases from the normal codepath; we special-case
8247 // comparisons to null.
8248 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008249 if (E->getOpcode() == BO_Sub) {
8250 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008251 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008252 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008253 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008254 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008255 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008256 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008257 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8258 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8259 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008260 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008261 // Make sure both labels come from the same function.
8262 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8263 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008264 return Error(E);
8265 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008266 }
Richard Smith83c68212011-10-31 05:11:32 +00008267 // Inequalities and subtractions between unrelated pointers have
8268 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008269 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008270 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008271 // A constant address may compare equal to the address of a symbol.
8272 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008273 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008274 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8275 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008276 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008277 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008278 // distinct addresses. In clang, the result of such a comparison is
8279 // unspecified, so it is not a constant expression. However, we do know
8280 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008281 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8282 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008283 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008284 // We can't tell whether weak symbols will end up pointing to the same
8285 // object.
8286 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008287 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008288 // We can't compare the address of the start of one object with the
8289 // past-the-end address of another object, per C++ DR1652.
8290 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8291 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8292 (RHSValue.Base && RHSValue.Offset.isZero() &&
8293 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8294 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008295 // We can't tell whether an object is at the same address as another
8296 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008297 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8298 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008299 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008300 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008301 // (Note that clang defaults to -fmerge-all-constants, which can
8302 // lead to inconsistent results for comparisons involving the address
8303 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008304 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008305 }
Eli Friedman64004332009-03-23 04:38:34 +00008306
Richard Smith1b470412012-02-01 08:10:20 +00008307 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8308 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8309
Richard Smith84f6dcf2012-02-02 01:16:57 +00008310 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8311 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8312
John McCalle3027922010-08-25 11:45:40 +00008313 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008314 // C++11 [expr.add]p6:
8315 // Unless both pointers point to elements of the same array object, or
8316 // one past the last element of the array object, the behavior is
8317 // undefined.
8318 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8319 !AreElementsOfSameArray(getType(LHSValue.Base),
8320 LHSDesignator, RHSDesignator))
8321 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8322
Chris Lattner882bdf22010-04-20 17:13:14 +00008323 QualType Type = E->getLHS()->getType();
8324 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008325
Richard Smithd62306a2011-11-10 06:34:14 +00008326 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008327 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008328 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008329
Richard Smith84c6b3d2013-09-10 21:34:14 +00008330 // As an extension, a type may have zero size (empty struct or union in
8331 // C, array of zero length). Pointer subtraction in such cases has
8332 // undefined behavior, so is not constant.
8333 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008334 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008335 << ElementType;
8336 return false;
8337 }
8338
Richard Smith1b470412012-02-01 08:10:20 +00008339 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8340 // and produce incorrect results when it overflows. Such behavior
8341 // appears to be non-conforming, but is common, so perhaps we should
8342 // assume the standard intended for such cases to be undefined behavior
8343 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008344
Richard Smith1b470412012-02-01 08:10:20 +00008345 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8346 // overflow in the final conversion to ptrdiff_t.
8347 APSInt LHS(
8348 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8349 APSInt RHS(
8350 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8351 APSInt ElemSize(
8352 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8353 APSInt TrueResult = (LHS - RHS) / ElemSize;
8354 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8355
Richard Smith0c6124b2015-12-03 01:36:22 +00008356 if (Result.extend(65) != TrueResult &&
8357 !HandleOverflow(Info, E, TrueResult, E->getType()))
8358 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008359 return Success(Result, E);
8360 }
Richard Smithde21b242012-01-31 06:41:30 +00008361
8362 // C++11 [expr.rel]p3:
8363 // Pointers to void (after pointer conversions) can be compared, with a
8364 // result defined as follows: If both pointers represent the same
8365 // address or are both the null pointer value, the result is true if the
8366 // operator is <= or >= and false otherwise; otherwise the result is
8367 // unspecified.
8368 // We interpret this as applying to pointers to *cv* void.
8369 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008370 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008371 CCEDiag(E, diag::note_constexpr_void_comparison);
8372
Richard Smith84f6dcf2012-02-02 01:16:57 +00008373 // C++11 [expr.rel]p2:
8374 // - If two pointers point to non-static data members of the same object,
8375 // or to subobjects or array elements fo such members, recursively, the
8376 // pointer to the later declared member compares greater provided the
8377 // two members have the same access control and provided their class is
8378 // not a union.
8379 // [...]
8380 // - Otherwise pointer comparisons are unspecified.
8381 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8382 E->isRelationalOp()) {
8383 bool WasArrayIndex;
8384 unsigned Mismatch =
8385 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8386 RHSDesignator, WasArrayIndex);
8387 // At the point where the designators diverge, the comparison has a
8388 // specified value if:
8389 // - we are comparing array indices
8390 // - we are comparing fields of a union, or fields with the same access
8391 // Otherwise, the result is unspecified and thus the comparison is not a
8392 // constant expression.
8393 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8394 Mismatch < RHSDesignator.Entries.size()) {
8395 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8396 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8397 if (!LF && !RF)
8398 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8399 else if (!LF)
8400 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8401 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8402 << RF->getParent() << RF;
8403 else if (!RF)
8404 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8405 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8406 << LF->getParent() << LF;
8407 else if (!LF->getParent()->isUnion() &&
8408 LF->getAccess() != RF->getAccess())
8409 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8410 << LF << LF->getAccess() << RF << RF->getAccess()
8411 << LF->getParent();
8412 }
8413 }
8414
Eli Friedman6c31cb42012-04-16 04:30:08 +00008415 // The comparison here must be unsigned, and performed with the same
8416 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008417 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8418 uint64_t CompareLHS = LHSOffset.getQuantity();
8419 uint64_t CompareRHS = RHSOffset.getQuantity();
8420 assert(PtrSize <= 64 && "Unexpected pointer width");
8421 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8422 CompareLHS &= Mask;
8423 CompareRHS &= Mask;
8424
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008425 // If there is a base and this is a relational operator, we can only
8426 // compare pointers within the object in question; otherwise, the result
8427 // depends on where the object is located in memory.
8428 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8429 QualType BaseTy = getType(LHSValue.Base);
8430 if (BaseTy->isIncompleteType())
8431 return Error(E);
8432 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8433 uint64_t OffsetLimit = Size.getQuantity();
8434 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8435 return Error(E);
8436 }
8437
Richard Smith8b3497e2011-10-31 01:37:14 +00008438 switch (E->getOpcode()) {
8439 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008440 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8441 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8442 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8443 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8444 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8445 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008446 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008447 }
8448 }
Richard Smith7bb00672012-02-01 01:42:44 +00008449
8450 if (LHSTy->isMemberPointerType()) {
8451 assert(E->isEqualityOp() && "unexpected member pointer operation");
8452 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8453
8454 MemberPtr LHSValue, RHSValue;
8455
8456 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008457 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008458 return false;
8459
8460 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8461 return false;
8462
8463 // C++11 [expr.eq]p2:
8464 // If both operands are null, they compare equal. Otherwise if only one is
8465 // null, they compare unequal.
8466 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8467 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8468 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8469 }
8470
8471 // Otherwise if either is a pointer to a virtual member function, the
8472 // result is unspecified.
8473 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8474 if (MD->isVirtual())
8475 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8477 if (MD->isVirtual())
8478 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8479
8480 // Otherwise they compare equal if and only if they would refer to the
8481 // same member of the same most derived object or the same subobject if
8482 // they were dereferenced with a hypothetical object of the associated
8483 // class type.
8484 bool Equal = LHSValue == RHSValue;
8485 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8486 }
8487
Richard Smithab44d9b2012-02-14 22:35:28 +00008488 if (LHSTy->isNullPtrType()) {
8489 assert(E->isComparisonOp() && "unexpected nullptr operation");
8490 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8491 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8492 // are compared, the result is true of the operator is <=, >= or ==, and
8493 // false otherwise.
8494 BinaryOperator::Opcode Opcode = E->getOpcode();
8495 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8496 }
8497
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008498 assert((!LHSTy->isIntegralOrEnumerationType() ||
8499 !RHSTy->isIntegralOrEnumerationType()) &&
8500 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8501 // We can't continue from here for non-integral types.
8502 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008503}
8504
Peter Collingbournee190dee2011-03-11 19:24:49 +00008505/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8506/// a result as the expression's type.
8507bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8508 const UnaryExprOrTypeTraitExpr *E) {
8509 switch(E->getKind()) {
8510 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008511 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008512 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008513 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008514 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008515 }
Eli Friedman64004332009-03-23 04:38:34 +00008516
Peter Collingbournee190dee2011-03-11 19:24:49 +00008517 case UETT_VecStep: {
8518 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008519
Peter Collingbournee190dee2011-03-11 19:24:49 +00008520 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008521 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008522
Peter Collingbournee190dee2011-03-11 19:24:49 +00008523 // The vec_step built-in functions that take a 3-component
8524 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8525 if (n == 3)
8526 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008527
Peter Collingbournee190dee2011-03-11 19:24:49 +00008528 return Success(n, E);
8529 } else
8530 return Success(1, E);
8531 }
8532
8533 case UETT_SizeOf: {
8534 QualType SrcTy = E->getTypeOfArgument();
8535 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8536 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008537 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8538 SrcTy = Ref->getPointeeType();
8539
Richard Smithd62306a2011-11-10 06:34:14 +00008540 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008541 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008542 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008543 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008544 }
Alexey Bataev00396512015-07-02 03:40:19 +00008545 case UETT_OpenMPRequiredSimdAlign:
8546 assert(E->isArgumentType());
8547 return Success(
8548 Info.Ctx.toCharUnitsFromBits(
8549 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8550 .getQuantity(),
8551 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008552 }
8553
8554 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008555}
8556
Peter Collingbournee9200682011-05-13 03:29:01 +00008557bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008558 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008559 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008560 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008561 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008562 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008563 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008564 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008565 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008566 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008567 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008568 APSInt IdxResult;
8569 if (!EvaluateInteger(Idx, IdxResult, Info))
8570 return false;
8571 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8572 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008573 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008574 CurrentType = AT->getElementType();
8575 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8576 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008577 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008578 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008579
James Y Knight7281c352015-12-29 22:31:18 +00008580 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008581 FieldDecl *MemberDecl = ON.getField();
8582 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008583 if (!RT)
8584 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008585 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008586 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008587 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008588 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008589 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008590 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008591 CurrentType = MemberDecl->getType().getNonReferenceType();
8592 break;
8593 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008594
James Y Knight7281c352015-12-29 22:31:18 +00008595 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008596 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008597
James Y Knight7281c352015-12-29 22:31:18 +00008598 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008599 CXXBaseSpecifier *BaseSpec = ON.getBase();
8600 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008601 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008602
8603 // Find the layout of the class whose base we are looking into.
8604 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008605 if (!RT)
8606 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008607 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008608 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008609 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8610
8611 // Find the base class itself.
8612 CurrentType = BaseSpec->getType();
8613 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8614 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008615 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008616
8617 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008618 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008619 break;
8620 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008621 }
8622 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008623 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008624}
8625
Chris Lattnere13042c2008-07-11 19:10:17 +00008626bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008627 switch (E->getOpcode()) {
8628 default:
8629 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8630 // See C99 6.6p3.
8631 return Error(E);
8632 case UO_Extension:
8633 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8634 // If so, we could clear the diagnostic ID.
8635 return Visit(E->getSubExpr());
8636 case UO_Plus:
8637 // The result is just the value.
8638 return Visit(E->getSubExpr());
8639 case UO_Minus: {
8640 if (!Visit(E->getSubExpr()))
8641 return false;
8642 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008643 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008644 if (Value.isSigned() && Value.isMinSignedValue() &&
8645 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8646 E->getType()))
8647 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008648 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008649 }
8650 case UO_Not: {
8651 if (!Visit(E->getSubExpr()))
8652 return false;
8653 if (!Result.isInt()) return Error(E);
8654 return Success(~Result.getInt(), E);
8655 }
8656 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008657 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008658 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008659 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008660 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008661 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008662 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008663}
Mike Stump11289f42009-09-09 15:08:12 +00008664
Chris Lattner477c4be2008-07-12 01:15:53 +00008665/// HandleCast - This is used to evaluate implicit or explicit casts where the
8666/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008667bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8668 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008669 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008670 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008671
Eli Friedmanc757de22011-03-25 00:43:55 +00008672 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008673 case CK_BaseToDerived:
8674 case CK_DerivedToBase:
8675 case CK_UncheckedDerivedToBase:
8676 case CK_Dynamic:
8677 case CK_ToUnion:
8678 case CK_ArrayToPointerDecay:
8679 case CK_FunctionToPointerDecay:
8680 case CK_NullToPointer:
8681 case CK_NullToMemberPointer:
8682 case CK_BaseToDerivedMemberPointer:
8683 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008684 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008685 case CK_ConstructorConversion:
8686 case CK_IntegralToPointer:
8687 case CK_ToVoid:
8688 case CK_VectorSplat:
8689 case CK_IntegralToFloating:
8690 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008691 case CK_CPointerToObjCPointerCast:
8692 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008693 case CK_AnyPointerToBlockPointerCast:
8694 case CK_ObjCObjectLValueCast:
8695 case CK_FloatingRealToComplex:
8696 case CK_FloatingComplexToReal:
8697 case CK_FloatingComplexCast:
8698 case CK_FloatingComplexToIntegralComplex:
8699 case CK_IntegralRealToComplex:
8700 case CK_IntegralComplexCast:
8701 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008702 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008703 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008704 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008705 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008706 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008707 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008708 llvm_unreachable("invalid cast kind for integral value");
8709
Eli Friedman9faf2f92011-03-25 19:07:11 +00008710 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008711 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008712 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008713 case CK_ARCProduceObject:
8714 case CK_ARCConsumeObject:
8715 case CK_ARCReclaimReturnedObject:
8716 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008717 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008718 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008719
Richard Smith4ef685b2012-01-17 21:17:26 +00008720 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008721 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008722 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008723 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008725
8726 case CK_MemberPointerToBoolean:
8727 case CK_PointerToBoolean:
8728 case CK_IntegralToBoolean:
8729 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008730 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008731 case CK_FloatingComplexToBoolean:
8732 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008733 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008734 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008735 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008736 uint64_t IntResult = BoolResult;
8737 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8738 IntResult = (uint64_t)-1;
8739 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008740 }
8741
Eli Friedmanc757de22011-03-25 00:43:55 +00008742 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008743 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008744 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008745
Eli Friedman742421e2009-02-20 01:15:07 +00008746 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008747 // Allow casts of address-of-label differences if they are no-ops
8748 // or narrowing. (The narrowing case isn't actually guaranteed to
8749 // be constant-evaluatable except in some narrow cases which are hard
8750 // to detect here. We let it through on the assumption the user knows
8751 // what they are doing.)
8752 if (Result.isAddrLabelDiff())
8753 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008754 // Only allow casts of lvalues if they are lossless.
8755 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8756 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008757
Richard Smith911e1422012-01-30 22:27:01 +00008758 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8759 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008760 }
Mike Stump11289f42009-09-09 15:08:12 +00008761
Eli Friedmanc757de22011-03-25 00:43:55 +00008762 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8764
John McCall45d55e42010-05-07 21:00:08 +00008765 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008766 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008767 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008768
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008769 if (LV.getLValueBase()) {
8770 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008771 // FIXME: Allow a larger integer size than the pointer size, and allow
8772 // narrowing back down to pointer width in subsequent integral casts.
8773 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008774 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008775 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008776
Richard Smithcf74da72011-11-16 07:18:12 +00008777 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008778 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008779 return true;
8780 }
8781
Yaxun Liu402804b2016-12-15 08:09:08 +00008782 uint64_t V;
8783 if (LV.isNullPointer())
8784 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8785 else
8786 V = LV.getLValueOffset().getQuantity();
8787
8788 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008789 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008790 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008791
Eli Friedmanc757de22011-03-25 00:43:55 +00008792 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008793 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008794 if (!EvaluateComplex(SubExpr, C, Info))
8795 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008796 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008797 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008798
Eli Friedmanc757de22011-03-25 00:43:55 +00008799 case CK_FloatingToIntegral: {
8800 APFloat F(0.0);
8801 if (!EvaluateFloat(SubExpr, F, Info))
8802 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008803
Richard Smith357362d2011-12-13 06:39:58 +00008804 APSInt Value;
8805 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8806 return false;
8807 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008808 }
8809 }
Mike Stump11289f42009-09-09 15:08:12 +00008810
Eli Friedmanc757de22011-03-25 00:43:55 +00008811 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008812}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008813
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008814bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8815 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008816 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008817 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8818 return false;
8819 if (!LV.isComplexInt())
8820 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008821 return Success(LV.getComplexIntReal(), E);
8822 }
8823
8824 return Visit(E->getSubExpr());
8825}
8826
Eli Friedman4e7a2412009-02-27 04:45:43 +00008827bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008828 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008829 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008830 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8831 return false;
8832 if (!LV.isComplexInt())
8833 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008834 return Success(LV.getComplexIntImag(), E);
8835 }
8836
Richard Smith4a678122011-10-24 18:44:57 +00008837 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008838 return Success(0, E);
8839}
8840
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008841bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8842 return Success(E->getPackLength(), E);
8843}
8844
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008845bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8846 return Success(E->getValue(), E);
8847}
8848
Chris Lattner05706e882008-07-11 18:11:29 +00008849//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008850// Float Evaluation
8851//===----------------------------------------------------------------------===//
8852
8853namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008854class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008855 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008856 APFloat &Result;
8857public:
8858 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008859 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008860
Richard Smith2e312c82012-03-03 22:46:17 +00008861 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008862 Result = V.getFloat();
8863 return true;
8864 }
Eli Friedman24c01542008-08-22 00:06:13 +00008865
Richard Smithfddd3842011-12-30 21:15:51 +00008866 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008867 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8868 return true;
8869 }
8870
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008871 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008872
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008873 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008874 bool VisitBinaryOperator(const BinaryOperator *E);
8875 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008876 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008877
John McCallb1fb0d32010-05-07 22:08:54 +00008878 bool VisitUnaryReal(const UnaryOperator *E);
8879 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008880
Richard Smithfddd3842011-12-30 21:15:51 +00008881 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008882};
8883} // end anonymous namespace
8884
8885static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008886 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008887 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008888}
8889
Jay Foad39c79802011-01-12 09:06:06 +00008890static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008891 QualType ResultTy,
8892 const Expr *Arg,
8893 bool SNaN,
8894 llvm::APFloat &Result) {
8895 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8896 if (!S) return false;
8897
8898 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8899
8900 llvm::APInt fill;
8901
8902 // Treat empty strings as if they were zero.
8903 if (S->getString().empty())
8904 fill = llvm::APInt(32, 0);
8905 else if (S->getString().getAsInteger(0, fill))
8906 return false;
8907
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008908 if (Context.getTargetInfo().isNan2008()) {
8909 if (SNaN)
8910 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8911 else
8912 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8913 } else {
8914 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8915 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8916 // a different encoding to what became a standard in 2008, and for pre-
8917 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8918 // sNaN. This is now known as "legacy NaN" encoding.
8919 if (SNaN)
8920 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8921 else
8922 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8923 }
8924
John McCall16291492010-02-28 13:00:19 +00008925 return true;
8926}
8927
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008928bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008929 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008930 default:
8931 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8932
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008933 case Builtin::BI__builtin_huge_val:
8934 case Builtin::BI__builtin_huge_valf:
8935 case Builtin::BI__builtin_huge_vall:
8936 case Builtin::BI__builtin_inf:
8937 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008938 case Builtin::BI__builtin_infl: {
8939 const llvm::fltSemantics &Sem =
8940 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008941 Result = llvm::APFloat::getInf(Sem);
8942 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008943 }
Mike Stump11289f42009-09-09 15:08:12 +00008944
John McCall16291492010-02-28 13:00:19 +00008945 case Builtin::BI__builtin_nans:
8946 case Builtin::BI__builtin_nansf:
8947 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008948 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8949 true, Result))
8950 return Error(E);
8951 return true;
John McCall16291492010-02-28 13:00:19 +00008952
Chris Lattner0b7282e2008-10-06 06:31:58 +00008953 case Builtin::BI__builtin_nan:
8954 case Builtin::BI__builtin_nanf:
8955 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008956 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008957 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008958 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8959 false, Result))
8960 return Error(E);
8961 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008962
8963 case Builtin::BI__builtin_fabs:
8964 case Builtin::BI__builtin_fabsf:
8965 case Builtin::BI__builtin_fabsl:
8966 if (!EvaluateFloat(E->getArg(0), Result, Info))
8967 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008968
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008969 if (Result.isNegative())
8970 Result.changeSign();
8971 return true;
8972
Richard Smith8889a3d2013-06-13 06:26:32 +00008973 // FIXME: Builtin::BI__builtin_powi
8974 // FIXME: Builtin::BI__builtin_powif
8975 // FIXME: Builtin::BI__builtin_powil
8976
Mike Stump11289f42009-09-09 15:08:12 +00008977 case Builtin::BI__builtin_copysign:
8978 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008979 case Builtin::BI__builtin_copysignl: {
8980 APFloat RHS(0.);
8981 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8982 !EvaluateFloat(E->getArg(1), RHS, Info))
8983 return false;
8984 Result.copySign(RHS);
8985 return true;
8986 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008987 }
8988}
8989
John McCallb1fb0d32010-05-07 22:08:54 +00008990bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008991 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8992 ComplexValue CV;
8993 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8994 return false;
8995 Result = CV.FloatReal;
8996 return true;
8997 }
8998
8999 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009000}
9001
9002bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009003 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9004 ComplexValue CV;
9005 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9006 return false;
9007 Result = CV.FloatImag;
9008 return true;
9009 }
9010
Richard Smith4a678122011-10-24 18:44:57 +00009011 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009012 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9013 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009014 return true;
9015}
9016
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009017bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009018 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009019 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009020 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009021 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009022 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009023 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9024 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009025 Result.changeSign();
9026 return true;
9027 }
9028}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009029
Eli Friedman24c01542008-08-22 00:06:13 +00009030bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009031 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9032 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009033
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009034 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009035 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009036 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009037 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009038 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9039 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009040}
9041
9042bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9043 Result = E->getValue();
9044 return true;
9045}
9046
Peter Collingbournee9200682011-05-13 03:29:01 +00009047bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9048 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009049
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009050 switch (E->getCastKind()) {
9051 default:
Richard Smith11562c52011-10-28 17:51:58 +00009052 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009053
9054 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009055 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009056 return EvaluateInteger(SubExpr, IntResult, Info) &&
9057 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9058 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009059 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009060
9061 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009062 if (!Visit(SubExpr))
9063 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009064 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9065 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009066 }
John McCalld7646252010-11-14 08:17:51 +00009067
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009068 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009069 ComplexValue V;
9070 if (!EvaluateComplex(SubExpr, V, Info))
9071 return false;
9072 Result = V.getComplexFloatReal();
9073 return true;
9074 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009075 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009076}
9077
Eli Friedman24c01542008-08-22 00:06:13 +00009078//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009079// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009080//===----------------------------------------------------------------------===//
9081
9082namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009083class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009084 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009085 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009086
Anders Carlsson537969c2008-11-16 20:27:53 +00009087public:
John McCall93d91dc2010-05-07 17:22:02 +00009088 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009089 : ExprEvaluatorBaseTy(info), Result(Result) {}
9090
Richard Smith2e312c82012-03-03 22:46:17 +00009091 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009092 Result.setFrom(V);
9093 return true;
9094 }
Mike Stump11289f42009-09-09 15:08:12 +00009095
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009096 bool ZeroInitialization(const Expr *E);
9097
Anders Carlsson537969c2008-11-16 20:27:53 +00009098 //===--------------------------------------------------------------------===//
9099 // Visitor Methods
9100 //===--------------------------------------------------------------------===//
9101
Peter Collingbournee9200682011-05-13 03:29:01 +00009102 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009103 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009104 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009105 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009106 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009107};
9108} // end anonymous namespace
9109
John McCall93d91dc2010-05-07 17:22:02 +00009110static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9111 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009112 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009113 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009114}
9115
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009116bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009117 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009118 if (ElemTy->isRealFloatingType()) {
9119 Result.makeComplexFloat();
9120 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9121 Result.FloatReal = Zero;
9122 Result.FloatImag = Zero;
9123 } else {
9124 Result.makeComplexInt();
9125 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9126 Result.IntReal = Zero;
9127 Result.IntImag = Zero;
9128 }
9129 return true;
9130}
9131
Peter Collingbournee9200682011-05-13 03:29:01 +00009132bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9133 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009134
9135 if (SubExpr->getType()->isRealFloatingType()) {
9136 Result.makeComplexFloat();
9137 APFloat &Imag = Result.FloatImag;
9138 if (!EvaluateFloat(SubExpr, Imag, Info))
9139 return false;
9140
9141 Result.FloatReal = APFloat(Imag.getSemantics());
9142 return true;
9143 } else {
9144 assert(SubExpr->getType()->isIntegerType() &&
9145 "Unexpected imaginary literal.");
9146
9147 Result.makeComplexInt();
9148 APSInt &Imag = Result.IntImag;
9149 if (!EvaluateInteger(SubExpr, Imag, Info))
9150 return false;
9151
9152 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9153 return true;
9154 }
9155}
9156
Peter Collingbournee9200682011-05-13 03:29:01 +00009157bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009158
John McCallfcef3cf2010-12-14 17:51:41 +00009159 switch (E->getCastKind()) {
9160 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009161 case CK_BaseToDerived:
9162 case CK_DerivedToBase:
9163 case CK_UncheckedDerivedToBase:
9164 case CK_Dynamic:
9165 case CK_ToUnion:
9166 case CK_ArrayToPointerDecay:
9167 case CK_FunctionToPointerDecay:
9168 case CK_NullToPointer:
9169 case CK_NullToMemberPointer:
9170 case CK_BaseToDerivedMemberPointer:
9171 case CK_DerivedToBaseMemberPointer:
9172 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009173 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009174 case CK_ConstructorConversion:
9175 case CK_IntegralToPointer:
9176 case CK_PointerToIntegral:
9177 case CK_PointerToBoolean:
9178 case CK_ToVoid:
9179 case CK_VectorSplat:
9180 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009181 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009182 case CK_IntegralToBoolean:
9183 case CK_IntegralToFloating:
9184 case CK_FloatingToIntegral:
9185 case CK_FloatingToBoolean:
9186 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009187 case CK_CPointerToObjCPointerCast:
9188 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009189 case CK_AnyPointerToBlockPointerCast:
9190 case CK_ObjCObjectLValueCast:
9191 case CK_FloatingComplexToReal:
9192 case CK_FloatingComplexToBoolean:
9193 case CK_IntegralComplexToReal:
9194 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009195 case CK_ARCProduceObject:
9196 case CK_ARCConsumeObject:
9197 case CK_ARCReclaimReturnedObject:
9198 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009199 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009200 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009201 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009202 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009203 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009204 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009205 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009206 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009207
John McCallfcef3cf2010-12-14 17:51:41 +00009208 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009209 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009210 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009211 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009212
9213 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009214 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009215 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009216 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009217
9218 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009219 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009220 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009221 return false;
9222
John McCallfcef3cf2010-12-14 17:51:41 +00009223 Result.makeComplexFloat();
9224 Result.FloatImag = APFloat(Real.getSemantics());
9225 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009226 }
9227
John McCallfcef3cf2010-12-14 17:51:41 +00009228 case CK_FloatingComplexCast: {
9229 if (!Visit(E->getSubExpr()))
9230 return false;
9231
9232 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9233 QualType From
9234 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9235
Richard Smith357362d2011-12-13 06:39:58 +00009236 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9237 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009238 }
9239
9240 case CK_FloatingComplexToIntegralComplex: {
9241 if (!Visit(E->getSubExpr()))
9242 return false;
9243
9244 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9245 QualType From
9246 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9247 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009248 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9249 To, Result.IntReal) &&
9250 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9251 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009252 }
9253
9254 case CK_IntegralRealToComplex: {
9255 APSInt &Real = Result.IntReal;
9256 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9257 return false;
9258
9259 Result.makeComplexInt();
9260 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9261 return true;
9262 }
9263
9264 case CK_IntegralComplexCast: {
9265 if (!Visit(E->getSubExpr()))
9266 return false;
9267
9268 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9269 QualType From
9270 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9271
Richard Smith911e1422012-01-30 22:27:01 +00009272 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9273 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009274 return true;
9275 }
9276
9277 case CK_IntegralComplexToFloatingComplex: {
9278 if (!Visit(E->getSubExpr()))
9279 return false;
9280
Ted Kremenek28831752012-08-23 20:46:57 +00009281 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009282 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009283 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009284 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009285 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9286 To, Result.FloatReal) &&
9287 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9288 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009289 }
9290 }
9291
9292 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009293}
9294
John McCall93d91dc2010-05-07 17:22:02 +00009295bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009296 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009297 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9298
Chandler Carrutha216cad2014-10-11 00:57:18 +00009299 // Track whether the LHS or RHS is real at the type system level. When this is
9300 // the case we can simplify our evaluation strategy.
9301 bool LHSReal = false, RHSReal = false;
9302
9303 bool LHSOK;
9304 if (E->getLHS()->getType()->isRealFloatingType()) {
9305 LHSReal = true;
9306 APFloat &Real = Result.FloatReal;
9307 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9308 if (LHSOK) {
9309 Result.makeComplexFloat();
9310 Result.FloatImag = APFloat(Real.getSemantics());
9311 }
9312 } else {
9313 LHSOK = Visit(E->getLHS());
9314 }
George Burgess IVa145e252016-05-25 22:38:36 +00009315 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009316 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009317
John McCall93d91dc2010-05-07 17:22:02 +00009318 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009319 if (E->getRHS()->getType()->isRealFloatingType()) {
9320 RHSReal = true;
9321 APFloat &Real = RHS.FloatReal;
9322 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9323 return false;
9324 RHS.makeComplexFloat();
9325 RHS.FloatImag = APFloat(Real.getSemantics());
9326 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009327 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009328
Chandler Carrutha216cad2014-10-11 00:57:18 +00009329 assert(!(LHSReal && RHSReal) &&
9330 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009331 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009332 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009333 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009334 if (Result.isComplexFloat()) {
9335 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9336 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009337 if (LHSReal)
9338 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9339 else if (!RHSReal)
9340 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9341 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009342 } else {
9343 Result.getComplexIntReal() += RHS.getComplexIntReal();
9344 Result.getComplexIntImag() += RHS.getComplexIntImag();
9345 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009346 break;
John McCalle3027922010-08-25 11:45:40 +00009347 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009348 if (Result.isComplexFloat()) {
9349 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9350 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009351 if (LHSReal) {
9352 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9353 Result.getComplexFloatImag().changeSign();
9354 } else if (!RHSReal) {
9355 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9356 APFloat::rmNearestTiesToEven);
9357 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009358 } else {
9359 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9360 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9361 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009362 break;
John McCalle3027922010-08-25 11:45:40 +00009363 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009364 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009365 // This is an implementation of complex multiplication according to the
9366 // constraints laid out in C11 Annex G. The implemantion uses the
9367 // following naming scheme:
9368 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009369 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009370 APFloat &A = LHS.getComplexFloatReal();
9371 APFloat &B = LHS.getComplexFloatImag();
9372 APFloat &C = RHS.getComplexFloatReal();
9373 APFloat &D = RHS.getComplexFloatImag();
9374 APFloat &ResR = Result.getComplexFloatReal();
9375 APFloat &ResI = Result.getComplexFloatImag();
9376 if (LHSReal) {
9377 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9378 ResR = A * C;
9379 ResI = A * D;
9380 } else if (RHSReal) {
9381 ResR = C * A;
9382 ResI = C * B;
9383 } else {
9384 // In the fully general case, we need to handle NaNs and infinities
9385 // robustly.
9386 APFloat AC = A * C;
9387 APFloat BD = B * D;
9388 APFloat AD = A * D;
9389 APFloat BC = B * C;
9390 ResR = AC - BD;
9391 ResI = AD + BC;
9392 if (ResR.isNaN() && ResI.isNaN()) {
9393 bool Recalc = false;
9394 if (A.isInfinity() || B.isInfinity()) {
9395 A = APFloat::copySign(
9396 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9397 B = APFloat::copySign(
9398 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9399 if (C.isNaN())
9400 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9401 if (D.isNaN())
9402 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9403 Recalc = true;
9404 }
9405 if (C.isInfinity() || D.isInfinity()) {
9406 C = APFloat::copySign(
9407 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9408 D = APFloat::copySign(
9409 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9410 if (A.isNaN())
9411 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9412 if (B.isNaN())
9413 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9414 Recalc = true;
9415 }
9416 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9417 AD.isInfinity() || BC.isInfinity())) {
9418 if (A.isNaN())
9419 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9420 if (B.isNaN())
9421 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9422 if (C.isNaN())
9423 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9424 if (D.isNaN())
9425 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9426 Recalc = true;
9427 }
9428 if (Recalc) {
9429 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9430 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9431 }
9432 }
9433 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009434 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009435 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009436 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009437 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9438 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009439 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009440 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9441 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9442 }
9443 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009444 case BO_Div:
9445 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009446 // This is an implementation of complex division according to the
9447 // constraints laid out in C11 Annex G. The implemantion uses the
9448 // following naming scheme:
9449 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009450 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009451 APFloat &A = LHS.getComplexFloatReal();
9452 APFloat &B = LHS.getComplexFloatImag();
9453 APFloat &C = RHS.getComplexFloatReal();
9454 APFloat &D = RHS.getComplexFloatImag();
9455 APFloat &ResR = Result.getComplexFloatReal();
9456 APFloat &ResI = Result.getComplexFloatImag();
9457 if (RHSReal) {
9458 ResR = A / C;
9459 ResI = B / C;
9460 } else {
9461 if (LHSReal) {
9462 // No real optimizations we can do here, stub out with zero.
9463 B = APFloat::getZero(A.getSemantics());
9464 }
9465 int DenomLogB = 0;
9466 APFloat MaxCD = maxnum(abs(C), abs(D));
9467 if (MaxCD.isFinite()) {
9468 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009469 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9470 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009471 }
9472 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009473 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9474 APFloat::rmNearestTiesToEven);
9475 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9476 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009477 if (ResR.isNaN() && ResI.isNaN()) {
9478 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9479 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9480 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9481 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9482 D.isFinite()) {
9483 A = APFloat::copySign(
9484 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9485 B = APFloat::copySign(
9486 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9487 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9488 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9489 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9490 C = APFloat::copySign(
9491 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9492 D = APFloat::copySign(
9493 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9494 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9495 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9496 }
9497 }
9498 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009499 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009500 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9501 return Error(E, diag::note_expr_divide_by_zero);
9502
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009503 ComplexValue LHS = Result;
9504 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9505 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9506 Result.getComplexIntReal() =
9507 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9508 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9509 Result.getComplexIntImag() =
9510 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9511 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9512 }
9513 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009514 }
9515
John McCall93d91dc2010-05-07 17:22:02 +00009516 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009517}
9518
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009519bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9520 // Get the operand value into 'Result'.
9521 if (!Visit(E->getSubExpr()))
9522 return false;
9523
9524 switch (E->getOpcode()) {
9525 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009526 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009527 case UO_Extension:
9528 return true;
9529 case UO_Plus:
9530 // The result is always just the subexpr.
9531 return true;
9532 case UO_Minus:
9533 if (Result.isComplexFloat()) {
9534 Result.getComplexFloatReal().changeSign();
9535 Result.getComplexFloatImag().changeSign();
9536 }
9537 else {
9538 Result.getComplexIntReal() = -Result.getComplexIntReal();
9539 Result.getComplexIntImag() = -Result.getComplexIntImag();
9540 }
9541 return true;
9542 case UO_Not:
9543 if (Result.isComplexFloat())
9544 Result.getComplexFloatImag().changeSign();
9545 else
9546 Result.getComplexIntImag() = -Result.getComplexIntImag();
9547 return true;
9548 }
9549}
9550
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009551bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9552 if (E->getNumInits() == 2) {
9553 if (E->getType()->isComplexType()) {
9554 Result.makeComplexFloat();
9555 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9556 return false;
9557 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9558 return false;
9559 } else {
9560 Result.makeComplexInt();
9561 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9562 return false;
9563 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9564 return false;
9565 }
9566 return true;
9567 }
9568 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9569}
9570
Anders Carlsson537969c2008-11-16 20:27:53 +00009571//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009572// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9573// implicit conversion.
9574//===----------------------------------------------------------------------===//
9575
9576namespace {
9577class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009578 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009579 APValue &Result;
9580public:
9581 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9582 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9583
9584 bool Success(const APValue &V, const Expr *E) {
9585 Result = V;
9586 return true;
9587 }
9588
9589 bool ZeroInitialization(const Expr *E) {
9590 ImplicitValueInitExpr VIE(
9591 E->getType()->castAs<AtomicType>()->getValueType());
9592 return Evaluate(Result, Info, &VIE);
9593 }
9594
9595 bool VisitCastExpr(const CastExpr *E) {
9596 switch (E->getCastKind()) {
9597 default:
9598 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9599 case CK_NonAtomicToAtomic:
9600 return Evaluate(Result, Info, E->getSubExpr());
9601 }
9602 }
9603};
9604} // end anonymous namespace
9605
9606static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9607 assert(E->isRValue() && E->getType()->isAtomicType());
9608 return AtomicExprEvaluator(Info, Result).Visit(E);
9609}
9610
9611//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009612// Void expression evaluation, primarily for a cast to void on the LHS of a
9613// comma operator
9614//===----------------------------------------------------------------------===//
9615
9616namespace {
9617class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009618 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009619public:
9620 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9621
Richard Smith2e312c82012-03-03 22:46:17 +00009622 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009623
9624 bool VisitCastExpr(const CastExpr *E) {
9625 switch (E->getCastKind()) {
9626 default:
9627 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9628 case CK_ToVoid:
9629 VisitIgnoredValue(E->getSubExpr());
9630 return true;
9631 }
9632 }
Hal Finkela8443c32014-07-17 14:49:58 +00009633
9634 bool VisitCallExpr(const CallExpr *E) {
9635 switch (E->getBuiltinCallee()) {
9636 default:
9637 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9638 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009639 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009640 // The argument is not evaluated!
9641 return true;
9642 }
9643 }
Richard Smith42d3af92011-12-07 00:43:50 +00009644};
9645} // end anonymous namespace
9646
9647static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9648 assert(E->isRValue() && E->getType()->isVoidType());
9649 return VoidExprEvaluator(Info).Visit(E);
9650}
9651
9652//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009653// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009654//===----------------------------------------------------------------------===//
9655
Richard Smith2e312c82012-03-03 22:46:17 +00009656static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009657 // In C, function designators are not lvalues, but we evaluate them as if they
9658 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009659 QualType T = E->getType();
9660 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009661 LValue LV;
9662 if (!EvaluateLValue(E, LV, Info))
9663 return false;
9664 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009665 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009666 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009667 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009668 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009669 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009670 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009671 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009672 LValue LV;
9673 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009674 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009675 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009676 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009677 llvm::APFloat F(0.0);
9678 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009679 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009680 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009681 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009682 ComplexValue C;
9683 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009684 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009685 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009686 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009687 MemberPtr P;
9688 if (!EvaluateMemberPointer(E, P, Info))
9689 return false;
9690 P.moveInto(Result);
9691 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009692 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009693 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009694 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009695 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9696 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009697 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009698 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009699 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009700 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009701 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009702 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9703 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009704 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009705 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009706 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009707 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009708 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009709 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009710 if (!EvaluateVoid(E, Info))
9711 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009712 } else if (T->isAtomicType()) {
9713 if (!EvaluateAtomic(E, Result, Info))
9714 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009715 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009716 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009717 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009718 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009719 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009720 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009721 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009722
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009723 return true;
9724}
9725
Richard Smithb228a862012-02-15 02:18:13 +00009726/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9727/// cases, the in-place evaluation is essential, since later initializers for
9728/// an object can indirectly refer to subobjects which were initialized earlier.
9729static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009730 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009731 assert(!E->isValueDependent());
9732
Richard Smith7525ff62013-05-09 07:14:00 +00009733 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009734 return false;
9735
9736 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009737 // Evaluate arrays and record types in-place, so that later initializers can
9738 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009739 if (E->getType()->isArrayType())
9740 return EvaluateArray(E, This, Result, Info);
9741 else if (E->getType()->isRecordType())
9742 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009743 }
9744
9745 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009746 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009747}
9748
Richard Smithf57d8cb2011-12-09 22:58:01 +00009749/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9750/// lvalue-to-rvalue cast if it is an lvalue.
9751static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009752 if (E->getType().isNull())
9753 return false;
9754
Richard Smithfddd3842011-12-30 21:15:51 +00009755 if (!CheckLiteralType(Info, E))
9756 return false;
9757
Richard Smith2e312c82012-03-03 22:46:17 +00009758 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009759 return false;
9760
9761 if (E->isGLValue()) {
9762 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009763 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009764 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009765 return false;
9766 }
9767
Richard Smith2e312c82012-03-03 22:46:17 +00009768 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009769 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009770}
Richard Smith11562c52011-10-28 17:51:58 +00009771
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009772static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9773 const ASTContext &Ctx, bool &IsConst) {
9774 // Fast-path evaluations of integer literals, since we sometimes see files
9775 // containing vast quantities of these.
9776 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9777 Result.Val = APValue(APSInt(L->getValue(),
9778 L->getType()->isUnsignedIntegerType()));
9779 IsConst = true;
9780 return true;
9781 }
James Dennett0492ef02014-03-14 17:44:10 +00009782
9783 // This case should be rare, but we need to check it before we check on
9784 // the type below.
9785 if (Exp->getType().isNull()) {
9786 IsConst = false;
9787 return true;
9788 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009789
9790 // FIXME: Evaluating values of large array and record types can cause
9791 // performance problems. Only do so in C++11 for now.
9792 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9793 Exp->getType()->isRecordType()) &&
9794 !Ctx.getLangOpts().CPlusPlus11) {
9795 IsConst = false;
9796 return true;
9797 }
9798 return false;
9799}
9800
9801
Richard Smith7b553f12011-10-29 00:50:52 +00009802/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009803/// any crazy technique (that has nothing to do with language standards) that
9804/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009805/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9806/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009807bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009808 bool IsConst;
9809 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9810 return IsConst;
9811
Richard Smith6d4c6582013-11-05 22:18:15 +00009812 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009813 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009814}
9815
Jay Foad39c79802011-01-12 09:06:06 +00009816bool Expr::EvaluateAsBooleanCondition(bool &Result,
9817 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009818 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009819 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009820 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009821}
9822
Richard Smithce8eca52015-12-08 03:21:47 +00009823static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9824 Expr::SideEffectsKind SEK) {
9825 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9826 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9827}
9828
Richard Smith5fab0c92011-12-28 19:48:30 +00009829bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9830 SideEffectsKind AllowSideEffects) const {
9831 if (!getType()->isIntegralOrEnumerationType())
9832 return false;
9833
Richard Smith11562c52011-10-28 17:51:58 +00009834 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009835 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009836 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009837 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009838
Richard Smith11562c52011-10-28 17:51:58 +00009839 Result = ExprResult.Val.getInt();
9840 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009841}
9842
Richard Trieube234c32016-04-21 21:04:55 +00009843bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9844 SideEffectsKind AllowSideEffects) const {
9845 if (!getType()->isRealFloatingType())
9846 return false;
9847
9848 EvalResult ExprResult;
9849 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9850 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9851 return false;
9852
9853 Result = ExprResult.Val.getFloat();
9854 return true;
9855}
9856
Jay Foad39c79802011-01-12 09:06:06 +00009857bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009858 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009859
John McCall45d55e42010-05-07 21:00:08 +00009860 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009861 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9862 !CheckLValueConstantExpression(Info, getExprLoc(),
9863 Ctx.getLValueReferenceType(getType()), LV))
9864 return false;
9865
Richard Smith2e312c82012-03-03 22:46:17 +00009866 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009867 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009868}
9869
Richard Smithd0b4dd62011-12-19 06:19:21 +00009870bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9871 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009872 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009873 // FIXME: Evaluating initializers for large array and record types can cause
9874 // performance problems. Only do so in C++11 for now.
9875 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009876 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009877 return false;
9878
Richard Smithd0b4dd62011-12-19 06:19:21 +00009879 Expr::EvalStatus EStatus;
9880 EStatus.Diag = &Notes;
9881
Richard Smith0c6124b2015-12-03 01:36:22 +00009882 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9883 ? EvalInfo::EM_ConstantExpression
9884 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009885 InitInfo.setEvaluatingDecl(VD, Value);
9886
9887 LValue LVal;
9888 LVal.set(VD);
9889
Richard Smithfddd3842011-12-30 21:15:51 +00009890 // C++11 [basic.start.init]p2:
9891 // Variables with static storage duration or thread storage duration shall be
9892 // zero-initialized before any other initialization takes place.
9893 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009894 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009895 !VD->getType()->isReferenceType()) {
9896 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009897 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009898 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009899 return false;
9900 }
9901
Richard Smith7525ff62013-05-09 07:14:00 +00009902 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9903 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009904 EStatus.HasSideEffects)
9905 return false;
9906
9907 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9908 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009909}
9910
Richard Smith7b553f12011-10-29 00:50:52 +00009911/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9912/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009913bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009914 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009915 return EvaluateAsRValue(Result, Ctx) &&
9916 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009917}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009918
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009919APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009920 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009921 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009922 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009923 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009924 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009925 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009926 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009927
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009928 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009929}
John McCall864e3962010-05-07 05:32:02 +00009930
Richard Smithe9ff7702013-11-05 22:23:30 +00009931void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009932 bool IsConst;
9933 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009934 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009935 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009936 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9937 }
9938}
9939
Richard Smithe6c01442013-06-05 00:46:14 +00009940bool Expr::EvalResult::isGlobalLValue() const {
9941 assert(Val.isLValue());
9942 return IsGlobalLValue(Val.getLValueBase());
9943}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009944
9945
John McCall864e3962010-05-07 05:32:02 +00009946/// isIntegerConstantExpr - this recursive routine will test if an expression is
9947/// an integer constant expression.
9948
9949/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9950/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009951
9952// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009953// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9954// and a (possibly null) SourceLocation indicating the location of the problem.
9955//
John McCall864e3962010-05-07 05:32:02 +00009956// Note that to reduce code duplication, this helper does no evaluation
9957// itself; the caller checks whether the expression is evaluatable, and
9958// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +00009959// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +00009960
Dan Gohman28ade552010-07-26 21:25:24 +00009961namespace {
9962
Richard Smith9e575da2012-12-28 13:25:52 +00009963enum ICEKind {
9964 /// This expression is an ICE.
9965 IK_ICE,
9966 /// This expression is not an ICE, but if it isn't evaluated, it's
9967 /// a legal subexpression for an ICE. This return value is used to handle
9968 /// the comma operator in C99 mode, and non-constant subexpressions.
9969 IK_ICEIfUnevaluated,
9970 /// This expression is not an ICE, and is not a legal subexpression for one.
9971 IK_NotICE
9972};
9973
John McCall864e3962010-05-07 05:32:02 +00009974struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009975 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009976 SourceLocation Loc;
9977
Richard Smith9e575da2012-12-28 13:25:52 +00009978 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009979};
9980
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009981}
Dan Gohman28ade552010-07-26 21:25:24 +00009982
Richard Smith9e575da2012-12-28 13:25:52 +00009983static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9984
9985static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009986
Craig Toppera31a8822013-08-22 07:09:37 +00009987static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009988 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009989 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009990 !EVResult.Val.isInt())
9991 return ICEDiag(IK_NotICE, E->getLocStart());
9992
John McCall864e3962010-05-07 05:32:02 +00009993 return NoDiag();
9994}
9995
Craig Toppera31a8822013-08-22 07:09:37 +00009996static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009997 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009998 if (!E->getType()->isIntegralOrEnumerationType())
9999 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010000
10001 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010002#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010003#define STMT(Node, Base) case Expr::Node##Class:
10004#define EXPR(Node, Base)
10005#include "clang/AST/StmtNodes.inc"
10006 case Expr::PredefinedExprClass:
10007 case Expr::FloatingLiteralClass:
10008 case Expr::ImaginaryLiteralClass:
10009 case Expr::StringLiteralClass:
10010 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010011 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010012 case Expr::MemberExprClass:
10013 case Expr::CompoundAssignOperatorClass:
10014 case Expr::CompoundLiteralExprClass:
10015 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010016 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010017 case Expr::ArrayInitLoopExprClass:
10018 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010019 case Expr::NoInitExprClass:
10020 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010021 case Expr::ImplicitValueInitExprClass:
10022 case Expr::ParenListExprClass:
10023 case Expr::VAArgExprClass:
10024 case Expr::AddrLabelExprClass:
10025 case Expr::StmtExprClass:
10026 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010027 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010028 case Expr::CXXDynamicCastExprClass:
10029 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010030 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010031 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010032 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010033 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010034 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010035 case Expr::CXXThisExprClass:
10036 case Expr::CXXThrowExprClass:
10037 case Expr::CXXNewExprClass:
10038 case Expr::CXXDeleteExprClass:
10039 case Expr::CXXPseudoDestructorExprClass:
10040 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010041 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010042 case Expr::DependentScopeDeclRefExprClass:
10043 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010044 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010045 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010046 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010047 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010048 case Expr::CXXTemporaryObjectExprClass:
10049 case Expr::CXXUnresolvedConstructExprClass:
10050 case Expr::CXXDependentScopeMemberExprClass:
10051 case Expr::UnresolvedMemberExprClass:
10052 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010053 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010054 case Expr::ObjCArrayLiteralClass:
10055 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010056 case Expr::ObjCEncodeExprClass:
10057 case Expr::ObjCMessageExprClass:
10058 case Expr::ObjCSelectorExprClass:
10059 case Expr::ObjCProtocolExprClass:
10060 case Expr::ObjCIvarRefExprClass:
10061 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010062 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010063 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010064 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010065 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010066 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010067 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010068 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010069 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010070 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010071 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010072 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010073 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010074 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010075 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010076 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010077 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010078 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010079 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010080 case Expr::CoawaitExprClass:
10081 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010082 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010083
Richard Smithf137f932014-01-25 20:50:08 +000010084 case Expr::InitListExprClass: {
10085 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10086 // form "T x = { a };" is equivalent to "T x = a;".
10087 // Unless we're initializing a reference, T is a scalar as it is known to be
10088 // of integral or enumeration type.
10089 if (E->isRValue())
10090 if (cast<InitListExpr>(E)->getNumInits() == 1)
10091 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10092 return ICEDiag(IK_NotICE, E->getLocStart());
10093 }
10094
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010095 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010096 case Expr::GNUNullExprClass:
10097 // GCC considers the GNU __null value to be an integral constant expression.
10098 return NoDiag();
10099
John McCall7c454bb2011-07-15 05:09:51 +000010100 case Expr::SubstNonTypeTemplateParmExprClass:
10101 return
10102 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10103
John McCall864e3962010-05-07 05:32:02 +000010104 case Expr::ParenExprClass:
10105 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010106 case Expr::GenericSelectionExprClass:
10107 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010108 case Expr::IntegerLiteralClass:
10109 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010110 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010111 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010112 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010113 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010114 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010115 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010116 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010117 return NoDiag();
10118 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010119 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010120 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10121 // constant expressions, but they can never be ICEs because an ICE cannot
10122 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010123 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010124 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010125 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010126 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010127 }
Richard Smith6365c912012-02-24 22:12:32 +000010128 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010129 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10130 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010131 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010132 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010133 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010134 // Parameter variables are never constants. Without this check,
10135 // getAnyInitializer() can find a default argument, which leads
10136 // to chaos.
10137 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010138 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010139
10140 // C++ 7.1.5.1p2
10141 // A variable of non-volatile const-qualified integral or enumeration
10142 // type initialized by an ICE can be used in ICEs.
10143 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010144 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010145 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010146
Richard Smithd0b4dd62011-12-19 06:19:21 +000010147 const VarDecl *VD;
10148 // Look for a declaration of this variable that has an initializer, and
10149 // check whether it is an ICE.
10150 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10151 return NoDiag();
10152 else
Richard Smith9e575da2012-12-28 13:25:52 +000010153 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010154 }
10155 }
Richard Smith9e575da2012-12-28 13:25:52 +000010156 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010157 }
John McCall864e3962010-05-07 05:32:02 +000010158 case Expr::UnaryOperatorClass: {
10159 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10160 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010161 case UO_PostInc:
10162 case UO_PostDec:
10163 case UO_PreInc:
10164 case UO_PreDec:
10165 case UO_AddrOf:
10166 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010167 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010168 // C99 6.6/3 allows increment and decrement within unevaluated
10169 // subexpressions of constant expressions, but they can never be ICEs
10170 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010171 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010172 case UO_Extension:
10173 case UO_LNot:
10174 case UO_Plus:
10175 case UO_Minus:
10176 case UO_Not:
10177 case UO_Real:
10178 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010179 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010180 }
Richard Smith9e575da2012-12-28 13:25:52 +000010181
John McCall864e3962010-05-07 05:32:02 +000010182 // OffsetOf falls through here.
10183 }
10184 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010185 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10186 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10187 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10188 // compliance: we should warn earlier for offsetof expressions with
10189 // array subscripts that aren't ICEs, and if the array subscripts
10190 // are ICEs, the value of the offsetof must be an integer constant.
10191 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010192 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010193 case Expr::UnaryExprOrTypeTraitExprClass: {
10194 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10195 if ((Exp->getKind() == UETT_SizeOf) &&
10196 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010197 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010198 return NoDiag();
10199 }
10200 case Expr::BinaryOperatorClass: {
10201 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10202 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010203 case BO_PtrMemD:
10204 case BO_PtrMemI:
10205 case BO_Assign:
10206 case BO_MulAssign:
10207 case BO_DivAssign:
10208 case BO_RemAssign:
10209 case BO_AddAssign:
10210 case BO_SubAssign:
10211 case BO_ShlAssign:
10212 case BO_ShrAssign:
10213 case BO_AndAssign:
10214 case BO_XorAssign:
10215 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010216 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10217 // constant expressions, but they can never be ICEs because an ICE cannot
10218 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010219 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010220
John McCalle3027922010-08-25 11:45:40 +000010221 case BO_Mul:
10222 case BO_Div:
10223 case BO_Rem:
10224 case BO_Add:
10225 case BO_Sub:
10226 case BO_Shl:
10227 case BO_Shr:
10228 case BO_LT:
10229 case BO_GT:
10230 case BO_LE:
10231 case BO_GE:
10232 case BO_EQ:
10233 case BO_NE:
10234 case BO_And:
10235 case BO_Xor:
10236 case BO_Or:
10237 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010238 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10239 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010240 if (Exp->getOpcode() == BO_Div ||
10241 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010242 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010243 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010244 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010245 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010246 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010247 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010248 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010249 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010250 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010251 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010252 }
10253 }
10254 }
John McCalle3027922010-08-25 11:45:40 +000010255 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010256 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010257 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10258 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010259 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10260 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010261 } else {
10262 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010263 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010264 }
10265 }
Richard Smith9e575da2012-12-28 13:25:52 +000010266 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010267 }
John McCalle3027922010-08-25 11:45:40 +000010268 case BO_LAnd:
10269 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010270 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10271 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010272 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010273 // Rare case where the RHS has a comma "side-effect"; we need
10274 // to actually check the condition to see whether the side
10275 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010276 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010277 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010278 return RHSResult;
10279 return NoDiag();
10280 }
10281
Richard Smith9e575da2012-12-28 13:25:52 +000010282 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010283 }
10284 }
10285 }
10286 case Expr::ImplicitCastExprClass:
10287 case Expr::CStyleCastExprClass:
10288 case Expr::CXXFunctionalCastExprClass:
10289 case Expr::CXXStaticCastExprClass:
10290 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010291 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010292 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010293 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010294 if (isa<ExplicitCastExpr>(E)) {
10295 if (const FloatingLiteral *FL
10296 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10297 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10298 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10299 APSInt IgnoredVal(DestWidth, !DestSigned);
10300 bool Ignored;
10301 // If the value does not fit in the destination type, the behavior is
10302 // undefined, so we are not required to treat it as a constant
10303 // expression.
10304 if (FL->getValue().convertToInteger(IgnoredVal,
10305 llvm::APFloat::rmTowardZero,
10306 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010307 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010308 return NoDiag();
10309 }
10310 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010311 switch (cast<CastExpr>(E)->getCastKind()) {
10312 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010313 case CK_AtomicToNonAtomic:
10314 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010315 case CK_NoOp:
10316 case CK_IntegralToBoolean:
10317 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010318 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010319 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010320 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010321 }
John McCall864e3962010-05-07 05:32:02 +000010322 }
John McCallc07a0c72011-02-17 10:25:35 +000010323 case Expr::BinaryConditionalOperatorClass: {
10324 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10325 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010326 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010327 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010328 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10329 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10330 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010331 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010332 return FalseResult;
10333 }
John McCall864e3962010-05-07 05:32:02 +000010334 case Expr::ConditionalOperatorClass: {
10335 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10336 // If the condition (ignoring parens) is a __builtin_constant_p call,
10337 // then only the true side is actually considered in an integer constant
10338 // expression, and it is fully evaluated. This is an important GNU
10339 // extension. See GCC PR38377 for discussion.
10340 if (const CallExpr *CallCE
10341 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010342 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010343 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010344 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010345 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010346 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010347
Richard Smithf57d8cb2011-12-09 22:58:01 +000010348 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10349 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010350
Richard Smith9e575da2012-12-28 13:25:52 +000010351 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010352 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010353 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010354 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010355 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010356 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010357 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010358 return NoDiag();
10359 // Rare case where the diagnostics depend on which side is evaluated
10360 // Note that if we get here, CondResult is 0, and at least one of
10361 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010362 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010363 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010364 return TrueResult;
10365 }
10366 case Expr::CXXDefaultArgExprClass:
10367 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010368 case Expr::CXXDefaultInitExprClass:
10369 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010370 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010371 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010372 }
10373 }
10374
David Blaikiee4d798f2012-01-20 21:50:17 +000010375 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010376}
10377
Richard Smithf57d8cb2011-12-09 22:58:01 +000010378/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010379static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010380 const Expr *E,
10381 llvm::APSInt *Value,
10382 SourceLocation *Loc) {
10383 if (!E->getType()->isIntegralOrEnumerationType()) {
10384 if (Loc) *Loc = E->getExprLoc();
10385 return false;
10386 }
10387
Richard Smith66e05fe2012-01-18 05:21:49 +000010388 APValue Result;
10389 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010390 return false;
10391
Richard Smith98710fc2014-11-13 23:03:19 +000010392 if (!Result.isInt()) {
10393 if (Loc) *Loc = E->getExprLoc();
10394 return false;
10395 }
10396
Richard Smith66e05fe2012-01-18 05:21:49 +000010397 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010398 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010399}
10400
Craig Toppera31a8822013-08-22 07:09:37 +000010401bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10402 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010403 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010404 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010405
Richard Smith9e575da2012-12-28 13:25:52 +000010406 ICEDiag D = CheckICE(this, Ctx);
10407 if (D.Kind != IK_ICE) {
10408 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010409 return false;
10410 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010411 return true;
10412}
10413
Craig Toppera31a8822013-08-22 07:09:37 +000010414bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010415 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010416 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010417 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10418
10419 if (!isIntegerConstantExpr(Ctx, Loc))
10420 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010421 // The only possible side-effects here are due to UB discovered in the
10422 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10423 // required to treat the expression as an ICE, so we produce the folded
10424 // value.
10425 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010426 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010427 return true;
10428}
Richard Smith66e05fe2012-01-18 05:21:49 +000010429
Craig Toppera31a8822013-08-22 07:09:37 +000010430bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010431 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010432}
10433
Craig Toppera31a8822013-08-22 07:09:37 +000010434bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010435 SourceLocation *Loc) const {
10436 // We support this checking in C++98 mode in order to diagnose compatibility
10437 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010438 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010439
Richard Smith98a0a492012-02-14 21:38:30 +000010440 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010441 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010442 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010443 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010444 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010445
10446 APValue Scratch;
10447 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10448
10449 if (!Diags.empty()) {
10450 IsConstExpr = false;
10451 if (Loc) *Loc = Diags[0].first;
10452 } else if (!IsConstExpr) {
10453 // FIXME: This shouldn't happen.
10454 if (Loc) *Loc = getExprLoc();
10455 }
10456
10457 return IsConstExpr;
10458}
Richard Smith253c2a32012-01-27 01:14:48 +000010459
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010460bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10461 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010462 ArrayRef<const Expr*> Args,
10463 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010464 Expr::EvalStatus Status;
10465 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10466
George Burgess IV177399e2017-01-09 04:12:14 +000010467 LValue ThisVal;
10468 const LValue *ThisPtr = nullptr;
10469 if (This) {
10470#ifndef NDEBUG
10471 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10472 assert(MD && "Don't provide `this` for non-methods.");
10473 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10474#endif
10475 if (EvaluateObjectArgument(Info, This, ThisVal))
10476 ThisPtr = &ThisVal;
10477 if (Info.EvalStatus.HasSideEffects)
10478 return false;
10479 }
10480
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010481 ArgVector ArgValues(Args.size());
10482 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10483 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010484 if ((*I)->isValueDependent() ||
10485 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010486 // If evaluation fails, throw away the argument entirely.
10487 ArgValues[I - Args.begin()] = APValue();
10488 if (Info.EvalStatus.HasSideEffects)
10489 return false;
10490 }
10491
10492 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010493 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010494 ArgValues.data());
10495 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10496}
10497
Richard Smith253c2a32012-01-27 01:14:48 +000010498bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010499 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010500 PartialDiagnosticAt> &Diags) {
10501 // FIXME: It would be useful to check constexpr function templates, but at the
10502 // moment the constant expression evaluator cannot cope with the non-rigorous
10503 // ASTs which we build for dependent expressions.
10504 if (FD->isDependentContext())
10505 return true;
10506
10507 Expr::EvalStatus Status;
10508 Status.Diag = &Diags;
10509
Richard Smith6d4c6582013-11-05 22:18:15 +000010510 EvalInfo Info(FD->getASTContext(), Status,
10511 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010512
10513 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010514 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010515
Richard Smith7525ff62013-05-09 07:14:00 +000010516 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010517 // is a temporary being used as the 'this' pointer.
10518 LValue This;
10519 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010520 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010521
Richard Smith253c2a32012-01-27 01:14:48 +000010522 ArrayRef<const Expr*> Args;
10523
Richard Smith2e312c82012-03-03 22:46:17 +000010524 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010525 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10526 // Evaluate the call as a constant initializer, to allow the construction
10527 // of objects of non-literal types.
10528 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010529 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10530 } else {
10531 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010532 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010533 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010534 }
Richard Smith253c2a32012-01-27 01:14:48 +000010535
10536 return Diags.empty();
10537}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010538
10539bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10540 const FunctionDecl *FD,
10541 SmallVectorImpl<
10542 PartialDiagnosticAt> &Diags) {
10543 Expr::EvalStatus Status;
10544 Status.Diag = &Diags;
10545
10546 EvalInfo Info(FD->getASTContext(), Status,
10547 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10548
10549 // Fabricate a call stack frame to give the arguments a plausible cover story.
10550 ArrayRef<const Expr*> Args;
10551 ArgVector ArgValues(0);
10552 bool Success = EvaluateArgs(Args, ArgValues, Info);
10553 (void)Success;
10554 assert(Success &&
10555 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010556 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010557
10558 APValue ResultScratch;
10559 Evaluate(ResultScratch, Info, E);
10560 return Diags.empty();
10561}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010562
10563bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10564 unsigned Type) const {
10565 if (!getType()->isPointerType())
10566 return false;
10567
10568 Expr::EvalStatus Status;
10569 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010570 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010571}