blob: f2e76288cb8b7005a4df9ea5f877045b67c4b505 [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 Smitha8105bc2012-01-06 16:39:00 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000354 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000355 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000356 if (Invalid) return;
George Burgess IVe3763372016-12-22 02:50:20 +0000357 if (isMostDerivedAnUnsizedArray()) {
358 // Can't verify -- trust that the user is doing the right thing (or if
359 // not, trust that the caller will catch the bad behavior).
360 Entries.back().ArrayIndex += N;
361 return;
362 }
George Burgess IVa51c4072015-10-16 01:49:01 +0000363 if (MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000365 Entries.back().ArrayIndex += N;
George Burgess IVe3763372016-12-22 02:50:20 +0000366 if (Entries.back().ArrayIndex > getMostDerivedArraySize()) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000367 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
368 setInvalid();
369 }
Richard Smith96e0c102011-11-04 02:25:55 +0000370 return;
371 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 if (IsOnePastTheEnd && N == (uint64_t)-1)
376 IsOnePastTheEnd = false;
377 else if (!IsOnePastTheEnd && N == 1)
378 IsOnePastTheEnd = true;
379 else if (N != 0) {
380 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000381 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000382 }
Richard Smith96e0c102011-11-04 02:25:55 +0000383 }
384 };
385
Richard Smith254a73d2011-10-28 22:34:42 +0000386 /// A stack frame in the constexpr call stack.
387 struct CallStackFrame {
388 EvalInfo &Info;
389
390 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000391 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000392
Richard Smithf6f003a2011-12-16 19:06:07 +0000393 /// Callee - The function which was called.
394 const FunctionDecl *Callee;
395
Richard Smithd62306a2011-11-10 06:34:14 +0000396 /// This - The binding for the this pointer in this call, if any.
397 const LValue *This;
398
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000399 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000400 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000401 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000402
Eli Friedman4830ec82012-06-25 21:21:08 +0000403 // Note that we intentionally use std::map here so that references to
404 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000405 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000406 typedef MapTy::const_iterator temp_iterator;
407 /// Temporaries - Temporary lvalues materialized within this stack frame.
408 MapTy Temporaries;
409
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000410 /// CallLoc - The location of the call expression for this call.
411 SourceLocation CallLoc;
412
413 /// Index - The call index of this call.
414 unsigned Index;
415
Richard Smithf6f003a2011-12-16 19:06:07 +0000416 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
417 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000418 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000420
421 APValue *getTemporary(const void *Key) {
422 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000423 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000424 }
425 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000426 };
427
Richard Smith852c9db2013-04-20 22:23:05 +0000428 /// Temporarily override 'this'.
429 class ThisOverrideRAII {
430 public:
431 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
432 : Frame(Frame), OldThis(Frame.This) {
433 if (Enable)
434 Frame.This = NewThis;
435 }
436 ~ThisOverrideRAII() {
437 Frame.This = OldThis;
438 }
439 private:
440 CallStackFrame &Frame;
441 const LValue *OldThis;
442 };
443
Richard Smith92b1ce02011-12-12 09:28:41 +0000444 /// A partial diagnostic which we might know in advance that we are not going
445 /// to emit.
446 class OptionalDiagnostic {
447 PartialDiagnostic *Diag;
448
449 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000450 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
451 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000452
453 template<typename T>
454 OptionalDiagnostic &operator<<(const T &v) {
455 if (Diag)
456 *Diag << v;
457 return *this;
458 }
Richard Smithfe800032012-01-31 04:08:20 +0000459
460 OptionalDiagnostic &operator<<(const APSInt &I) {
461 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000462 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000463 I.toString(Buffer);
464 *Diag << StringRef(Buffer.data(), Buffer.size());
465 }
466 return *this;
467 }
468
469 OptionalDiagnostic &operator<<(const APFloat &F) {
470 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000471 // FIXME: Force the precision of the source value down so we don't
472 // print digits which are usually useless (we don't really care here if
473 // we truncate a digit by accident in edge cases). Ideally,
474 // APFloat::toString would automatically print the shortest
475 // representation which rounds to the correct value, but it's a bit
476 // tricky to implement.
477 unsigned precision =
478 llvm::APFloat::semanticsPrecision(F.getSemantics());
479 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000480 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000481 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000482 *Diag << StringRef(Buffer.data(), Buffer.size());
483 }
484 return *this;
485 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000486 };
487
Richard Smith08d6a2c2013-07-24 07:11:57 +0000488 /// A cleanup, and a flag indicating whether it is lifetime-extended.
489 class Cleanup {
490 llvm::PointerIntPair<APValue*, 1, bool> Value;
491
492 public:
493 Cleanup(APValue *Val, bool IsLifetimeExtended)
494 : Value(Val, IsLifetimeExtended) {}
495
496 bool isLifetimeExtended() const { return Value.getInt(); }
497 void endLifetime() {
498 *Value.getPointer() = APValue();
499 }
500 };
501
Richard Smithb228a862012-02-15 02:18:13 +0000502 /// EvalInfo - This is a private struct used by the evaluator to capture
503 /// information about a subexpression as it is folded. It retains information
504 /// about the AST context, but also maintains information about the folded
505 /// expression.
506 ///
507 /// If an expression could be evaluated, it is still possible it is not a C
508 /// "integer constant expression" or constant expression. If not, this struct
509 /// captures information about how and why not.
510 ///
511 /// One bit of information passed *into* the request for constant folding
512 /// indicates whether the subexpression is "evaluated" or not according to C
513 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
514 /// evaluate the expression regardless of what the RHS is, but C only allows
515 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000516 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000517 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000518
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000519 /// EvalStatus - Contains information about the evaluation.
520 Expr::EvalStatus &EvalStatus;
521
522 /// CurrentCall - The top of the constexpr call stack.
523 CallStackFrame *CurrentCall;
524
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000525 /// CallStackDepth - The number of calls in the call stack right now.
526 unsigned CallStackDepth;
527
Richard Smithb228a862012-02-15 02:18:13 +0000528 /// NextCallIndex - The next call index to assign.
529 unsigned NextCallIndex;
530
Richard Smitha3d3bd22013-05-08 02:12:03 +0000531 /// StepsLeft - The remaining number of evaluation steps we're permitted
532 /// to perform. This is essentially a limit for the number of statements
533 /// we will evaluate.
534 unsigned StepsLeft;
535
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000536 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000537 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000538 CallStackFrame BottomFrame;
539
Richard Smith08d6a2c2013-07-24 07:11:57 +0000540 /// A stack of values whose lifetimes end at the end of some surrounding
541 /// evaluation frame.
542 llvm::SmallVector<Cleanup, 16> CleanupStack;
543
Richard Smithd62306a2011-11-10 06:34:14 +0000544 /// EvaluatingDecl - This is the declaration whose initializer is being
545 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000546 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000547
548 /// EvaluatingDeclValue - This is the value being constructed for the
549 /// declaration whose initializer is being evaluated, if any.
550 APValue *EvaluatingDeclValue;
551
Richard Smith410306b2016-12-12 02:53:20 +0000552 /// The current array initialization index, if we're performing array
553 /// initialization.
554 uint64_t ArrayInitIndex = -1;
555
Richard Smith357362d2011-12-13 06:39:58 +0000556 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
557 /// notes attached to it will also be stored, otherwise they will not be.
558 bool HasActiveDiagnostic;
559
Richard Smith0c6124b2015-12-03 01:36:22 +0000560 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
561 /// fold (not just why it's not strictly a constant expression)?
562 bool HasFoldFailureDiagnostic;
563
George Burgess IV8c892b52016-05-25 22:31:54 +0000564 /// \brief Whether or not we're currently speculatively evaluating.
565 bool IsSpeculativelyEvaluating;
566
Richard Smith6d4c6582013-11-05 22:18:15 +0000567 enum EvaluationMode {
568 /// Evaluate as a constant expression. Stop if we find that the expression
569 /// is not a constant expression.
570 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000571
Richard Smith6d4c6582013-11-05 22:18:15 +0000572 /// Evaluate as a potential constant expression. Keep going if we hit a
573 /// construct that we can't evaluate yet (because we don't yet know the
574 /// value of something) but stop if we hit something that could never be
575 /// a constant expression.
576 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000577
Richard Smith6d4c6582013-11-05 22:18:15 +0000578 /// Fold the expression to a constant. Stop if we hit a side-effect that
579 /// we can't model.
580 EM_ConstantFold,
581
582 /// Evaluate the expression looking for integer overflow and similar
583 /// issues. Don't worry about side-effects, and try to visit all
584 /// subexpressions.
585 EM_EvaluateForOverflow,
586
587 /// Evaluate in any way we know how. Don't worry about side-effects that
588 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000589 EM_IgnoreSideEffects,
590
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression. Some expressions can be retried in the
593 /// optimizer if we don't constant fold them here, but in an unevaluated
594 /// context we try to fold them immediately since the optimizer never
595 /// gets a chance to look at it.
596 EM_ConstantExpressionUnevaluated,
597
598 /// Evaluate as a potential constant expression. Keep going if we hit a
599 /// construct that we can't evaluate yet (because we don't yet know the
600 /// value of something) but stop if we hit something that could never be
601 /// a constant expression. Some expressions can be retried in the
602 /// optimizer if we don't constant fold them here, but in an unevaluated
603 /// context we try to fold them immediately since the optimizer never
604 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000605 EM_PotentialConstantExpressionUnevaluated,
606
George Burgess IVe3763372016-12-22 02:50:20 +0000607 /// Evaluate as a constant expression. Continue evaluating if either:
608 /// - We find a MemberExpr with a base that can't be evaluated.
609 /// - We find a variable initialized with a call to a function that has
610 /// the alloc_size attribute on it.
611 /// In either case, the LValue returned shall have an invalid base; in the
612 /// former, the base will be the invalid MemberExpr, in the latter, the
613 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
614 /// said CallExpr.
615 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000616 } EvalMode;
617
618 /// Are we checking whether the expression is a potential constant
619 /// expression?
620 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000621 return EvalMode == EM_PotentialConstantExpression ||
622 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000623 }
624
625 /// Are we checking an expression for overflow?
626 // FIXME: We should check for any kind of undefined or suspicious behavior
627 // in such constructs, not just overflow.
628 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
629
630 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000631 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000632 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000633 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000634 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
635 EvaluatingDecl((const ValueDecl *)nullptr),
636 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000637 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
638 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000639
Richard Smith7525ff62013-05-09 07:14:00 +0000640 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
641 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000642 EvaluatingDeclValue = &Value;
643 }
644
David Blaikiebbafb8a2012-03-11 07:00:24 +0000645 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000646
Richard Smith357362d2011-12-13 06:39:58 +0000647 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000648 // Don't perform any constexpr calls (other than the call we're checking)
649 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000650 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000651 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000652 if (NextCallIndex == 0) {
653 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000654 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000655 return false;
656 }
Richard Smith357362d2011-12-13 06:39:58 +0000657 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
658 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000659 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000660 << getLangOpts().ConstexprCallDepth;
661 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000662 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000663
Richard Smithb228a862012-02-15 02:18:13 +0000664 CallStackFrame *getCallFrame(unsigned CallIndex) {
665 assert(CallIndex && "no call index in getCallFrame");
666 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
667 // be null in this loop.
668 CallStackFrame *Frame = CurrentCall;
669 while (Frame->Index > CallIndex)
670 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000671 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000672 }
673
Richard Smitha3d3bd22013-05-08 02:12:03 +0000674 bool nextStep(const Stmt *S) {
675 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000676 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000677 return false;
678 }
679 --StepsLeft;
680 return true;
681 }
682
Richard Smith357362d2011-12-13 06:39:58 +0000683 private:
684 /// Add a diagnostic to the diagnostics list.
685 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
686 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
687 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
688 return EvalStatus.Diag->back().second;
689 }
690
Richard Smithf6f003a2011-12-16 19:06:07 +0000691 /// Add notes containing a call stack to the current point of evaluation.
692 void addCallStack(unsigned Limit);
693
Faisal Valie690b7a2016-07-02 22:34:24 +0000694 private:
695 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
696 unsigned ExtraNotes, bool IsCCEDiag) {
697
Richard Smith92b1ce02011-12-12 09:28:41 +0000698 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 // If we have a prior diagnostic, it will be noting that the expression
700 // isn't a constant expression. This diagnostic is more important,
701 // unless we require this evaluation to produce a constant expression.
702 //
703 // FIXME: We might want to show both diagnostics to the user in
704 // EM_ConstantFold mode.
705 if (!EvalStatus.Diag->empty()) {
706 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000707 case EM_ConstantFold:
708 case EM_IgnoreSideEffects:
709 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000710 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000711 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000712 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 case EM_ConstantExpression:
714 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000715 case EM_ConstantExpressionUnevaluated:
716 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000717 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 HasActiveDiagnostic = false;
719 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 }
721 }
722
Richard Smithf6f003a2011-12-16 19:06:07 +0000723 unsigned CallStackNotes = CallStackDepth - 1;
724 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
725 if (Limit)
726 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000728 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000729
Richard Smith357362d2011-12-13 06:39:58 +0000730 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000731 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000732 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000733 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
734 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000736 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000737 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000738 }
Richard Smith357362d2011-12-13 06:39:58 +0000739 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000740 return OptionalDiagnostic();
741 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000742 public:
743 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
744 OptionalDiagnostic
745 FFDiag(SourceLocation Loc,
746 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
747 unsigned ExtraNotes = 0) {
748 return Diag(Loc, DiagId, ExtraNotes, false);
749 }
750
751 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000753 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000754 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000755 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000756 HasActiveDiagnostic = false;
757 return OptionalDiagnostic();
758 }
759
Richard Smith92b1ce02011-12-12 09:28:41 +0000760 /// Diagnose that the evaluation does not produce a C++11 core constant
761 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 ///
763 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
764 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000766 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000767 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000768 // Don't override a previous diagnostic. Don't bother collecting
769 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000770 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000771 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000772 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000773 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000774 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000775 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000776 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
777 = diag::note_invalid_subexpr_in_const_expr,
778 unsigned ExtraNotes = 0) {
779 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
780 }
Richard Smith357362d2011-12-13 06:39:58 +0000781 /// Add a note to a prior diagnostic.
782 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
783 if (!HasActiveDiagnostic)
784 return OptionalDiagnostic();
785 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000786 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000787
788 /// Add a stack of notes to a prior diagnostic.
789 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
790 if (HasActiveDiagnostic) {
791 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
792 Diags.begin(), Diags.end());
793 }
794 }
Richard Smith253c2a32012-01-27 01:14:48 +0000795
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 /// Should we continue evaluation after encountering a side-effect that we
797 /// couldn't model?
798 bool keepEvaluatingAfterSideEffect() {
799 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000800 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000801 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 case EM_EvaluateForOverflow:
803 case EM_IgnoreSideEffects:
804 return true;
805
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000807 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000809 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 return false;
811 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000812 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 }
814
815 /// Note that we have had a side-effect, and determine whether we should
816 /// keep evaluating.
817 bool noteSideEffect() {
818 EvalStatus.HasSideEffects = true;
819 return keepEvaluatingAfterSideEffect();
820 }
821
Richard Smithce8eca52015-12-08 03:21:47 +0000822 /// Should we continue evaluation after encountering undefined behavior?
823 bool keepEvaluatingAfterUndefinedBehavior() {
824 switch (EvalMode) {
825 case EM_EvaluateForOverflow:
826 case EM_IgnoreSideEffects:
827 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000828 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000829 return true;
830
831 case EM_PotentialConstantExpression:
832 case EM_PotentialConstantExpressionUnevaluated:
833 case EM_ConstantExpression:
834 case EM_ConstantExpressionUnevaluated:
835 return false;
836 }
837 llvm_unreachable("Missed EvalMode case");
838 }
839
840 /// Note that we hit something that was technically undefined behavior, but
841 /// that we can evaluate past it (such as signed overflow or floating-point
842 /// division by zero.)
843 bool noteUndefinedBehavior() {
844 EvalStatus.HasUndefinedBehavior = true;
845 return keepEvaluatingAfterUndefinedBehavior();
846 }
847
Richard Smith253c2a32012-01-27 01:14:48 +0000848 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000849 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000850 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000851 if (!StepsLeft)
852 return false;
853
854 switch (EvalMode) {
855 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000856 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000857 case EM_EvaluateForOverflow:
858 return true;
859
860 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000861 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000862 case EM_ConstantFold:
863 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000864 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000865 return false;
866 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000867 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000868 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000869
George Burgess IV8c892b52016-05-25 22:31:54 +0000870 /// Notes that we failed to evaluate an expression that other expressions
871 /// directly depend on, and determine if we should keep evaluating. This
872 /// should only be called if we actually intend to keep evaluating.
873 ///
874 /// Call noteSideEffect() instead if we may be able to ignore the value that
875 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
876 ///
877 /// (Foo(), 1) // use noteSideEffect
878 /// (Foo() || true) // use noteSideEffect
879 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000880 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000881 // Failure when evaluating some expression often means there is some
882 // subexpression whose evaluation was skipped. Therefore, (because we
883 // don't track whether we skipped an expression when unwinding after an
884 // evaluation failure) every evaluation failure that bubbles up from a
885 // subexpression implies that a side-effect has potentially happened. We
886 // skip setting the HasSideEffects flag to true until we decide to
887 // continue evaluating after that point, which happens here.
888 bool KeepGoing = keepEvaluatingAfterFailure();
889 EvalStatus.HasSideEffects |= KeepGoing;
890 return KeepGoing;
891 }
892
George Burgess IV3a03fab2015-09-04 21:28:13 +0000893 bool allowInvalidBaseExpr() const {
George Burgess IVe3763372016-12-22 02:50:20 +0000894 return EvalMode == EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000895 }
Richard Smith410306b2016-12-12 02:53:20 +0000896
897 class ArrayInitLoopIndex {
898 EvalInfo &Info;
899 uint64_t OuterIndex;
900
901 public:
902 ArrayInitLoopIndex(EvalInfo &Info)
903 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
904 Info.ArrayInitIndex = 0;
905 }
906 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
907
908 operator uint64_t&() { return Info.ArrayInitIndex; }
909 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000910 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000911
912 /// Object used to treat all foldable expressions as constant expressions.
913 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000914 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000915 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000916 bool HadNoPriorDiags;
917 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000918
Richard Smith6d4c6582013-11-05 22:18:15 +0000919 explicit FoldConstant(EvalInfo &Info, bool Enabled)
920 : Info(Info),
921 Enabled(Enabled),
922 HadNoPriorDiags(Info.EvalStatus.Diag &&
923 Info.EvalStatus.Diag->empty() &&
924 !Info.EvalStatus.HasSideEffects),
925 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000926 if (Enabled &&
927 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
928 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000930 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 void keepDiagnostics() { Enabled = false; }
932 ~FoldConstant() {
933 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000934 !Info.EvalStatus.HasSideEffects)
935 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000936 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000937 }
938 };
Richard Smith17100ba2012-02-16 02:46:34 +0000939
George Burgess IV3a03fab2015-09-04 21:28:13 +0000940 /// RAII object used to treat the current evaluation as the correct pointer
941 /// offset fold for the current EvalMode
942 struct FoldOffsetRAII {
943 EvalInfo &Info;
944 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000945 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000946 : Info(Info), OldMode(Info.EvalMode) {
947 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000948 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000949 }
950
951 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
952 };
953
George Burgess IV8c892b52016-05-25 22:31:54 +0000954 /// RAII object used to optionally suppress diagnostics and side-effects from
955 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000956 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000957 /// Pair of EvalInfo, and a bit that stores whether or not we were
958 /// speculatively evaluating when we created this RAII.
959 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000960 Expr::EvalStatus Old;
961
George Burgess IV8c892b52016-05-25 22:31:54 +0000962 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
963 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
964 Old = Other.Old;
965 Other.InfoAndOldSpecEval.setPointer(nullptr);
966 }
967
968 void maybeRestoreState() {
969 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
970 if (!Info)
971 return;
972
973 Info->EvalStatus = Old;
974 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
975 }
976
Richard Smith17100ba2012-02-16 02:46:34 +0000977 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 SpeculativeEvaluationRAII() = default;
979
980 SpeculativeEvaluationRAII(
981 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
982 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
983 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000984 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000985 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000986 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000987
988 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
989 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
990 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000991 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000992
993 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
994 maybeRestoreState();
995 moveFromAndCancel(std::move(Other));
996 return *this;
997 }
998
999 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001000 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001001
1002 /// RAII object wrapping a full-expression or block scope, and handling
1003 /// the ending of the lifetime of temporaries created within it.
1004 template<bool IsFullExpression>
1005 class ScopeRAII {
1006 EvalInfo &Info;
1007 unsigned OldStackSize;
1008 public:
1009 ScopeRAII(EvalInfo &Info)
1010 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1011 ~ScopeRAII() {
1012 // Body moved to a static method to encourage the compiler to inline away
1013 // instances of this class.
1014 cleanup(Info, OldStackSize);
1015 }
1016 private:
1017 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1018 unsigned NewEnd = OldStackSize;
1019 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1020 I != N; ++I) {
1021 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1022 // Full-expression cleanup of a lifetime-extended temporary: nothing
1023 // to do, just move this cleanup to the right place in the stack.
1024 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1025 ++NewEnd;
1026 } else {
1027 // End the lifetime of the object.
1028 Info.CleanupStack[I].endLifetime();
1029 }
1030 }
1031 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1032 Info.CleanupStack.end());
1033 }
1034 };
1035 typedef ScopeRAII<false> BlockScopeRAII;
1036 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001037}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001038
Richard Smitha8105bc2012-01-06 16:39:00 +00001039bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1040 CheckSubobjectKind CSK) {
1041 if (Invalid)
1042 return false;
1043 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001044 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001045 << CSK;
1046 setInvalid();
1047 return false;
1048 }
1049 return true;
1050}
1051
1052void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1053 const Expr *E, uint64_t N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001054 // If we're complaining, we must be able to statically determine the size of
1055 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001056 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001057 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001058 << static_cast<int>(N) << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001059 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001060 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001061 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001062 << static_cast<int>(N) << /*non-array*/ 1;
1063 setInvalid();
1064}
1065
Richard Smithf6f003a2011-12-16 19:06:07 +00001066CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1067 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001068 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001069 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1070 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001071 Info.CurrentCall = this;
1072 ++Info.CallStackDepth;
1073}
1074
1075CallStackFrame::~CallStackFrame() {
1076 assert(Info.CurrentCall == this && "calls retired out of order");
1077 --Info.CallStackDepth;
1078 Info.CurrentCall = Caller;
1079}
1080
Richard Smith08d6a2c2013-07-24 07:11:57 +00001081APValue &CallStackFrame::createTemporary(const void *Key,
1082 bool IsLifetimeExtended) {
1083 APValue &Result = Temporaries[Key];
1084 assert(Result.isUninit() && "temporary created multiple times");
1085 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1086 return Result;
1087}
1088
Richard Smith84401042013-06-03 05:03:02 +00001089static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001090
1091void EvalInfo::addCallStack(unsigned Limit) {
1092 // Determine which calls to skip, if any.
1093 unsigned ActiveCalls = CallStackDepth - 1;
1094 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1095 if (Limit && Limit < ActiveCalls) {
1096 SkipStart = Limit / 2 + Limit % 2;
1097 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001098 }
1099
Richard Smithf6f003a2011-12-16 19:06:07 +00001100 // Walk the call stack and add the diagnostics.
1101 unsigned CallIdx = 0;
1102 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1103 Frame = Frame->Caller, ++CallIdx) {
1104 // Skip this call?
1105 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1106 if (CallIdx == SkipStart) {
1107 // Note that we're skipping calls.
1108 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1109 << unsigned(ActiveCalls - Limit);
1110 }
1111 continue;
1112 }
1113
Richard Smith5179eb72016-06-28 19:03:57 +00001114 // Use a different note for an inheriting constructor, because from the
1115 // user's perspective it's not really a function at all.
1116 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1117 if (CD->isInheritingConstructor()) {
1118 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1119 << CD->getParent();
1120 continue;
1121 }
1122 }
1123
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001124 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001125 llvm::raw_svector_ostream Out(Buffer);
1126 describeCall(Frame, Out);
1127 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1128 }
1129}
1130
1131namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001132 struct ComplexValue {
1133 private:
1134 bool IsInt;
1135
1136 public:
1137 APSInt IntReal, IntImag;
1138 APFloat FloatReal, FloatImag;
1139
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001140 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001141
1142 void makeComplexFloat() { IsInt = false; }
1143 bool isComplexFloat() const { return !IsInt; }
1144 APFloat &getComplexFloatReal() { return FloatReal; }
1145 APFloat &getComplexFloatImag() { return FloatImag; }
1146
1147 void makeComplexInt() { IsInt = true; }
1148 bool isComplexInt() const { return IsInt; }
1149 APSInt &getComplexIntReal() { return IntReal; }
1150 APSInt &getComplexIntImag() { return IntImag; }
1151
Richard Smith2e312c82012-03-03 22:46:17 +00001152 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001153 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001154 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001155 else
Richard Smith2e312c82012-03-03 22:46:17 +00001156 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001157 }
Richard Smith2e312c82012-03-03 22:46:17 +00001158 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001159 assert(v.isComplexFloat() || v.isComplexInt());
1160 if (v.isComplexFloat()) {
1161 makeComplexFloat();
1162 FloatReal = v.getComplexFloatReal();
1163 FloatImag = v.getComplexFloatImag();
1164 } else {
1165 makeComplexInt();
1166 IntReal = v.getComplexIntReal();
1167 IntImag = v.getComplexIntImag();
1168 }
1169 }
John McCall93d91dc2010-05-07 17:22:02 +00001170 };
John McCall45d55e42010-05-07 21:00:08 +00001171
1172 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001173 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001174 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001175 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001176 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001177 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001178 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001179
Richard Smithce40ad62011-11-12 22:28:03 +00001180 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001181 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001182 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001183 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001184 SubobjectDesignator &getLValueDesignator() { return Designator; }
1185 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001186 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001187
Richard Smith2e312c82012-03-03 22:46:17 +00001188 void moveInto(APValue &V) const {
1189 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001190 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1191 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001192 else {
1193 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1194 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1195 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001196 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001197 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001198 }
John McCall45d55e42010-05-07 21:00:08 +00001199 }
Richard Smith2e312c82012-03-03 22:46:17 +00001200 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001201 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001202 Base = V.getLValueBase();
1203 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001204 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001205 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001206 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001207 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001208 }
1209
Yaxun Liu402804b2016-12-15 08:09:08 +00001210 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1211 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001212#ifndef NDEBUG
1213 // We only allow a few types of invalid bases. Enforce that here.
1214 if (BInvalid) {
1215 const auto *E = B.get<const Expr *>();
1216 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1217 "Unexpected type of invalid base");
1218 }
1219#endif
1220
Richard Smithce40ad62011-11-12 22:28:03 +00001221 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001222 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001223 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001224 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001225 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001226 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001227 }
1228
George Burgess IV3a03fab2015-09-04 21:28:13 +00001229 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1230 set(B, I, true);
1231 }
1232
Richard Smitha8105bc2012-01-06 16:39:00 +00001233 // Check that this LValue is not based on a null pointer. If it is, produce
1234 // a diagnostic and mark the designator as invalid.
1235 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1236 CheckSubobjectKind CSK) {
1237 if (Designator.Invalid)
1238 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001239 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001240 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001241 << CSK;
1242 Designator.setInvalid();
1243 return false;
1244 }
1245 return true;
1246 }
1247
1248 // Check this LValue refers to an object. If not, set the designator to be
1249 // invalid and emit a diagnostic.
1250 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001251 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001252 Designator.checkSubobject(Info, E, CSK);
1253 }
1254
1255 void addDecl(EvalInfo &Info, const Expr *E,
1256 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001257 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1258 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001259 }
George Burgess IVe3763372016-12-22 02:50:20 +00001260 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1261 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1262 assert(isBaseAnAllocSizeCall(Base) &&
1263 "Only alloc_size bases can have unsized arrays");
1264 Designator.FirstEntryIsAnUnsizedArray = true;
1265 Designator.addUnsizedArrayUnchecked(ElemTy);
1266 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001267 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001268 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1269 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001270 }
Richard Smith66c96992012-02-18 22:04:06 +00001271 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001272 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1273 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001274 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001275 void clearIsNullPointer() {
1276 IsNullPtr = false;
1277 }
1278 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1279 CharUnits ElementSize) {
1280 // Compute the new offset in the appropriate width.
1281 Offset += Index * ElementSize;
1282 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1283 Designator.adjustIndex(Info, E, Index);
1284 if (Index)
1285 clearIsNullPointer();
1286 }
1287 void adjustOffset(CharUnits N) {
1288 Offset += N;
1289 if (N.getQuantity())
1290 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001291 }
John McCall45d55e42010-05-07 21:00:08 +00001292 };
Richard Smith027bf112011-11-17 22:56:20 +00001293
1294 struct MemberPtr {
1295 MemberPtr() {}
1296 explicit MemberPtr(const ValueDecl *Decl) :
1297 DeclAndIsDerivedMember(Decl, false), Path() {}
1298
1299 /// The member or (direct or indirect) field referred to by this member
1300 /// pointer, or 0 if this is a null member pointer.
1301 const ValueDecl *getDecl() const {
1302 return DeclAndIsDerivedMember.getPointer();
1303 }
1304 /// Is this actually a member of some type derived from the relevant class?
1305 bool isDerivedMember() const {
1306 return DeclAndIsDerivedMember.getInt();
1307 }
1308 /// Get the class which the declaration actually lives in.
1309 const CXXRecordDecl *getContainingRecord() const {
1310 return cast<CXXRecordDecl>(
1311 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1312 }
1313
Richard Smith2e312c82012-03-03 22:46:17 +00001314 void moveInto(APValue &V) const {
1315 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001316 }
Richard Smith2e312c82012-03-03 22:46:17 +00001317 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001318 assert(V.isMemberPointer());
1319 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1320 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1321 Path.clear();
1322 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1323 Path.insert(Path.end(), P.begin(), P.end());
1324 }
1325
1326 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1327 /// whether the member is a member of some class derived from the class type
1328 /// of the member pointer.
1329 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1330 /// Path - The path of base/derived classes from the member declaration's
1331 /// class (exclusive) to the class type of the member pointer (inclusive).
1332 SmallVector<const CXXRecordDecl*, 4> Path;
1333
1334 /// Perform a cast towards the class of the Decl (either up or down the
1335 /// hierarchy).
1336 bool castBack(const CXXRecordDecl *Class) {
1337 assert(!Path.empty());
1338 const CXXRecordDecl *Expected;
1339 if (Path.size() >= 2)
1340 Expected = Path[Path.size() - 2];
1341 else
1342 Expected = getContainingRecord();
1343 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1344 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1345 // if B does not contain the original member and is not a base or
1346 // derived class of the class containing the original member, the result
1347 // of the cast is undefined.
1348 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1349 // (D::*). We consider that to be a language defect.
1350 return false;
1351 }
1352 Path.pop_back();
1353 return true;
1354 }
1355 /// Perform a base-to-derived member pointer cast.
1356 bool castToDerived(const CXXRecordDecl *Derived) {
1357 if (!getDecl())
1358 return true;
1359 if (!isDerivedMember()) {
1360 Path.push_back(Derived);
1361 return true;
1362 }
1363 if (!castBack(Derived))
1364 return false;
1365 if (Path.empty())
1366 DeclAndIsDerivedMember.setInt(false);
1367 return true;
1368 }
1369 /// Perform a derived-to-base member pointer cast.
1370 bool castToBase(const CXXRecordDecl *Base) {
1371 if (!getDecl())
1372 return true;
1373 if (Path.empty())
1374 DeclAndIsDerivedMember.setInt(true);
1375 if (isDerivedMember()) {
1376 Path.push_back(Base);
1377 return true;
1378 }
1379 return castBack(Base);
1380 }
1381 };
Richard Smith357362d2011-12-13 06:39:58 +00001382
Richard Smith7bb00672012-02-01 01:42:44 +00001383 /// Compare two member pointers, which are assumed to be of the same type.
1384 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1385 if (!LHS.getDecl() || !RHS.getDecl())
1386 return !LHS.getDecl() && !RHS.getDecl();
1387 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1388 return false;
1389 return LHS.Path == RHS.Path;
1390 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001392
Richard Smith2e312c82012-03-03 22:46:17 +00001393static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001394static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1395 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001396 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001397static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1398static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001399static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1400 EvalInfo &Info);
1401static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001402static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001403static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001404 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001405static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001406static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001407static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001408static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001409
1410//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001411// Misc utilities
1412//===----------------------------------------------------------------------===//
1413
Richard Smith84401042013-06-03 05:03:02 +00001414/// Produce a string describing the given constexpr call.
1415static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1416 unsigned ArgIndex = 0;
1417 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1418 !isa<CXXConstructorDecl>(Frame->Callee) &&
1419 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1420
1421 if (!IsMemberCall)
1422 Out << *Frame->Callee << '(';
1423
1424 if (Frame->This && IsMemberCall) {
1425 APValue Val;
1426 Frame->This->moveInto(Val);
1427 Val.printPretty(Out, Frame->Info.Ctx,
1428 Frame->This->Designator.MostDerivedType);
1429 // FIXME: Add parens around Val if needed.
1430 Out << "->" << *Frame->Callee << '(';
1431 IsMemberCall = false;
1432 }
1433
1434 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1435 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1436 if (ArgIndex > (unsigned)IsMemberCall)
1437 Out << ", ";
1438
1439 const ParmVarDecl *Param = *I;
1440 const APValue &Arg = Frame->Arguments[ArgIndex];
1441 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1442
1443 if (ArgIndex == 0 && IsMemberCall)
1444 Out << "->" << *Frame->Callee << '(';
1445 }
1446
1447 Out << ')';
1448}
1449
Richard Smithd9f663b2013-04-22 15:31:51 +00001450/// Evaluate an expression to see if it had side-effects, and discard its
1451/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001452/// \return \c true if the caller should keep evaluating.
1453static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001454 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001455 if (!Evaluate(Scratch, Info, E))
1456 // We don't need the value, but we might have skipped a side effect here.
1457 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001458 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001459}
1460
Richard Smith861b5b52013-05-07 23:34:45 +00001461/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1462/// return its existing value.
Richard Smith642a2362017-01-30 23:30:26 +00001463static bool getExtValue(EvalInfo &Info, const Expr *E, const APSInt &Value,
1464 int64_t &Result) {
1465 if (Value.isSigned() ? Value.getMinSignedBits() > 64
1466 : Value.getActiveBits() > 64) {
1467 Info.FFDiag(E);
1468 return false;
1469 }
1470
1471 Result = Value.isSigned() ? Value.getSExtValue()
1472 : static_cast<int64_t>(Value.getZExtValue());
1473 return true;
Richard Smith861b5b52013-05-07 23:34:45 +00001474}
1475
Richard Smithd62306a2011-11-10 06:34:14 +00001476/// Should this call expression be treated as a string literal?
1477static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001478 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001479 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1480 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1481}
1482
Richard Smithce40ad62011-11-12 22:28:03 +00001483static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001484 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1485 // constant expression of pointer type that evaluates to...
1486
1487 // ... a null pointer value, or a prvalue core constant expression of type
1488 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001489 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001490
Richard Smithce40ad62011-11-12 22:28:03 +00001491 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1492 // ... the address of an object with static storage duration,
1493 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1494 return VD->hasGlobalStorage();
1495 // ... the address of a function,
1496 return isa<FunctionDecl>(D);
1497 }
1498
1499 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001500 switch (E->getStmtClass()) {
1501 default:
1502 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001503 case Expr::CompoundLiteralExprClass: {
1504 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1505 return CLE->isFileScope() && CLE->isLValue();
1506 }
Richard Smithe6c01442013-06-05 00:46:14 +00001507 case Expr::MaterializeTemporaryExprClass:
1508 // A materialized temporary might have been lifetime-extended to static
1509 // storage duration.
1510 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001511 // A string literal has static storage duration.
1512 case Expr::StringLiteralClass:
1513 case Expr::PredefinedExprClass:
1514 case Expr::ObjCStringLiteralClass:
1515 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001516 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001517 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001518 return true;
1519 case Expr::CallExprClass:
1520 return IsStringLiteralCall(cast<CallExpr>(E));
1521 // For GCC compatibility, &&label has static storage duration.
1522 case Expr::AddrLabelExprClass:
1523 return true;
1524 // A Block literal expression may be used as the initialization value for
1525 // Block variables at global or local static scope.
1526 case Expr::BlockExprClass:
1527 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001528 case Expr::ImplicitValueInitExprClass:
1529 // FIXME:
1530 // We can never form an lvalue with an implicit value initialization as its
1531 // base through expression evaluation, so these only appear in one case: the
1532 // implicit variable declaration we invent when checking whether a constexpr
1533 // constructor can produce a constant expression. We must assume that such
1534 // an expression might be a global lvalue.
1535 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001536 }
John McCall95007602010-05-10 23:27:23 +00001537}
1538
Richard Smithb228a862012-02-15 02:18:13 +00001539static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1540 assert(Base && "no location for a null lvalue");
1541 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1542 if (VD)
1543 Info.Note(VD->getLocation(), diag::note_declared_at);
1544 else
Ted Kremenek28831752012-08-23 20:46:57 +00001545 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001546 diag::note_constexpr_temporary_here);
1547}
1548
Richard Smith80815602011-11-07 05:07:52 +00001549/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001550/// value for an address or reference constant expression. Return true if we
1551/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001552static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1553 QualType Type, const LValue &LVal) {
1554 bool IsReferenceType = Type->isReferenceType();
1555
Richard Smith357362d2011-12-13 06:39:58 +00001556 APValue::LValueBase Base = LVal.getLValueBase();
1557 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1558
Richard Smith0dea49e2012-02-18 04:58:18 +00001559 // Check that the object is a global. Note that the fake 'this' object we
1560 // manufacture when checking potential constant expressions is conservatively
1561 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001562 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001563 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001564 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001565 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001566 << IsReferenceType << !Designator.Entries.empty()
1567 << !!VD << VD;
1568 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001569 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001570 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001571 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001572 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001573 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001574 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001575 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001576 LVal.getLValueCallIndex() == 0) &&
1577 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001578
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001579 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1580 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001581 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001582 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001583 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001584
Hans Wennborg82dd8772014-06-25 22:19:48 +00001585 // A dllimport variable never acts like a constant.
1586 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001587 return false;
1588 }
1589 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1590 // __declspec(dllimport) must be handled very carefully:
1591 // We must never initialize an expression with the thunk in C++.
1592 // Doing otherwise would allow the same id-expression to yield
1593 // different addresses for the same function in different translation
1594 // units. However, this means that we must dynamically initialize the
1595 // expression with the contents of the import address table at runtime.
1596 //
1597 // The C language has no notion of ODR; furthermore, it has no notion of
1598 // dynamic initialization. This means that we are permitted to
1599 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001600 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001601 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001602 }
1603 }
1604
Richard Smitha8105bc2012-01-06 16:39:00 +00001605 // Allow address constant expressions to be past-the-end pointers. This is
1606 // an extension: the standard requires them to point to an object.
1607 if (!IsReferenceType)
1608 return true;
1609
1610 // A reference constant expression must refer to an object.
1611 if (!Base) {
1612 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001613 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001614 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001615 }
1616
Richard Smith357362d2011-12-13 06:39:58 +00001617 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001618 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001619 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001620 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001621 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001622 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001623 }
1624
Richard Smith80815602011-11-07 05:07:52 +00001625 return true;
1626}
1627
Richard Smithfddd3842011-12-30 21:15:51 +00001628/// Check that this core constant expression is of literal type, and if not,
1629/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001630static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001631 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001632 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001633 return true;
1634
Richard Smith7525ff62013-05-09 07:14:00 +00001635 // C++1y: A constant initializer for an object o [...] may also invoke
1636 // constexpr constructors for o and its subobjects even if those objects
1637 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001638 //
1639 // C++11 missed this detail for aggregates, so classes like this:
1640 // struct foo_t { union { int i; volatile int j; } u; };
1641 // are not (obviously) initializable like so:
1642 // __attribute__((__require_constant_initialization__))
1643 // static const foo_t x = {{0}};
1644 // because "i" is a subobject with non-literal initialization (due to the
1645 // volatile member of the union). See:
1646 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1647 // Therefore, we use the C++1y behavior.
1648 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001649 return true;
1650
Richard Smithfddd3842011-12-30 21:15:51 +00001651 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001652 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001653 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001654 << E->getType();
1655 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001656 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001657 return false;
1658}
1659
Richard Smith0b0a0b62011-10-29 20:57:55 +00001660/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001661/// constant expression. If not, report an appropriate diagnostic. Does not
1662/// check that the expression is of literal type.
1663static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1664 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001665 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001666 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001667 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001668 return false;
1669 }
1670
Richard Smith77be48a2014-07-31 06:31:19 +00001671 // We allow _Atomic(T) to be initialized from anything that T can be
1672 // initialized from.
1673 if (const AtomicType *AT = Type->getAs<AtomicType>())
1674 Type = AT->getValueType();
1675
Richard Smithb228a862012-02-15 02:18:13 +00001676 // Core issue 1454: For a literal constant expression of array or class type,
1677 // each subobject of its value shall have been initialized by a constant
1678 // expression.
1679 if (Value.isArray()) {
1680 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1681 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1682 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1683 Value.getArrayInitializedElt(I)))
1684 return false;
1685 }
1686 if (!Value.hasArrayFiller())
1687 return true;
1688 return CheckConstantExpression(Info, DiagLoc, EltTy,
1689 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001690 }
Richard Smithb228a862012-02-15 02:18:13 +00001691 if (Value.isUnion() && Value.getUnionField()) {
1692 return CheckConstantExpression(Info, DiagLoc,
1693 Value.getUnionField()->getType(),
1694 Value.getUnionValue());
1695 }
1696 if (Value.isStruct()) {
1697 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1698 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1699 unsigned BaseIndex = 0;
1700 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1701 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1702 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1703 Value.getStructBase(BaseIndex)))
1704 return false;
1705 }
1706 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001707 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001708 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1709 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001710 return false;
1711 }
1712 }
1713
1714 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001715 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001716 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001717 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1718 }
1719
1720 // Everything else is fine.
1721 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001722}
1723
Benjamin Kramer8407df72015-03-09 16:47:52 +00001724static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001725 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001726}
1727
1728static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001729 if (Value.CallIndex)
1730 return false;
1731 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1732 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001733}
1734
Richard Smithcecf1842011-11-01 21:06:14 +00001735static bool IsWeakLValue(const LValue &Value) {
1736 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001737 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001738}
1739
David Majnemerb5116032014-12-09 23:32:34 +00001740static bool isZeroSized(const LValue &Value) {
1741 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001742 if (Decl && isa<VarDecl>(Decl)) {
1743 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001744 if (Ty->isArrayType())
1745 return Ty->isIncompleteType() ||
1746 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001747 }
1748 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001749}
1750
Richard Smith2e312c82012-03-03 22:46:17 +00001751static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001752 // A null base expression indicates a null pointer. These are always
1753 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001754 if (!Value.getLValueBase()) {
1755 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001756 return true;
1757 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001758
Richard Smith027bf112011-11-17 22:56:20 +00001759 // We have a non-null base. These are generally known to be true, but if it's
1760 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001761 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001762 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001763 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001764}
1765
Richard Smith2e312c82012-03-03 22:46:17 +00001766static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001767 switch (Val.getKind()) {
1768 case APValue::Uninitialized:
1769 return false;
1770 case APValue::Int:
1771 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001772 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001773 case APValue::Float:
1774 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001775 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001776 case APValue::ComplexInt:
1777 Result = Val.getComplexIntReal().getBoolValue() ||
1778 Val.getComplexIntImag().getBoolValue();
1779 return true;
1780 case APValue::ComplexFloat:
1781 Result = !Val.getComplexFloatReal().isZero() ||
1782 !Val.getComplexFloatImag().isZero();
1783 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001784 case APValue::LValue:
1785 return EvalPointerValueAsBool(Val, Result);
1786 case APValue::MemberPointer:
1787 Result = Val.getMemberPointerDecl();
1788 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001789 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001790 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001791 case APValue::Struct:
1792 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001793 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001794 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001795 }
1796
Richard Smith11562c52011-10-28 17:51:58 +00001797 llvm_unreachable("unknown APValue kind");
1798}
1799
1800static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1801 EvalInfo &Info) {
1802 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001803 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001804 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001805 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001806 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001807}
1808
Richard Smith357362d2011-12-13 06:39:58 +00001809template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001810static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001811 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001812 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001813 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001814 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001815}
1816
1817static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1818 QualType SrcType, const APFloat &Value,
1819 QualType DestType, APSInt &Result) {
1820 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001821 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001822 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001823
Richard Smith357362d2011-12-13 06:39:58 +00001824 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001825 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001826 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1827 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001828 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001829 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001830}
1831
Richard Smith357362d2011-12-13 06:39:58 +00001832static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1833 QualType SrcType, QualType DestType,
1834 APFloat &Result) {
1835 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001836 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001837 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1838 APFloat::rmNearestTiesToEven, &ignored)
1839 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001840 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001841 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001842}
1843
Richard Smith911e1422012-01-30 22:27:01 +00001844static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1845 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001846 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001847 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001848 APSInt Result = Value;
1849 // Figure out if this is a truncate, extend or noop cast.
1850 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001851 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001852 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001853 return Result;
1854}
1855
Richard Smith357362d2011-12-13 06:39:58 +00001856static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1857 QualType SrcType, const APSInt &Value,
1858 QualType DestType, APFloat &Result) {
1859 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1860 if (Result.convertFromAPInt(Value, Value.isSigned(),
1861 APFloat::rmNearestTiesToEven)
1862 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001863 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001864 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001865}
1866
Richard Smith49ca8aa2013-08-06 07:09:20 +00001867static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1868 APValue &Value, const FieldDecl *FD) {
1869 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1870
1871 if (!Value.isInt()) {
1872 // Trying to store a pointer-cast-to-integer into a bitfield.
1873 // FIXME: In this case, we should provide the diagnostic for casting
1874 // a pointer to an integer.
1875 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001876 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001877 return false;
1878 }
1879
1880 APSInt &Int = Value.getInt();
1881 unsigned OldBitWidth = Int.getBitWidth();
1882 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1883 if (NewBitWidth < OldBitWidth)
1884 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1885 return true;
1886}
1887
Eli Friedman803acb32011-12-22 03:51:45 +00001888static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1889 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001890 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001891 if (!Evaluate(SVal, Info, E))
1892 return false;
1893 if (SVal.isInt()) {
1894 Res = SVal.getInt();
1895 return true;
1896 }
1897 if (SVal.isFloat()) {
1898 Res = SVal.getFloat().bitcastToAPInt();
1899 return true;
1900 }
1901 if (SVal.isVector()) {
1902 QualType VecTy = E->getType();
1903 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1904 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1905 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1906 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1907 Res = llvm::APInt::getNullValue(VecSize);
1908 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1909 APValue &Elt = SVal.getVectorElt(i);
1910 llvm::APInt EltAsInt;
1911 if (Elt.isInt()) {
1912 EltAsInt = Elt.getInt();
1913 } else if (Elt.isFloat()) {
1914 EltAsInt = Elt.getFloat().bitcastToAPInt();
1915 } else {
1916 // Don't try to handle vectors of anything other than int or float
1917 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001918 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001919 return false;
1920 }
1921 unsigned BaseEltSize = EltAsInt.getBitWidth();
1922 if (BigEndian)
1923 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1924 else
1925 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1926 }
1927 return true;
1928 }
1929 // Give up if the input isn't an int, float, or vector. For example, we
1930 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001931 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001932 return false;
1933}
1934
Richard Smith43e77732013-05-07 04:50:00 +00001935/// Perform the given integer operation, which is known to need at most BitWidth
1936/// bits, and check for overflow in the original type (if that type was not an
1937/// unsigned type).
1938template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001939static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1940 const APSInt &LHS, const APSInt &RHS,
1941 unsigned BitWidth, Operation Op,
1942 APSInt &Result) {
1943 if (LHS.isUnsigned()) {
1944 Result = Op(LHS, RHS);
1945 return true;
1946 }
Richard Smith43e77732013-05-07 04:50:00 +00001947
1948 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001949 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001950 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001951 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001952 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001953 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001954 << Result.toString(10) << E->getType();
1955 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001956 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001957 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001958 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001959}
1960
1961/// Perform the given binary integer operation.
1962static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1963 BinaryOperatorKind Opcode, APSInt RHS,
1964 APSInt &Result) {
1965 switch (Opcode) {
1966 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001967 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001968 return false;
1969 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001970 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1971 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001972 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001973 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1974 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001975 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001976 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1977 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001978 case BO_And: Result = LHS & RHS; return true;
1979 case BO_Xor: Result = LHS ^ RHS; return true;
1980 case BO_Or: Result = LHS | RHS; return true;
1981 case BO_Div:
1982 case BO_Rem:
1983 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001984 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001985 return false;
1986 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001987 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1988 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1989 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001990 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1991 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001992 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1993 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001994 return true;
1995 case BO_Shl: {
1996 if (Info.getLangOpts().OpenCL)
1997 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1998 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1999 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2000 RHS.isUnsigned());
2001 else if (RHS.isSigned() && RHS.isNegative()) {
2002 // During constant-folding, a negative shift is an opposite shift. Such
2003 // a shift is not a constant expression.
2004 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2005 RHS = -RHS;
2006 goto shift_right;
2007 }
2008 shift_left:
2009 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2010 // the shifted type.
2011 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2012 if (SA != RHS) {
2013 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2014 << RHS << E->getType() << LHS.getBitWidth();
2015 } else if (LHS.isSigned()) {
2016 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2017 // operand, and must not overflow the corresponding unsigned type.
2018 if (LHS.isNegative())
2019 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2020 else if (LHS.countLeadingZeros() < SA)
2021 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2022 }
2023 Result = LHS << SA;
2024 return true;
2025 }
2026 case BO_Shr: {
2027 if (Info.getLangOpts().OpenCL)
2028 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2029 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2030 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2031 RHS.isUnsigned());
2032 else if (RHS.isSigned() && RHS.isNegative()) {
2033 // During constant-folding, a negative shift is an opposite shift. Such a
2034 // shift is not a constant expression.
2035 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2036 RHS = -RHS;
2037 goto shift_left;
2038 }
2039 shift_right:
2040 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2041 // shifted type.
2042 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2043 if (SA != RHS)
2044 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2045 << RHS << E->getType() << LHS.getBitWidth();
2046 Result = LHS >> SA;
2047 return true;
2048 }
2049
2050 case BO_LT: Result = LHS < RHS; return true;
2051 case BO_GT: Result = LHS > RHS; return true;
2052 case BO_LE: Result = LHS <= RHS; return true;
2053 case BO_GE: Result = LHS >= RHS; return true;
2054 case BO_EQ: Result = LHS == RHS; return true;
2055 case BO_NE: Result = LHS != RHS; return true;
2056 }
2057}
2058
Richard Smith861b5b52013-05-07 23:34:45 +00002059/// Perform the given binary floating-point operation, in-place, on LHS.
2060static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2061 APFloat &LHS, BinaryOperatorKind Opcode,
2062 const APFloat &RHS) {
2063 switch (Opcode) {
2064 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002066 return false;
2067 case BO_Mul:
2068 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2069 break;
2070 case BO_Add:
2071 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2072 break;
2073 case BO_Sub:
2074 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2075 break;
2076 case BO_Div:
2077 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2078 break;
2079 }
2080
Richard Smith0c6124b2015-12-03 01:36:22 +00002081 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002082 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002083 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002084 }
Richard Smith861b5b52013-05-07 23:34:45 +00002085 return true;
2086}
2087
Richard Smitha8105bc2012-01-06 16:39:00 +00002088/// Cast an lvalue referring to a base subobject to a derived class, by
2089/// truncating the lvalue's path to the given length.
2090static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2091 const RecordDecl *TruncatedType,
2092 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002093 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002094
2095 // Check we actually point to a derived class object.
2096 if (TruncatedElements == D.Entries.size())
2097 return true;
2098 assert(TruncatedElements >= D.MostDerivedPathLength &&
2099 "not casting to a derived class");
2100 if (!Result.checkSubobject(Info, E, CSK_Derived))
2101 return false;
2102
2103 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002104 const RecordDecl *RD = TruncatedType;
2105 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002106 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002107 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2108 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002109 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002110 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002111 else
Richard Smithd62306a2011-11-10 06:34:14 +00002112 Result.Offset -= Layout.getBaseClassOffset(Base);
2113 RD = Base;
2114 }
Richard Smith027bf112011-11-17 22:56:20 +00002115 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002116 return true;
2117}
2118
John McCalld7bca762012-05-01 00:38:49 +00002119static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002120 const CXXRecordDecl *Derived,
2121 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002122 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002123 if (!RL) {
2124 if (Derived->isInvalidDecl()) return false;
2125 RL = &Info.Ctx.getASTRecordLayout(Derived);
2126 }
2127
Richard Smithd62306a2011-11-10 06:34:14 +00002128 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002129 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002130 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002131}
2132
Richard Smitha8105bc2012-01-06 16:39:00 +00002133static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002134 const CXXRecordDecl *DerivedDecl,
2135 const CXXBaseSpecifier *Base) {
2136 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2137
John McCalld7bca762012-05-01 00:38:49 +00002138 if (!Base->isVirtual())
2139 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002140
Richard Smitha8105bc2012-01-06 16:39:00 +00002141 SubobjectDesignator &D = Obj.Designator;
2142 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002143 return false;
2144
Richard Smitha8105bc2012-01-06 16:39:00 +00002145 // Extract most-derived object and corresponding type.
2146 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2147 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2148 return false;
2149
2150 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002151 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002152 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2153 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002154 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002155 return true;
2156}
2157
Richard Smith84401042013-06-03 05:03:02 +00002158static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2159 QualType Type, LValue &Result) {
2160 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2161 PathE = E->path_end();
2162 PathI != PathE; ++PathI) {
2163 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2164 *PathI))
2165 return false;
2166 Type = (*PathI)->getType();
2167 }
2168 return true;
2169}
2170
Richard Smithd62306a2011-11-10 06:34:14 +00002171/// Update LVal to refer to the given field, which must be a member of the type
2172/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002173static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002174 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002175 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002176 if (!RL) {
2177 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002178 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002179 }
Richard Smithd62306a2011-11-10 06:34:14 +00002180
2181 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002182 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002183 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002184 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002185}
2186
Richard Smith1b78b3d2012-01-25 22:15:11 +00002187/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002188static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002189 LValue &LVal,
2190 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002191 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002192 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002193 return false;
2194 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002195}
2196
Richard Smithd62306a2011-11-10 06:34:14 +00002197/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002198static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2199 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002200 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2201 // extension.
2202 if (Type->isVoidType() || Type->isFunctionType()) {
2203 Size = CharUnits::One();
2204 return true;
2205 }
2206
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002207 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002208 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002209 return false;
2210 }
2211
Richard Smithd62306a2011-11-10 06:34:14 +00002212 if (!Type->isConstantSizeType()) {
2213 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002214 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002215 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002216 return false;
2217 }
2218
2219 Size = Info.Ctx.getTypeSizeInChars(Type);
2220 return true;
2221}
2222
2223/// Update a pointer value to model pointer arithmetic.
2224/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002225/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002226/// \param LVal - The pointer value to be updated.
2227/// \param EltTy - The pointee type represented by LVal.
2228/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002229static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2230 LValue &LVal, QualType EltTy,
2231 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002232 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002233 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002234 return false;
2235
Yaxun Liu402804b2016-12-15 08:09:08 +00002236 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002237 return true;
2238}
2239
Richard Smith66c96992012-02-18 22:04:06 +00002240/// Update an lvalue to refer to a component of a complex number.
2241/// \param Info - Information about the ongoing evaluation.
2242/// \param LVal - The lvalue to be updated.
2243/// \param EltTy - The complex number's component type.
2244/// \param Imag - False for the real component, true for the imaginary.
2245static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2246 LValue &LVal, QualType EltTy,
2247 bool Imag) {
2248 if (Imag) {
2249 CharUnits SizeOfComponent;
2250 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2251 return false;
2252 LVal.Offset += SizeOfComponent;
2253 }
2254 LVal.addComplex(Info, E, EltTy, Imag);
2255 return true;
2256}
2257
Richard Smith27908702011-10-24 17:54:18 +00002258/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002259///
2260/// \param Info Information about the ongoing evaluation.
2261/// \param E An expression to be used when printing diagnostics.
2262/// \param VD The variable whose initializer should be obtained.
2263/// \param Frame The frame in which the variable was created. Must be null
2264/// if this variable is not local to the evaluation.
2265/// \param Result Filled in with a pointer to the value of the variable.
2266static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2267 const VarDecl *VD, CallStackFrame *Frame,
2268 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002269 // If this is a parameter to an active constexpr function call, perform
2270 // argument substitution.
2271 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002272 // Assume arguments of a potential constant expression are unknown
2273 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002274 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002275 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002276 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002277 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002278 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002279 }
Richard Smith3229b742013-05-05 21:17:10 +00002280 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002281 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002282 }
Richard Smith27908702011-10-24 17:54:18 +00002283
Richard Smithd9f663b2013-04-22 15:31:51 +00002284 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002285 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002286 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002287 if (!Result) {
2288 // Assume variables referenced within a lambda's call operator that were
2289 // not declared within the call operator are captures and during checking
2290 // of a potential constant expression, assume they are unknown constant
2291 // expressions.
2292 assert(isLambdaCallOperator(Frame->Callee) &&
2293 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2294 "missing value for local variable");
2295 if (Info.checkingPotentialConstantExpression())
2296 return false;
2297 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002298 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002299 diag::note_unimplemented_constexpr_lambda_feature_ast)
2300 << "captures not currently allowed";
2301 return false;
2302 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002303 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002304 }
2305
Richard Smithd0b4dd62011-12-19 06:19:21 +00002306 // Dig out the initializer, and use the declaration which it's attached to.
2307 const Expr *Init = VD->getAnyInitializer(VD);
2308 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002309 // If we're checking a potential constant expression, the variable could be
2310 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002311 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002312 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002313 return false;
2314 }
2315
Richard Smithd62306a2011-11-10 06:34:14 +00002316 // If we're currently evaluating the initializer of this declaration, use that
2317 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002318 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002319 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002320 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002321 }
2322
Richard Smithcecf1842011-11-01 21:06:14 +00002323 // Never evaluate the initializer of a weak variable. We can't be sure that
2324 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002325 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002326 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002327 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002328 }
Richard Smithcecf1842011-11-01 21:06:14 +00002329
Richard Smithd0b4dd62011-12-19 06:19:21 +00002330 // Check that we can fold the initializer. In C++, we will have already done
2331 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002332 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002333 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002334 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002335 Notes.size() + 1) << VD;
2336 Info.Note(VD->getLocation(), diag::note_declared_at);
2337 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002338 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002339 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002340 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002341 Notes.size() + 1) << VD;
2342 Info.Note(VD->getLocation(), diag::note_declared_at);
2343 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002344 }
Richard Smith27908702011-10-24 17:54:18 +00002345
Richard Smith3229b742013-05-05 21:17:10 +00002346 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002347 return true;
Richard Smith27908702011-10-24 17:54:18 +00002348}
2349
Richard Smith11562c52011-10-28 17:51:58 +00002350static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002351 Qualifiers Quals = T.getQualifiers();
2352 return Quals.hasConst() && !Quals.hasVolatile();
2353}
2354
Richard Smithe97cbd72011-11-11 04:05:33 +00002355/// Get the base index of the given base class within an APValue representing
2356/// the given derived class.
2357static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2358 const CXXRecordDecl *Base) {
2359 Base = Base->getCanonicalDecl();
2360 unsigned Index = 0;
2361 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2362 E = Derived->bases_end(); I != E; ++I, ++Index) {
2363 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2364 return Index;
2365 }
2366
2367 llvm_unreachable("base class missing from derived class's bases list");
2368}
2369
Richard Smith3da88fa2013-04-26 14:36:30 +00002370/// Extract the value of a character from a string literal.
2371static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2372 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002373 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2374 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2375 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002376 const StringLiteral *S = cast<StringLiteral>(Lit);
2377 const ConstantArrayType *CAT =
2378 Info.Ctx.getAsConstantArrayType(S->getType());
2379 assert(CAT && "string literal isn't an array");
2380 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002381 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002382
2383 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002384 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002385 if (Index < S->getLength())
2386 Value = S->getCodeUnit(Index);
2387 return Value;
2388}
2389
Richard Smith3da88fa2013-04-26 14:36:30 +00002390// Expand a string literal into an array of characters.
2391static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2392 APValue &Result) {
2393 const StringLiteral *S = cast<StringLiteral>(Lit);
2394 const ConstantArrayType *CAT =
2395 Info.Ctx.getAsConstantArrayType(S->getType());
2396 assert(CAT && "string literal isn't an array");
2397 QualType CharType = CAT->getElementType();
2398 assert(CharType->isIntegerType() && "unexpected character type");
2399
2400 unsigned Elts = CAT->getSize().getZExtValue();
2401 Result = APValue(APValue::UninitArray(),
2402 std::min(S->getLength(), Elts), Elts);
2403 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2404 CharType->isUnsignedIntegerType());
2405 if (Result.hasArrayFiller())
2406 Result.getArrayFiller() = APValue(Value);
2407 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2408 Value = S->getCodeUnit(I);
2409 Result.getArrayInitializedElt(I) = APValue(Value);
2410 }
2411}
2412
2413// Expand an array so that it has more than Index filled elements.
2414static void expandArray(APValue &Array, unsigned Index) {
2415 unsigned Size = Array.getArraySize();
2416 assert(Index < Size);
2417
2418 // Always at least double the number of elements for which we store a value.
2419 unsigned OldElts = Array.getArrayInitializedElts();
2420 unsigned NewElts = std::max(Index+1, OldElts * 2);
2421 NewElts = std::min(Size, std::max(NewElts, 8u));
2422
2423 // Copy the data across.
2424 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2425 for (unsigned I = 0; I != OldElts; ++I)
2426 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2427 for (unsigned I = OldElts; I != NewElts; ++I)
2428 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2429 if (NewValue.hasArrayFiller())
2430 NewValue.getArrayFiller() = Array.getArrayFiller();
2431 Array.swap(NewValue);
2432}
2433
Richard Smithb01fe402014-09-16 01:24:02 +00002434/// Determine whether a type would actually be read by an lvalue-to-rvalue
2435/// conversion. If it's of class type, we may assume that the copy operation
2436/// is trivial. Note that this is never true for a union type with fields
2437/// (because the copy always "reads" the active member) and always true for
2438/// a non-class type.
2439static bool isReadByLvalueToRvalueConversion(QualType T) {
2440 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2441 if (!RD || (RD->isUnion() && !RD->field_empty()))
2442 return true;
2443 if (RD->isEmpty())
2444 return false;
2445
2446 for (auto *Field : RD->fields())
2447 if (isReadByLvalueToRvalueConversion(Field->getType()))
2448 return true;
2449
2450 for (auto &BaseSpec : RD->bases())
2451 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2452 return true;
2453
2454 return false;
2455}
2456
2457/// Diagnose an attempt to read from any unreadable field within the specified
2458/// type, which might be a class type.
2459static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2460 QualType T) {
2461 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2462 if (!RD)
2463 return false;
2464
2465 if (!RD->hasMutableFields())
2466 return false;
2467
2468 for (auto *Field : RD->fields()) {
2469 // If we're actually going to read this field in some way, then it can't
2470 // be mutable. If we're in a union, then assigning to a mutable field
2471 // (even an empty one) can change the active member, so that's not OK.
2472 // FIXME: Add core issue number for the union case.
2473 if (Field->isMutable() &&
2474 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002475 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002476 Info.Note(Field->getLocation(), diag::note_declared_at);
2477 return true;
2478 }
2479
2480 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2481 return true;
2482 }
2483
2484 for (auto &BaseSpec : RD->bases())
2485 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2486 return true;
2487
2488 // All mutable fields were empty, and thus not actually read.
2489 return false;
2490}
2491
Richard Smith861b5b52013-05-07 23:34:45 +00002492/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002493enum AccessKinds {
2494 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002495 AK_Assign,
2496 AK_Increment,
2497 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002498};
2499
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002500namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002501/// A handle to a complete object (an object that is not a subobject of
2502/// another object).
2503struct CompleteObject {
2504 /// The value of the complete object.
2505 APValue *Value;
2506 /// The type of the complete object.
2507 QualType Type;
2508
Craig Topper36250ad2014-05-12 05:36:57 +00002509 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002510 CompleteObject(APValue *Value, QualType Type)
2511 : Value(Value), Type(Type) {
2512 assert(Value && "missing value for complete object");
2513 }
2514
Aaron Ballman67347662015-02-15 22:00:28 +00002515 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002516};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002517} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002518
Richard Smith3da88fa2013-04-26 14:36:30 +00002519/// Find the designated sub-object of an rvalue.
2520template<typename SubobjectHandler>
2521typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002522findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002523 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002524 if (Sub.Invalid)
2525 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002526 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002527 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002528 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002529 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002530 << handler.AccessKind;
2531 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002532 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002533 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002534 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002535
Richard Smith3229b742013-05-05 21:17:10 +00002536 APValue *O = Obj.Value;
2537 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002538 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002539
Richard Smithd62306a2011-11-10 06:34:14 +00002540 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002541 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2542 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002543 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002544 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002545 return handler.failed();
2546 }
2547
Richard Smith49ca8aa2013-08-06 07:09:20 +00002548 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002549 // If we are reading an object of class type, there may still be more
2550 // things we need to check: if there are any mutable subobjects, we
2551 // cannot perform this read. (This only happens when performing a trivial
2552 // copy or assignment.)
2553 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2554 diagnoseUnreadableFields(Info, E, ObjType))
2555 return handler.failed();
2556
Richard Smith49ca8aa2013-08-06 07:09:20 +00002557 if (!handler.found(*O, ObjType))
2558 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002559
Richard Smith49ca8aa2013-08-06 07:09:20 +00002560 // If we modified a bit-field, truncate it to the right width.
2561 if (handler.AccessKind != AK_Read &&
2562 LastField && LastField->isBitField() &&
2563 !truncateBitfieldValue(Info, E, *O, LastField))
2564 return false;
2565
2566 return true;
2567 }
2568
Craig Topper36250ad2014-05-12 05:36:57 +00002569 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002570 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002571 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002572 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002573 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002574 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002575 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002576 // Note, it should not be possible to form a pointer with a valid
2577 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002578 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002579 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002580 << handler.AccessKind;
2581 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002582 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002583 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002584 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002585
2586 ObjType = CAT->getElementType();
2587
Richard Smith14a94132012-02-17 03:35:37 +00002588 // An array object is represented as either an Array APValue or as an
2589 // LValue which refers to a string literal.
2590 if (O->isLValue()) {
2591 assert(I == N - 1 && "extracting subobject of character?");
2592 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002593 if (handler.AccessKind != AK_Read)
2594 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2595 *O);
2596 else
2597 return handler.foundString(*O, ObjType, Index);
2598 }
2599
2600 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002601 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002602 else if (handler.AccessKind != AK_Read) {
2603 expandArray(*O, Index);
2604 O = &O->getArrayInitializedElt(Index);
2605 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002606 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002607 } else if (ObjType->isAnyComplexType()) {
2608 // Next subobject is a complex number.
2609 uint64_t Index = Sub.Entries[I].ArrayIndex;
2610 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002611 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002612 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002613 << handler.AccessKind;
2614 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002615 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002616 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002617 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002618
2619 bool WasConstQualified = ObjType.isConstQualified();
2620 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2621 if (WasConstQualified)
2622 ObjType.addConst();
2623
Richard Smith66c96992012-02-18 22:04:06 +00002624 assert(I == N - 1 && "extracting subobject of scalar?");
2625 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 return handler.found(Index ? O->getComplexIntImag()
2627 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002628 } else {
2629 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002630 return handler.found(Index ? O->getComplexFloatImag()
2631 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002632 }
Richard Smithd62306a2011-11-10 06:34:14 +00002633 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002634 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002635 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002636 << Field;
2637 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002638 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002639 }
2640
Richard Smithd62306a2011-11-10 06:34:14 +00002641 // Next subobject is a class, struct or union field.
2642 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2643 if (RD->isUnion()) {
2644 const FieldDecl *UnionField = O->getUnionField();
2645 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002646 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002647 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002648 << handler.AccessKind << Field << !UnionField << UnionField;
2649 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002650 }
Richard Smithd62306a2011-11-10 06:34:14 +00002651 O = &O->getUnionValue();
2652 } else
2653 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002654
2655 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002656 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 if (WasConstQualified && !Field->isMutable())
2658 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002659
2660 if (ObjType.isVolatileQualified()) {
2661 if (Info.getLangOpts().CPlusPlus) {
2662 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002663 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002665 Info.Note(Field->getLocation(), diag::note_declared_at);
2666 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002667 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002668 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002669 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002670 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002671
2672 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002673 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002674 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002675 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2676 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2677 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002678
2679 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002680 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 if (WasConstQualified)
2682 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002683 }
2684 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002685}
2686
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002687namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002688struct ExtractSubobjectHandler {
2689 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002690 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002691
2692 static const AccessKinds AccessKind = AK_Read;
2693
2694 typedef bool result_type;
2695 bool failed() { return false; }
2696 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002697 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002698 return true;
2699 }
2700 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002701 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002702 return true;
2703 }
2704 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002705 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002706 return true;
2707 }
2708 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002709 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002710 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2711 return true;
2712 }
2713};
Richard Smith3229b742013-05-05 21:17:10 +00002714} // end anonymous namespace
2715
Richard Smith3da88fa2013-04-26 14:36:30 +00002716const AccessKinds ExtractSubobjectHandler::AccessKind;
2717
2718/// Extract the designated sub-object of an rvalue.
2719static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002720 const CompleteObject &Obj,
2721 const SubobjectDesignator &Sub,
2722 APValue &Result) {
2723 ExtractSubobjectHandler Handler = { Info, Result };
2724 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002725}
2726
Richard Smith3229b742013-05-05 21:17:10 +00002727namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002728struct ModifySubobjectHandler {
2729 EvalInfo &Info;
2730 APValue &NewVal;
2731 const Expr *E;
2732
2733 typedef bool result_type;
2734 static const AccessKinds AccessKind = AK_Assign;
2735
2736 bool checkConst(QualType QT) {
2737 // Assigning to a const object has undefined behavior.
2738 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002739 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 return false;
2741 }
2742 return true;
2743 }
2744
2745 bool failed() { return false; }
2746 bool found(APValue &Subobj, QualType SubobjType) {
2747 if (!checkConst(SubobjType))
2748 return false;
2749 // We've been given ownership of NewVal, so just swap it in.
2750 Subobj.swap(NewVal);
2751 return true;
2752 }
2753 bool found(APSInt &Value, QualType SubobjType) {
2754 if (!checkConst(SubobjType))
2755 return false;
2756 if (!NewVal.isInt()) {
2757 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002758 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002759 return false;
2760 }
2761 Value = NewVal.getInt();
2762 return true;
2763 }
2764 bool found(APFloat &Value, QualType SubobjType) {
2765 if (!checkConst(SubobjType))
2766 return false;
2767 Value = NewVal.getFloat();
2768 return true;
2769 }
2770 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2771 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2772 }
2773};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002774} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002775
Richard Smith3229b742013-05-05 21:17:10 +00002776const AccessKinds ModifySubobjectHandler::AccessKind;
2777
Richard Smith3da88fa2013-04-26 14:36:30 +00002778/// Update the designated sub-object of an rvalue to the given value.
2779static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002780 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 const SubobjectDesignator &Sub,
2782 APValue &NewVal) {
2783 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002784 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002785}
2786
Richard Smith84f6dcf2012-02-02 01:16:57 +00002787/// Find the position where two subobject designators diverge, or equivalently
2788/// the length of the common initial subsequence.
2789static unsigned FindDesignatorMismatch(QualType ObjType,
2790 const SubobjectDesignator &A,
2791 const SubobjectDesignator &B,
2792 bool &WasArrayIndex) {
2793 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2794 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002795 if (!ObjType.isNull() &&
2796 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002797 // Next subobject is an array element.
2798 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2799 WasArrayIndex = true;
2800 return I;
2801 }
Richard Smith66c96992012-02-18 22:04:06 +00002802 if (ObjType->isAnyComplexType())
2803 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2804 else
2805 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002806 } else {
2807 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2808 WasArrayIndex = false;
2809 return I;
2810 }
2811 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2812 // Next subobject is a field.
2813 ObjType = FD->getType();
2814 else
2815 // Next subobject is a base class.
2816 ObjType = QualType();
2817 }
2818 }
2819 WasArrayIndex = false;
2820 return I;
2821}
2822
2823/// Determine whether the given subobject designators refer to elements of the
2824/// same array object.
2825static bool AreElementsOfSameArray(QualType ObjType,
2826 const SubobjectDesignator &A,
2827 const SubobjectDesignator &B) {
2828 if (A.Entries.size() != B.Entries.size())
2829 return false;
2830
George Burgess IVa51c4072015-10-16 01:49:01 +00002831 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002832 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2833 // A is a subobject of the array element.
2834 return false;
2835
2836 // If A (and B) designates an array element, the last entry will be the array
2837 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2838 // of length 1' case, and the entire path must match.
2839 bool WasArrayIndex;
2840 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2841 return CommonLength >= A.Entries.size() - IsArray;
2842}
2843
Richard Smith3229b742013-05-05 21:17:10 +00002844/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002845static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2846 AccessKinds AK, const LValue &LVal,
2847 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002848 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002849 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002850 return CompleteObject();
2851 }
2852
Craig Topper36250ad2014-05-12 05:36:57 +00002853 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002854 if (LVal.CallIndex) {
2855 Frame = Info.getCallFrame(LVal.CallIndex);
2856 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002857 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002858 << AK << LVal.Base.is<const ValueDecl*>();
2859 NoteLValueLocation(Info, LVal.Base);
2860 return CompleteObject();
2861 }
Richard Smith3229b742013-05-05 21:17:10 +00002862 }
2863
2864 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2865 // is not a constant expression (even if the object is non-volatile). We also
2866 // apply this rule to C++98, in order to conform to the expected 'volatile'
2867 // semantics.
2868 if (LValType.isVolatileQualified()) {
2869 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002870 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002871 << AK << LValType;
2872 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002873 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002874 return CompleteObject();
2875 }
2876
2877 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002878 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002879 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002880
2881 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2882 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2883 // In C++11, constexpr, non-volatile variables initialized with constant
2884 // expressions are constant expressions too. Inside constexpr functions,
2885 // parameters are constant expressions even if they're non-const.
2886 // In C++1y, objects local to a constant expression (those with a Frame) are
2887 // both readable and writable inside constant expressions.
2888 // In C, such things can also be folded, although they are not ICEs.
2889 const VarDecl *VD = dyn_cast<VarDecl>(D);
2890 if (VD) {
2891 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2892 VD = VDef;
2893 }
2894 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002895 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002896 return CompleteObject();
2897 }
2898
2899 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002900 if (BaseType.isVolatileQualified()) {
2901 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002902 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002903 << AK << 1 << VD;
2904 Info.Note(VD->getLocation(), diag::note_declared_at);
2905 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002906 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002907 }
2908 return CompleteObject();
2909 }
2910
2911 // Unless we're looking at a local variable or argument in a constexpr call,
2912 // the variable we're reading must be const.
2913 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002914 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002915 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2916 // OK, we can read and modify an object if we're in the process of
2917 // evaluating its initializer, because its lifetime began in this
2918 // evaluation.
2919 } else if (AK != AK_Read) {
2920 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002921 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002922 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002923 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002924 // OK, we can read this variable.
2925 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002926 // In OpenCL if a variable is in constant address space it is a const value.
2927 if (!(BaseType.isConstQualified() ||
2928 (Info.getLangOpts().OpenCL &&
2929 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002930 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002931 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002932 Info.Note(VD->getLocation(), diag::note_declared_at);
2933 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002934 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002935 }
2936 return CompleteObject();
2937 }
2938 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2939 // We support folding of const floating-point types, in order to make
2940 // static const data members of such types (supported as an extension)
2941 // more useful.
2942 if (Info.getLangOpts().CPlusPlus11) {
2943 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2944 Info.Note(VD->getLocation(), diag::note_declared_at);
2945 } else {
2946 Info.CCEDiag(E);
2947 }
George Burgess IVb5316982016-12-27 05:33:20 +00002948 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2949 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2950 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002951 } else {
2952 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002953 if (Info.checkingPotentialConstantExpression() &&
2954 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2955 // The definition of this variable could be constexpr. We can't
2956 // access it right now, but may be able to in future.
2957 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002958 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002959 Info.Note(VD->getLocation(), diag::note_declared_at);
2960 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002961 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002962 }
2963 return CompleteObject();
2964 }
2965 }
2966
2967 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2968 return CompleteObject();
2969 } else {
2970 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2971
2972 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002973 if (const MaterializeTemporaryExpr *MTE =
2974 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2975 assert(MTE->getStorageDuration() == SD_Static &&
2976 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002977
Richard Smithe6c01442013-06-05 00:46:14 +00002978 // Per C++1y [expr.const]p2:
2979 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2980 // - a [...] glvalue of integral or enumeration type that refers to
2981 // a non-volatile const object [...]
2982 // [...]
2983 // - a [...] glvalue of literal type that refers to a non-volatile
2984 // object whose lifetime began within the evaluation of e.
2985 //
2986 // C++11 misses the 'began within the evaluation of e' check and
2987 // instead allows all temporaries, including things like:
2988 // int &&r = 1;
2989 // int x = ++r;
2990 // constexpr int k = r;
2991 // Therefore we use the C++1y rules in C++11 too.
2992 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2993 const ValueDecl *ED = MTE->getExtendingDecl();
2994 if (!(BaseType.isConstQualified() &&
2995 BaseType->isIntegralOrEnumerationType()) &&
2996 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002997 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002998 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2999 return CompleteObject();
3000 }
3001
3002 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3003 assert(BaseVal && "got reference to unevaluated temporary");
3004 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003005 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003006 return CompleteObject();
3007 }
3008 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003009 BaseVal = Frame->getTemporary(Base);
3010 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003011 }
Richard Smith3229b742013-05-05 21:17:10 +00003012
3013 // Volatile temporary objects cannot be accessed in constant expressions.
3014 if (BaseType.isVolatileQualified()) {
3015 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003016 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003017 << AK << 0;
3018 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3019 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003020 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003021 }
3022 return CompleteObject();
3023 }
3024 }
3025
Richard Smith7525ff62013-05-09 07:14:00 +00003026 // During the construction of an object, it is not yet 'const'.
3027 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3028 // and this doesn't do quite the right thing for const subobjects of the
3029 // object under construction.
3030 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3031 BaseType = Info.Ctx.getCanonicalType(BaseType);
3032 BaseType.removeLocalConst();
3033 }
3034
Richard Smith6d4c6582013-11-05 22:18:15 +00003035 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003036 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003037 //
3038 // FIXME: Not all local state is mutable. Allow local constant subobjects
3039 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003040 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3041 Info.EvalStatus.HasSideEffects) ||
3042 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003043 return CompleteObject();
3044
3045 return CompleteObject(BaseVal, BaseType);
3046}
3047
Richard Smith243ef902013-05-05 23:31:59 +00003048/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3049/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3050/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003051///
3052/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003053/// \param Conv - The expression for which we are performing the conversion.
3054/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003055/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3056/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003057/// \param LVal - The glvalue on which we are attempting to perform this action.
3058/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003059static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003060 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003061 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003062 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003063 return false;
3064
Richard Smith3229b742013-05-05 21:17:10 +00003065 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003066 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003067 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003068 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3069 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3070 // initializer until now for such expressions. Such an expression can't be
3071 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003072 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003073 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003074 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003075 }
Richard Smith3229b742013-05-05 21:17:10 +00003076 APValue Lit;
3077 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3078 return false;
3079 CompleteObject LitObj(&Lit, Base->getType());
3080 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003081 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003082 // We represent a string literal array as an lvalue pointing at the
3083 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003084 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003085 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3086 CompleteObject StrObj(&Str, Base->getType());
3087 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003088 }
Richard Smith11562c52011-10-28 17:51:58 +00003089 }
3090
Richard Smith3229b742013-05-05 21:17:10 +00003091 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3092 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003093}
3094
3095/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003096static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003097 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003098 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003099 return false;
3100
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003101 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003102 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003103 return false;
3104 }
3105
Richard Smith3229b742013-05-05 21:17:10 +00003106 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3107 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003108}
3109
Richard Smith243ef902013-05-05 23:31:59 +00003110static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3111 return T->isSignedIntegerType() &&
3112 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3113}
3114
3115namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003116struct CompoundAssignSubobjectHandler {
3117 EvalInfo &Info;
3118 const Expr *E;
3119 QualType PromotedLHSType;
3120 BinaryOperatorKind Opcode;
3121 const APValue &RHS;
3122
3123 static const AccessKinds AccessKind = AK_Assign;
3124
3125 typedef bool result_type;
3126
3127 bool checkConst(QualType QT) {
3128 // Assigning to a const object has undefined behavior.
3129 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003130 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003131 return false;
3132 }
3133 return true;
3134 }
3135
3136 bool failed() { return false; }
3137 bool found(APValue &Subobj, QualType SubobjType) {
3138 switch (Subobj.getKind()) {
3139 case APValue::Int:
3140 return found(Subobj.getInt(), SubobjType);
3141 case APValue::Float:
3142 return found(Subobj.getFloat(), SubobjType);
3143 case APValue::ComplexInt:
3144 case APValue::ComplexFloat:
3145 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003146 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003147 return false;
3148 case APValue::LValue:
3149 return foundPointer(Subobj, SubobjType);
3150 default:
3151 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003152 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003153 return false;
3154 }
3155 }
3156 bool found(APSInt &Value, QualType SubobjType) {
3157 if (!checkConst(SubobjType))
3158 return false;
3159
3160 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3161 // We don't support compound assignment on integer-cast-to-pointer
3162 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003163 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003164 return false;
3165 }
3166
3167 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3168 SubobjType, Value);
3169 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3170 return false;
3171 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3172 return true;
3173 }
3174 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003175 return checkConst(SubobjType) &&
3176 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3177 Value) &&
3178 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3179 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003180 }
3181 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3182 if (!checkConst(SubobjType))
3183 return false;
3184
3185 QualType PointeeType;
3186 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3187 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003188
3189 if (PointeeType.isNull() || !RHS.isInt() ||
3190 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003191 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003192 return false;
3193 }
3194
Richard Smith642a2362017-01-30 23:30:26 +00003195 int64_t Offset;
3196 if (!getExtValue(Info, E, RHS.getInt(), Offset))
3197 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00003198 if (Opcode == BO_Sub)
3199 Offset = -Offset;
3200
3201 LValue LVal;
3202 LVal.setFrom(Info.Ctx, Subobj);
3203 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3204 return false;
3205 LVal.moveInto(Subobj);
3206 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003207 }
3208 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3209 llvm_unreachable("shouldn't encounter string elements here");
3210 }
3211};
3212} // end anonymous namespace
3213
3214const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3215
3216/// Perform a compound assignment of LVal <op>= RVal.
3217static bool handleCompoundAssignment(
3218 EvalInfo &Info, const Expr *E,
3219 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3220 BinaryOperatorKind Opcode, const APValue &RVal) {
3221 if (LVal.Designator.Invalid)
3222 return false;
3223
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003224 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003225 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003226 return false;
3227 }
3228
3229 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3230 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3231 RVal };
3232 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3233}
3234
3235namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003236struct IncDecSubobjectHandler {
3237 EvalInfo &Info;
3238 const Expr *E;
3239 AccessKinds AccessKind;
3240 APValue *Old;
3241
3242 typedef bool result_type;
3243
3244 bool checkConst(QualType QT) {
3245 // Assigning to a const object has undefined behavior.
3246 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003247 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003248 return false;
3249 }
3250 return true;
3251 }
3252
3253 bool failed() { return false; }
3254 bool found(APValue &Subobj, QualType SubobjType) {
3255 // Stash the old value. Also clear Old, so we don't clobber it later
3256 // if we're post-incrementing a complex.
3257 if (Old) {
3258 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003259 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003260 }
3261
3262 switch (Subobj.getKind()) {
3263 case APValue::Int:
3264 return found(Subobj.getInt(), SubobjType);
3265 case APValue::Float:
3266 return found(Subobj.getFloat(), SubobjType);
3267 case APValue::ComplexInt:
3268 return found(Subobj.getComplexIntReal(),
3269 SubobjType->castAs<ComplexType>()->getElementType()
3270 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3271 case APValue::ComplexFloat:
3272 return found(Subobj.getComplexFloatReal(),
3273 SubobjType->castAs<ComplexType>()->getElementType()
3274 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3275 case APValue::LValue:
3276 return foundPointer(Subobj, SubobjType);
3277 default:
3278 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003279 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003280 return false;
3281 }
3282 }
3283 bool found(APSInt &Value, QualType SubobjType) {
3284 if (!checkConst(SubobjType))
3285 return false;
3286
3287 if (!SubobjType->isIntegerType()) {
3288 // We don't support increment / decrement on integer-cast-to-pointer
3289 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003290 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003291 return false;
3292 }
3293
3294 if (Old) *Old = APValue(Value);
3295
3296 // bool arithmetic promotes to int, and the conversion back to bool
3297 // doesn't reduce mod 2^n, so special-case it.
3298 if (SubobjType->isBooleanType()) {
3299 if (AccessKind == AK_Increment)
3300 Value = 1;
3301 else
3302 Value = !Value;
3303 return true;
3304 }
3305
3306 bool WasNegative = Value.isNegative();
3307 if (AccessKind == AK_Increment) {
3308 ++Value;
3309
3310 if (!WasNegative && Value.isNegative() &&
3311 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3312 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003313 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003314 }
3315 } else {
3316 --Value;
3317
3318 if (WasNegative && !Value.isNegative() &&
3319 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3320 unsigned BitWidth = Value.getBitWidth();
3321 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3322 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003323 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003324 }
3325 }
3326 return true;
3327 }
3328 bool found(APFloat &Value, QualType SubobjType) {
3329 if (!checkConst(SubobjType))
3330 return false;
3331
3332 if (Old) *Old = APValue(Value);
3333
3334 APFloat One(Value.getSemantics(), 1);
3335 if (AccessKind == AK_Increment)
3336 Value.add(One, APFloat::rmNearestTiesToEven);
3337 else
3338 Value.subtract(One, APFloat::rmNearestTiesToEven);
3339 return true;
3340 }
3341 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3342 if (!checkConst(SubobjType))
3343 return false;
3344
3345 QualType PointeeType;
3346 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3347 PointeeType = PT->getPointeeType();
3348 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003349 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003350 return false;
3351 }
3352
3353 LValue LVal;
3354 LVal.setFrom(Info.Ctx, Subobj);
3355 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3356 AccessKind == AK_Increment ? 1 : -1))
3357 return false;
3358 LVal.moveInto(Subobj);
3359 return true;
3360 }
3361 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3362 llvm_unreachable("shouldn't encounter string elements here");
3363 }
3364};
3365} // end anonymous namespace
3366
3367/// Perform an increment or decrement on LVal.
3368static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3369 QualType LValType, bool IsIncrement, APValue *Old) {
3370 if (LVal.Designator.Invalid)
3371 return false;
3372
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003373 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003374 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003375 return false;
3376 }
3377
3378 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3379 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3380 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3381 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3382}
3383
Richard Smithe97cbd72011-11-11 04:05:33 +00003384/// Build an lvalue for the object argument of a member function call.
3385static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3386 LValue &This) {
3387 if (Object->getType()->isPointerType())
3388 return EvaluatePointer(Object, This, Info);
3389
3390 if (Object->isGLValue())
3391 return EvaluateLValue(Object, This, Info);
3392
Richard Smithd9f663b2013-04-22 15:31:51 +00003393 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003394 return EvaluateTemporary(Object, This, Info);
3395
Faisal Valie690b7a2016-07-02 22:34:24 +00003396 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003397 return false;
3398}
3399
3400/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3401/// lvalue referring to the result.
3402///
3403/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003404/// \param LV - An lvalue referring to the base of the member pointer.
3405/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003406/// \param IncludeMember - Specifies whether the member itself is included in
3407/// the resulting LValue subobject designator. This is not possible when
3408/// creating a bound member function.
3409/// \return The field or method declaration to which the member pointer refers,
3410/// or 0 if evaluation fails.
3411static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003412 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003413 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003414 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003415 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003416 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003417 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003418 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003419
3420 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3421 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003422 if (!MemPtr.getDecl()) {
3423 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003424 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003425 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003426 }
Richard Smith253c2a32012-01-27 01:14:48 +00003427
Richard Smith027bf112011-11-17 22:56:20 +00003428 if (MemPtr.isDerivedMember()) {
3429 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003430 // The end of the derived-to-base path for the base object must match the
3431 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003432 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003433 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003434 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003435 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003436 }
Richard Smith027bf112011-11-17 22:56:20 +00003437 unsigned PathLengthToMember =
3438 LV.Designator.Entries.size() - MemPtr.Path.size();
3439 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3440 const CXXRecordDecl *LVDecl = getAsBaseClass(
3441 LV.Designator.Entries[PathLengthToMember + I]);
3442 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003443 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003444 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003445 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003446 }
Richard Smith027bf112011-11-17 22:56:20 +00003447 }
3448
3449 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003450 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003451 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003452 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003453 } else if (!MemPtr.Path.empty()) {
3454 // Extend the LValue path with the member pointer's path.
3455 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3456 MemPtr.Path.size() + IncludeMember);
3457
3458 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003459 if (const PointerType *PT = LVType->getAs<PointerType>())
3460 LVType = PT->getPointeeType();
3461 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3462 assert(RD && "member pointer access on non-class-type expression");
3463 // The first class in the path is that of the lvalue.
3464 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3465 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003466 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003467 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003468 RD = Base;
3469 }
3470 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003471 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3472 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003473 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003474 }
3475
3476 // Add the member. Note that we cannot build bound member functions here.
3477 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003478 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003479 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003480 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003481 } else if (const IndirectFieldDecl *IFD =
3482 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003483 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003484 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003485 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003486 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003487 }
Richard Smith027bf112011-11-17 22:56:20 +00003488 }
3489
3490 return MemPtr.getDecl();
3491}
3492
Richard Smith84401042013-06-03 05:03:02 +00003493static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3494 const BinaryOperator *BO,
3495 LValue &LV,
3496 bool IncludeMember = true) {
3497 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3498
3499 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003500 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003501 MemberPtr MemPtr;
3502 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3503 }
Craig Topper36250ad2014-05-12 05:36:57 +00003504 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003505 }
3506
3507 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3508 BO->getRHS(), IncludeMember);
3509}
3510
Richard Smith027bf112011-11-17 22:56:20 +00003511/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3512/// the provided lvalue, which currently refers to the base object.
3513static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3514 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003515 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003516 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003517 return false;
3518
Richard Smitha8105bc2012-01-06 16:39:00 +00003519 QualType TargetQT = E->getType();
3520 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3521 TargetQT = PT->getPointeeType();
3522
3523 // Check this cast lands within the final derived-to-base subobject path.
3524 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003525 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003526 << D.MostDerivedType << TargetQT;
3527 return false;
3528 }
3529
Richard Smith027bf112011-11-17 22:56:20 +00003530 // Check the type of the final cast. We don't need to check the path,
3531 // since a cast can only be formed if the path is unique.
3532 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003533 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3534 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003535 if (NewEntriesSize == D.MostDerivedPathLength)
3536 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3537 else
Richard Smith027bf112011-11-17 22:56:20 +00003538 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003539 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003540 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003541 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003542 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003543 }
Richard Smith027bf112011-11-17 22:56:20 +00003544
3545 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003546 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003547}
3548
Mike Stump876387b2009-10-27 22:09:17 +00003549namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003550enum EvalStmtResult {
3551 /// Evaluation failed.
3552 ESR_Failed,
3553 /// Hit a 'return' statement.
3554 ESR_Returned,
3555 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003556 ESR_Succeeded,
3557 /// Hit a 'continue' statement.
3558 ESR_Continue,
3559 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003560 ESR_Break,
3561 /// Still scanning for 'case' or 'default' statement.
3562 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003563};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003564}
Richard Smith254a73d2011-10-28 22:34:42 +00003565
Richard Smith97fcf4b2016-08-14 23:15:52 +00003566static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3567 // We don't need to evaluate the initializer for a static local.
3568 if (!VD->hasLocalStorage())
3569 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003570
Richard Smith97fcf4b2016-08-14 23:15:52 +00003571 LValue Result;
3572 Result.set(VD, Info.CurrentCall->Index);
3573 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003574
Richard Smith97fcf4b2016-08-14 23:15:52 +00003575 const Expr *InitE = VD->getInit();
3576 if (!InitE) {
3577 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3578 << false << VD->getType();
3579 Val = APValue();
3580 return false;
3581 }
Richard Smith51f03172013-06-20 03:00:05 +00003582
Richard Smith97fcf4b2016-08-14 23:15:52 +00003583 if (InitE->isValueDependent())
3584 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003585
Richard Smith97fcf4b2016-08-14 23:15:52 +00003586 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3587 // Wipe out any partially-computed value, to allow tracking that this
3588 // evaluation failed.
3589 Val = APValue();
3590 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003591 }
3592
3593 return true;
3594}
3595
Richard Smith97fcf4b2016-08-14 23:15:52 +00003596static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3597 bool OK = true;
3598
3599 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3600 OK &= EvaluateVarDecl(Info, VD);
3601
3602 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3603 for (auto *BD : DD->bindings())
3604 if (auto *VD = BD->getHoldingVar())
3605 OK &= EvaluateDecl(Info, VD);
3606
3607 return OK;
3608}
3609
3610
Richard Smith4e18ca52013-05-06 05:56:11 +00003611/// Evaluate a condition (either a variable declaration or an expression).
3612static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3613 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003614 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003615 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3616 return false;
3617 return EvaluateAsBooleanCondition(Cond, Result, Info);
3618}
3619
Richard Smith89210072016-04-04 23:29:43 +00003620namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003621/// \brief A location where the result (returned value) of evaluating a
3622/// statement should be stored.
3623struct StmtResult {
3624 /// The APValue that should be filled in with the returned value.
3625 APValue &Value;
3626 /// The location containing the result, if any (used to support RVO).
3627 const LValue *Slot;
3628};
Richard Smith89210072016-04-04 23:29:43 +00003629}
Richard Smith52a980a2015-08-28 02:43:42 +00003630
3631static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003632 const Stmt *S,
3633 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003634
3635/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003636static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003637 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003638 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003639 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003640 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003641 case ESR_Break:
3642 return ESR_Succeeded;
3643 case ESR_Succeeded:
3644 case ESR_Continue:
3645 return ESR_Continue;
3646 case ESR_Failed:
3647 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003648 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003649 return ESR;
3650 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003651 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003652}
3653
Richard Smith496ddcf2013-05-12 17:32:42 +00003654/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003655static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003656 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003657 BlockScopeRAII Scope(Info);
3658
Richard Smith496ddcf2013-05-12 17:32:42 +00003659 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003660 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003661 {
3662 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003663 if (const Stmt *Init = SS->getInit()) {
3664 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3665 if (ESR != ESR_Succeeded)
3666 return ESR;
3667 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003668 if (SS->getConditionVariable() &&
3669 !EvaluateDecl(Info, SS->getConditionVariable()))
3670 return ESR_Failed;
3671 if (!EvaluateInteger(SS->getCond(), Value, Info))
3672 return ESR_Failed;
3673 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003674
3675 // Find the switch case corresponding to the value of the condition.
3676 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003677 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003678 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3679 SC = SC->getNextSwitchCase()) {
3680 if (isa<DefaultStmt>(SC)) {
3681 Found = SC;
3682 continue;
3683 }
3684
3685 const CaseStmt *CS = cast<CaseStmt>(SC);
3686 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3687 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3688 : LHS;
3689 if (LHS <= Value && Value <= RHS) {
3690 Found = SC;
3691 break;
3692 }
3693 }
3694
3695 if (!Found)
3696 return ESR_Succeeded;
3697
3698 // Search the switch body for the switch case and evaluate it from there.
3699 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3700 case ESR_Break:
3701 return ESR_Succeeded;
3702 case ESR_Succeeded:
3703 case ESR_Continue:
3704 case ESR_Failed:
3705 case ESR_Returned:
3706 return ESR;
3707 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003708 // This can only happen if the switch case is nested within a statement
3709 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003710 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003711 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003712 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003713 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003714}
3715
Richard Smith254a73d2011-10-28 22:34:42 +00003716// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003717static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003718 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003719 if (!Info.nextStep(S))
3720 return ESR_Failed;
3721
Richard Smith496ddcf2013-05-12 17:32:42 +00003722 // If we're hunting down a 'case' or 'default' label, recurse through
3723 // substatements until we hit the label.
3724 if (Case) {
3725 // FIXME: We don't start the lifetime of objects whose initialization we
3726 // jump over. However, such objects must be of class type with a trivial
3727 // default constructor that initialize all subobjects, so must be empty,
3728 // so this almost never matters.
3729 switch (S->getStmtClass()) {
3730 case Stmt::CompoundStmtClass:
3731 // FIXME: Precompute which substatement of a compound statement we
3732 // would jump to, and go straight there rather than performing a
3733 // linear scan each time.
3734 case Stmt::LabelStmtClass:
3735 case Stmt::AttributedStmtClass:
3736 case Stmt::DoStmtClass:
3737 break;
3738
3739 case Stmt::CaseStmtClass:
3740 case Stmt::DefaultStmtClass:
3741 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003742 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003743 break;
3744
3745 case Stmt::IfStmtClass: {
3746 // FIXME: Precompute which side of an 'if' we would jump to, and go
3747 // straight there rather than scanning both sides.
3748 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003749
3750 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3751 // preceded by our switch label.
3752 BlockScopeRAII Scope(Info);
3753
Richard Smith496ddcf2013-05-12 17:32:42 +00003754 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3755 if (ESR != ESR_CaseNotFound || !IS->getElse())
3756 return ESR;
3757 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3758 }
3759
3760 case Stmt::WhileStmtClass: {
3761 EvalStmtResult ESR =
3762 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3763 if (ESR != ESR_Continue)
3764 return ESR;
3765 break;
3766 }
3767
3768 case Stmt::ForStmtClass: {
3769 const ForStmt *FS = cast<ForStmt>(S);
3770 EvalStmtResult ESR =
3771 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3772 if (ESR != ESR_Continue)
3773 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003774 if (FS->getInc()) {
3775 FullExpressionRAII IncScope(Info);
3776 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3777 return ESR_Failed;
3778 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003779 break;
3780 }
3781
3782 case Stmt::DeclStmtClass:
3783 // FIXME: If the variable has initialization that can't be jumped over,
3784 // bail out of any immediately-surrounding compound-statement too.
3785 default:
3786 return ESR_CaseNotFound;
3787 }
3788 }
3789
Richard Smith254a73d2011-10-28 22:34:42 +00003790 switch (S->getStmtClass()) {
3791 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003792 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003793 // Don't bother evaluating beyond an expression-statement which couldn't
3794 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003795 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003796 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003797 return ESR_Failed;
3798 return ESR_Succeeded;
3799 }
3800
Faisal Valie690b7a2016-07-02 22:34:24 +00003801 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003802 return ESR_Failed;
3803
3804 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003805 return ESR_Succeeded;
3806
Richard Smithd9f663b2013-04-22 15:31:51 +00003807 case Stmt::DeclStmtClass: {
3808 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003809 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003810 // Each declaration initialization is its own full-expression.
3811 // FIXME: This isn't quite right; if we're performing aggregate
3812 // initialization, each braced subexpression is its own full-expression.
3813 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003814 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003815 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003816 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003817 return ESR_Succeeded;
3818 }
3819
Richard Smith357362d2011-12-13 06:39:58 +00003820 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003821 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003822 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003823 if (RetExpr &&
3824 !(Result.Slot
3825 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3826 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003827 return ESR_Failed;
3828 return ESR_Returned;
3829 }
Richard Smith254a73d2011-10-28 22:34:42 +00003830
3831 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003832 BlockScopeRAII Scope(Info);
3833
Richard Smith254a73d2011-10-28 22:34:42 +00003834 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003835 for (const auto *BI : CS->body()) {
3836 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003837 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003838 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003839 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003840 return ESR;
3841 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003842 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003843 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003844
3845 case Stmt::IfStmtClass: {
3846 const IfStmt *IS = cast<IfStmt>(S);
3847
3848 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003849 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003850 if (const Stmt *Init = IS->getInit()) {
3851 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3852 if (ESR != ESR_Succeeded)
3853 return ESR;
3854 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003855 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003856 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003857 return ESR_Failed;
3858
3859 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3860 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3861 if (ESR != ESR_Succeeded)
3862 return ESR;
3863 }
3864 return ESR_Succeeded;
3865 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003866
3867 case Stmt::WhileStmtClass: {
3868 const WhileStmt *WS = cast<WhileStmt>(S);
3869 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003870 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003871 bool Continue;
3872 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3873 Continue))
3874 return ESR_Failed;
3875 if (!Continue)
3876 break;
3877
3878 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3879 if (ESR != ESR_Continue)
3880 return ESR;
3881 }
3882 return ESR_Succeeded;
3883 }
3884
3885 case Stmt::DoStmtClass: {
3886 const DoStmt *DS = cast<DoStmt>(S);
3887 bool Continue;
3888 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003889 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003890 if (ESR != ESR_Continue)
3891 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003892 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003893
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003895 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3896 return ESR_Failed;
3897 } while (Continue);
3898 return ESR_Succeeded;
3899 }
3900
3901 case Stmt::ForStmtClass: {
3902 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003903 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003904 if (FS->getInit()) {
3905 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3906 if (ESR != ESR_Succeeded)
3907 return ESR;
3908 }
3909 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003910 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003911 bool Continue = true;
3912 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3913 FS->getCond(), Continue))
3914 return ESR_Failed;
3915 if (!Continue)
3916 break;
3917
3918 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3919 if (ESR != ESR_Continue)
3920 return ESR;
3921
Richard Smith08d6a2c2013-07-24 07:11:57 +00003922 if (FS->getInc()) {
3923 FullExpressionRAII IncScope(Info);
3924 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3925 return ESR_Failed;
3926 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003927 }
3928 return ESR_Succeeded;
3929 }
3930
Richard Smith896e0d72013-05-06 06:51:17 +00003931 case Stmt::CXXForRangeStmtClass: {
3932 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003933 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003934
3935 // Initialize the __range variable.
3936 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3937 if (ESR != ESR_Succeeded)
3938 return ESR;
3939
3940 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003941 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3942 if (ESR != ESR_Succeeded)
3943 return ESR;
3944 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003945 if (ESR != ESR_Succeeded)
3946 return ESR;
3947
3948 while (true) {
3949 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003950 {
3951 bool Continue = true;
3952 FullExpressionRAII CondExpr(Info);
3953 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3954 return ESR_Failed;
3955 if (!Continue)
3956 break;
3957 }
Richard Smith896e0d72013-05-06 06:51:17 +00003958
3959 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003960 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003961 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3962 if (ESR != ESR_Succeeded)
3963 return ESR;
3964
3965 // Loop body.
3966 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3967 if (ESR != ESR_Continue)
3968 return ESR;
3969
3970 // Increment: ++__begin
3971 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3972 return ESR_Failed;
3973 }
3974
3975 return ESR_Succeeded;
3976 }
3977
Richard Smith496ddcf2013-05-12 17:32:42 +00003978 case Stmt::SwitchStmtClass:
3979 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3980
Richard Smith4e18ca52013-05-06 05:56:11 +00003981 case Stmt::ContinueStmtClass:
3982 return ESR_Continue;
3983
3984 case Stmt::BreakStmtClass:
3985 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003986
3987 case Stmt::LabelStmtClass:
3988 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3989
3990 case Stmt::AttributedStmtClass:
3991 // As a general principle, C++11 attributes can be ignored without
3992 // any semantic impact.
3993 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3994 Case);
3995
3996 case Stmt::CaseStmtClass:
3997 case Stmt::DefaultStmtClass:
3998 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003999 }
4000}
4001
Richard Smithcc36f692011-12-22 02:22:31 +00004002/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4003/// default constructor. If so, we'll fold it whether or not it's marked as
4004/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4005/// so we need special handling.
4006static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004007 const CXXConstructorDecl *CD,
4008 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004009 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4010 return false;
4011
Richard Smith66e05fe2012-01-18 05:21:49 +00004012 // Value-initialization does not call a trivial default constructor, so such a
4013 // call is a core constant expression whether or not the constructor is
4014 // constexpr.
4015 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004016 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004017 // FIXME: If DiagDecl is an implicitly-declared special member function,
4018 // we should be much more explicit about why it's not constexpr.
4019 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4020 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4021 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004022 } else {
4023 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4024 }
4025 }
4026 return true;
4027}
4028
Richard Smith357362d2011-12-13 06:39:58 +00004029/// CheckConstexprFunction - Check that a function can be called in a constant
4030/// expression.
4031static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4032 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004033 const FunctionDecl *Definition,
4034 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004035 // Potential constant expressions can contain calls to declared, but not yet
4036 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004037 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004038 Declaration->isConstexpr())
4039 return false;
4040
Richard Smith0838f3a2013-05-14 05:18:44 +00004041 // Bail out with no diagnostic if the function declaration itself is invalid.
4042 // We will have produced a relevant diagnostic while parsing it.
4043 if (Declaration->isInvalidDecl())
4044 return false;
4045
Richard Smith357362d2011-12-13 06:39:58 +00004046 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004047 if (Definition && Definition->isConstexpr() &&
4048 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004049 return true;
4050
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004051 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004052 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004053
Richard Smith5179eb72016-06-28 19:03:57 +00004054 // If this function is not constexpr because it is an inherited
4055 // non-constexpr constructor, diagnose that directly.
4056 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4057 if (CD && CD->isInheritingConstructor()) {
4058 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4059 if (!Inherited->isConstexpr())
4060 DiagDecl = CD = Inherited;
4061 }
4062
4063 // FIXME: If DiagDecl is an implicitly-declared special member function
4064 // or an inheriting constructor, we should be much more explicit about why
4065 // it's not constexpr.
4066 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004067 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004068 << CD->getInheritedConstructor().getConstructor()->getParent();
4069 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004070 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004071 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004072 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4073 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004074 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004075 }
4076 return false;
4077}
4078
Richard Smithbe6dd812014-11-19 21:27:17 +00004079/// Determine if a class has any fields that might need to be copied by a
4080/// trivial copy or move operation.
4081static bool hasFields(const CXXRecordDecl *RD) {
4082 if (!RD || RD->isEmpty())
4083 return false;
4084 for (auto *FD : RD->fields()) {
4085 if (FD->isUnnamedBitfield())
4086 continue;
4087 return true;
4088 }
4089 for (auto &Base : RD->bases())
4090 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4091 return true;
4092 return false;
4093}
4094
Richard Smithd62306a2011-11-10 06:34:14 +00004095namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004096typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004097}
4098
4099/// EvaluateArgs - Evaluate the arguments to a function call.
4100static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4101 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004102 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004103 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004104 I != E; ++I) {
4105 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4106 // If we're checking for a potential constant expression, evaluate all
4107 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004108 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004109 return false;
4110 Success = false;
4111 }
4112 }
4113 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004114}
4115
Richard Smith254a73d2011-10-28 22:34:42 +00004116/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004117static bool HandleFunctionCall(SourceLocation CallLoc,
4118 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004119 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004120 EvalInfo &Info, APValue &Result,
4121 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004122 ArgVector ArgValues(Args.size());
4123 if (!EvaluateArgs(Args, ArgValues, Info))
4124 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004125
Richard Smith253c2a32012-01-27 01:14:48 +00004126 if (!Info.CheckCallLimit(CallLoc))
4127 return false;
4128
4129 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004130
4131 // For a trivial copy or move assignment, perform an APValue copy. This is
4132 // essential for unions, where the operations performed by the assignment
4133 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004134 //
4135 // Skip this for non-union classes with no fields; in that case, the defaulted
4136 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004137 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004138 if (MD && MD->isDefaulted() &&
4139 (MD->getParent()->isUnion() ||
4140 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004141 assert(This &&
4142 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4143 LValue RHS;
4144 RHS.setFrom(Info.Ctx, ArgValues[0]);
4145 APValue RHSValue;
4146 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4147 RHS, RHSValue))
4148 return false;
4149 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4150 RHSValue))
4151 return false;
4152 This->moveInto(Result);
4153 return true;
4154 }
4155
Richard Smith52a980a2015-08-28 02:43:42 +00004156 StmtResult Ret = {Result, ResultSlot};
4157 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004158 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004159 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004160 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004161 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004162 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004163 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004164}
4165
Richard Smithd62306a2011-11-10 06:34:14 +00004166/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004167static bool HandleConstructorCall(const Expr *E, const LValue &This,
4168 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004169 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004170 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004171 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004172 if (!Info.CheckCallLimit(CallLoc))
4173 return false;
4174
Richard Smith3607ffe2012-02-13 03:54:03 +00004175 const CXXRecordDecl *RD = Definition->getParent();
4176 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004177 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004178 return false;
4179 }
4180
Richard Smith5179eb72016-06-28 19:03:57 +00004181 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004182
Richard Smith52a980a2015-08-28 02:43:42 +00004183 // FIXME: Creating an APValue just to hold a nonexistent return value is
4184 // wasteful.
4185 APValue RetVal;
4186 StmtResult Ret = {RetVal, nullptr};
4187
Richard Smith5179eb72016-06-28 19:03:57 +00004188 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004189 if (Definition->isDelegatingConstructor()) {
4190 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004191 {
4192 FullExpressionRAII InitScope(Info);
4193 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4194 return false;
4195 }
Richard Smith52a980a2015-08-28 02:43:42 +00004196 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004197 }
4198
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004199 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004200 // essential for unions (or classes with anonymous union members), where the
4201 // operations performed by the constructor cannot be represented by
4202 // ctor-initializers.
4203 //
4204 // Skip this for empty non-union classes; we should not perform an
4205 // lvalue-to-rvalue conversion on them because their copy constructor does not
4206 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004207 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004208 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004209 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004210 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004211 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004212 return handleLValueToRValueConversion(
4213 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4214 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004215 }
4216
4217 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004218 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004219 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004220 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004221
John McCalld7bca762012-05-01 00:38:49 +00004222 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004223 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4224
Richard Smith08d6a2c2013-07-24 07:11:57 +00004225 // A scope for temporaries lifetime-extended by reference members.
4226 BlockScopeRAII LifetimeExtendedScope(Info);
4227
Richard Smith253c2a32012-01-27 01:14:48 +00004228 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004229 unsigned BasesSeen = 0;
4230#ifndef NDEBUG
4231 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4232#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004233 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004234 LValue Subobject = This;
4235 APValue *Value = &Result;
4236
4237 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004238 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004239 if (I->isBaseInitializer()) {
4240 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004241#ifndef NDEBUG
4242 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004243 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004244 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4245 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4246 "base class initializers not in expected order");
4247 ++BaseIt;
4248#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004249 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004250 BaseType->getAsCXXRecordDecl(), &Layout))
4251 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004252 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004253 } else if ((FD = I->getMember())) {
4254 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004255 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004256 if (RD->isUnion()) {
4257 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004258 Value = &Result.getUnionValue();
4259 } else {
4260 Value = &Result.getStructField(FD->getFieldIndex());
4261 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004262 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004263 // Walk the indirect field decl's chain to find the object to initialize,
4264 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004265 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004266 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004267 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4268 // Switch the union field if it differs. This happens if we had
4269 // preceding zero-initialization, and we're now initializing a union
4270 // subobject other than the first.
4271 // FIXME: In this case, the values of the other subobjects are
4272 // specified, since zero-initialization sets all padding bits to zero.
4273 if (Value->isUninit() ||
4274 (Value->isUnion() && Value->getUnionField() != FD)) {
4275 if (CD->isUnion())
4276 *Value = APValue(FD);
4277 else
4278 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004279 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004280 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004281 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004282 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004283 if (CD->isUnion())
4284 Value = &Value->getUnionValue();
4285 else
4286 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004287 }
Richard Smithd62306a2011-11-10 06:34:14 +00004288 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004289 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004290 }
Richard Smith253c2a32012-01-27 01:14:48 +00004291
Richard Smith08d6a2c2013-07-24 07:11:57 +00004292 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004293 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4294 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004295 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004296 // If we're checking for a potential constant expression, evaluate all
4297 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004298 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004299 return false;
4300 Success = false;
4301 }
Richard Smithd62306a2011-11-10 06:34:14 +00004302 }
4303
Richard Smithd9f663b2013-04-22 15:31:51 +00004304 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004305 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004306}
4307
Richard Smith5179eb72016-06-28 19:03:57 +00004308static bool HandleConstructorCall(const Expr *E, const LValue &This,
4309 ArrayRef<const Expr*> Args,
4310 const CXXConstructorDecl *Definition,
4311 EvalInfo &Info, APValue &Result) {
4312 ArgVector ArgValues(Args.size());
4313 if (!EvaluateArgs(Args, ArgValues, Info))
4314 return false;
4315
4316 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4317 Info, Result);
4318}
4319
Eli Friedman9a156e52008-11-12 09:44:48 +00004320//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004321// Generic Evaluation
4322//===----------------------------------------------------------------------===//
4323namespace {
4324
Aaron Ballman68af21c2014-01-03 19:26:43 +00004325template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004326class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004327 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004328private:
Richard Smith52a980a2015-08-28 02:43:42 +00004329 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004330 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004331 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004332 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004333 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004334 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004335 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004336
Richard Smith17100ba2012-02-16 02:46:34 +00004337 // Check whether a conditional operator with a non-constant condition is a
4338 // potential constant expression. If neither arm is a potential constant
4339 // expression, then the conditional operator is not either.
4340 template<typename ConditionalOperator>
4341 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004342 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004343
4344 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004345 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004346 {
Richard Smith17100ba2012-02-16 02:46:34 +00004347 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004348 StmtVisitorTy::Visit(E->getFalseExpr());
4349 if (Diag.empty())
4350 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004351 }
Richard Smith17100ba2012-02-16 02:46:34 +00004352
George Burgess IV8c892b52016-05-25 22:31:54 +00004353 {
4354 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004355 Diag.clear();
4356 StmtVisitorTy::Visit(E->getTrueExpr());
4357 if (Diag.empty())
4358 return;
4359 }
4360
4361 Error(E, diag::note_constexpr_conditional_never_const);
4362 }
4363
4364
4365 template<typename ConditionalOperator>
4366 bool HandleConditionalOperator(const ConditionalOperator *E) {
4367 bool BoolResult;
4368 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004369 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004370 CheckPotentialConstantConditional(E);
4371 return false;
4372 }
4373
4374 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4375 return StmtVisitorTy::Visit(EvalExpr);
4376 }
4377
Peter Collingbournee9200682011-05-13 03:29:01 +00004378protected:
4379 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004380 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004381 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4382
Richard Smith92b1ce02011-12-12 09:28:41 +00004383 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004384 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004385 }
4386
Aaron Ballman68af21c2014-01-03 19:26:43 +00004387 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004388
4389public:
4390 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4391
4392 EvalInfo &getEvalInfo() { return Info; }
4393
Richard Smithf57d8cb2011-12-09 22:58:01 +00004394 /// Report an evaluation error. This should only be called when an error is
4395 /// first discovered. When propagating an error, just return false.
4396 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004397 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004398 return false;
4399 }
4400 bool Error(const Expr *E) {
4401 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4402 }
4403
Aaron Ballman68af21c2014-01-03 19:26:43 +00004404 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004405 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004406 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004407 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004408 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004409 }
4410
Aaron Ballman68af21c2014-01-03 19:26:43 +00004411 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004412 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004413 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004414 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004415 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004416 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004417 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004418 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004419 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004420 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004421 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004422 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004423 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004424 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004425 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004426 // The initializer may not have been parsed yet, or might be erroneous.
4427 if (!E->getExpr())
4428 return Error(E);
4429 return StmtVisitorTy::Visit(E->getExpr());
4430 }
Richard Smith5894a912011-12-19 22:12:41 +00004431 // We cannot create any objects for which cleanups are required, so there is
4432 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004434 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004435
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004437 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4438 return static_cast<Derived*>(this)->VisitCastExpr(E);
4439 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004440 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004441 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4442 return static_cast<Derived*>(this)->VisitCastExpr(E);
4443 }
4444
Aaron Ballman68af21c2014-01-03 19:26:43 +00004445 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004446 switch (E->getOpcode()) {
4447 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004448 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004449
4450 case BO_Comma:
4451 VisitIgnoredValue(E->getLHS());
4452 return StmtVisitorTy::Visit(E->getRHS());
4453
4454 case BO_PtrMemD:
4455 case BO_PtrMemI: {
4456 LValue Obj;
4457 if (!HandleMemberPointerAccess(Info, E, Obj))
4458 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004459 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004460 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004461 return false;
4462 return DerivedSuccess(Result, E);
4463 }
4464 }
4465 }
4466
Aaron Ballman68af21c2014-01-03 19:26:43 +00004467 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004468 // Evaluate and cache the common expression. We treat it as a temporary,
4469 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004470 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004471 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004472 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004473
Richard Smith17100ba2012-02-16 02:46:34 +00004474 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004475 }
4476
Aaron Ballman68af21c2014-01-03 19:26:43 +00004477 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004478 bool IsBcpCall = false;
4479 // If the condition (ignoring parens) is a __builtin_constant_p call,
4480 // the result is a constant expression if it can be folded without
4481 // side-effects. This is an important GNU extension. See GCC PR38377
4482 // for discussion.
4483 if (const CallExpr *CallCE =
4484 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004485 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004486 IsBcpCall = true;
4487
4488 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4489 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004490 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004491 return false;
4492
Richard Smith6d4c6582013-11-05 22:18:15 +00004493 FoldConstant Fold(Info, IsBcpCall);
4494 if (!HandleConditionalOperator(E)) {
4495 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004496 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004497 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004498
4499 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004500 }
4501
Aaron Ballman68af21c2014-01-03 19:26:43 +00004502 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004503 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4504 return DerivedSuccess(*Value, E);
4505
4506 const Expr *Source = E->getSourceExpr();
4507 if (!Source)
4508 return Error(E);
4509 if (Source == E) { // sanity checking.
4510 assert(0 && "OpaqueValueExpr recursively refers to itself");
4511 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004512 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004513 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004514 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004515
Aaron Ballman68af21c2014-01-03 19:26:43 +00004516 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004517 APValue Result;
4518 if (!handleCallExpr(E, Result, nullptr))
4519 return false;
4520 return DerivedSuccess(Result, E);
4521 }
4522
4523 bool handleCallExpr(const CallExpr *E, APValue &Result,
4524 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004525 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004526 QualType CalleeType = Callee->getType();
4527
Craig Topper36250ad2014-05-12 05:36:57 +00004528 const FunctionDecl *FD = nullptr;
4529 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004530 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004531 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004532
Richard Smithe97cbd72011-11-11 04:05:33 +00004533 // Extract function decl and 'this' pointer from the callee.
4534 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004535 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004536 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4537 // Explicit bound member calls, such as x.f() or p->g();
4538 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004539 return false;
4540 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004541 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004542 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004543 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4544 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004545 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4546 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004547 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004548 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004549 return Error(Callee);
4550
4551 FD = dyn_cast<FunctionDecl>(Member);
4552 if (!FD)
4553 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004554 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004555 LValue Call;
4556 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004557 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004558
Richard Smitha8105bc2012-01-06 16:39:00 +00004559 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004560 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004561 FD = dyn_cast_or_null<FunctionDecl>(
4562 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004563 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004564 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004565 // Don't call function pointers which have been cast to some other type.
4566 // Per DR (no number yet), the caller and callee can differ in noexcept.
4567 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4568 CalleeType->getPointeeType(), FD->getType())) {
4569 return Error(E);
4570 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004571
4572 // Overloaded operator calls to member functions are represented as normal
4573 // calls with '*this' as the first argument.
4574 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4575 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004576 // FIXME: When selecting an implicit conversion for an overloaded
4577 // operator delete, we sometimes try to evaluate calls to conversion
4578 // operators without a 'this' parameter!
4579 if (Args.empty())
4580 return Error(E);
4581
Richard Smithe97cbd72011-11-11 04:05:33 +00004582 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4583 return false;
4584 This = &ThisVal;
4585 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004586 } else if (MD && MD->isLambdaStaticInvoker()) {
4587 // Map the static invoker for the lambda back to the call operator.
4588 // Conveniently, we don't have to slice out the 'this' argument (as is
4589 // being done for the non-static case), since a static member function
4590 // doesn't have an implicit argument passed in.
4591 const CXXRecordDecl *ClosureClass = MD->getParent();
4592 assert(
4593 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4594 "Number of captures must be zero for conversion to function-ptr");
4595
4596 const CXXMethodDecl *LambdaCallOp =
4597 ClosureClass->getLambdaCallOperator();
4598
4599 // Set 'FD', the function that will be called below, to the call
4600 // operator. If the closure object represents a generic lambda, find
4601 // the corresponding specialization of the call operator.
4602
4603 if (ClosureClass->isGenericLambda()) {
4604 assert(MD->isFunctionTemplateSpecialization() &&
4605 "A generic lambda's static-invoker function must be a "
4606 "template specialization");
4607 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4608 FunctionTemplateDecl *CallOpTemplate =
4609 LambdaCallOp->getDescribedFunctionTemplate();
4610 void *InsertPos = nullptr;
4611 FunctionDecl *CorrespondingCallOpSpecialization =
4612 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4613 assert(CorrespondingCallOpSpecialization &&
4614 "We must always have a function call operator specialization "
4615 "that corresponds to our static invoker specialization");
4616 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4617 } else
4618 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004619 }
4620
Faisal Valid92e7492017-01-08 18:56:11 +00004621
Richard Smithe97cbd72011-11-11 04:05:33 +00004622 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004623 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004624
Richard Smith47b34932012-02-01 02:39:43 +00004625 if (This && !This->checkSubobject(Info, E, CSK_This))
4626 return false;
4627
Richard Smith3607ffe2012-02-13 03:54:03 +00004628 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4629 // calls to such functions in constant expressions.
4630 if (This && !HasQualifier &&
4631 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4632 return Error(E, diag::note_constexpr_virtual_call);
4633
Craig Topper36250ad2014-05-12 05:36:57 +00004634 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004635 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004636
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004637 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004638 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4639 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004640 return false;
4641
Richard Smith52a980a2015-08-28 02:43:42 +00004642 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004643 }
4644
Aaron Ballman68af21c2014-01-03 19:26:43 +00004645 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004646 return StmtVisitorTy::Visit(E->getInitializer());
4647 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004648 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004649 if (E->getNumInits() == 0)
4650 return DerivedZeroInitialization(E);
4651 if (E->getNumInits() == 1)
4652 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004653 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004654 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004655 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004656 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004657 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004658 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004659 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004660 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004661 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004662 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004663 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004664
Richard Smithd62306a2011-11-10 06:34:14 +00004665 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004666 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004667 assert(!E->isArrow() && "missing call to bound member function?");
4668
Richard Smith2e312c82012-03-03 22:46:17 +00004669 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004670 if (!Evaluate(Val, Info, E->getBase()))
4671 return false;
4672
4673 QualType BaseTy = E->getBase()->getType();
4674
4675 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004676 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004677 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004678 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004679 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4680
Richard Smith3229b742013-05-05 21:17:10 +00004681 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004682 SubobjectDesignator Designator(BaseTy);
4683 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004684
Richard Smith3229b742013-05-05 21:17:10 +00004685 APValue Result;
4686 return extractSubobject(Info, E, Obj, Designator, Result) &&
4687 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004688 }
4689
Aaron Ballman68af21c2014-01-03 19:26:43 +00004690 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004691 switch (E->getCastKind()) {
4692 default:
4693 break;
4694
Richard Smitha23ab512013-05-23 00:30:41 +00004695 case CK_AtomicToNonAtomic: {
4696 APValue AtomicVal;
4697 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4698 return false;
4699 return DerivedSuccess(AtomicVal, E);
4700 }
4701
Richard Smith11562c52011-10-28 17:51:58 +00004702 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004703 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004704 return StmtVisitorTy::Visit(E->getSubExpr());
4705
4706 case CK_LValueToRValue: {
4707 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004708 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4709 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004710 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004711 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004712 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004713 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004714 return false;
4715 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004716 }
4717 }
4718
Richard Smithf57d8cb2011-12-09 22:58:01 +00004719 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004720 }
4721
Aaron Ballman68af21c2014-01-03 19:26:43 +00004722 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004723 return VisitUnaryPostIncDec(UO);
4724 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004725 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004726 return VisitUnaryPostIncDec(UO);
4727 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004728 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004729 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004730 return Error(UO);
4731
4732 LValue LVal;
4733 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4734 return false;
4735 APValue RVal;
4736 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4737 UO->isIncrementOp(), &RVal))
4738 return false;
4739 return DerivedSuccess(RVal, UO);
4740 }
4741
Aaron Ballman68af21c2014-01-03 19:26:43 +00004742 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004743 // We will have checked the full-expressions inside the statement expression
4744 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004745 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004746 return Error(E);
4747
Richard Smith08d6a2c2013-07-24 07:11:57 +00004748 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004749 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004750 if (CS->body_empty())
4751 return true;
4752
Richard Smith51f03172013-06-20 03:00:05 +00004753 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4754 BE = CS->body_end();
4755 /**/; ++BI) {
4756 if (BI + 1 == BE) {
4757 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4758 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004759 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004760 diag::note_constexpr_stmt_expr_unsupported);
4761 return false;
4762 }
4763 return this->Visit(FinalExpr);
4764 }
4765
4766 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004767 StmtResult Result = { ReturnValue, nullptr };
4768 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004769 if (ESR != ESR_Succeeded) {
4770 // FIXME: If the statement-expression terminated due to 'return',
4771 // 'break', or 'continue', it would be nice to propagate that to
4772 // the outer statement evaluation rather than bailing out.
4773 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004774 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004775 diag::note_constexpr_stmt_expr_unsupported);
4776 return false;
4777 }
4778 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004779
4780 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004781 }
4782
Richard Smith4a678122011-10-24 18:44:57 +00004783 /// Visit a value which is evaluated, but whose value is ignored.
4784 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004785 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004786 }
David Majnemere9807b22016-02-26 04:23:19 +00004787
4788 /// Potentially visit a MemberExpr's base expression.
4789 void VisitIgnoredBaseExpression(const Expr *E) {
4790 // While MSVC doesn't evaluate the base expression, it does diagnose the
4791 // presence of side-effecting behavior.
4792 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4793 return;
4794 VisitIgnoredValue(E);
4795 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004796};
4797
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004798}
Peter Collingbournee9200682011-05-13 03:29:01 +00004799
4800//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004801// Common base class for lvalue and temporary evaluation.
4802//===----------------------------------------------------------------------===//
4803namespace {
4804template<class Derived>
4805class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004806 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004807protected:
4808 LValue &Result;
4809 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004810 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004811
4812 bool Success(APValue::LValueBase B) {
4813 Result.set(B);
4814 return true;
4815 }
4816
4817public:
4818 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4819 ExprEvaluatorBaseTy(Info), Result(Result) {}
4820
Richard Smith2e312c82012-03-03 22:46:17 +00004821 bool Success(const APValue &V, const Expr *E) {
4822 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004823 return true;
4824 }
Richard Smith027bf112011-11-17 22:56:20 +00004825
Richard Smith027bf112011-11-17 22:56:20 +00004826 bool VisitMemberExpr(const MemberExpr *E) {
4827 // Handle non-static data members.
4828 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004829 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004830 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004831 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004832 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004833 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004834 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004835 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004836 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004837 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004838 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004839 BaseTy = E->getBase()->getType();
4840 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004841 if (!EvalOK) {
4842 if (!this->Info.allowInvalidBaseExpr())
4843 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004844 Result.setInvalid(E);
4845 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004846 }
Richard Smith027bf112011-11-17 22:56:20 +00004847
Richard Smith1b78b3d2012-01-25 22:15:11 +00004848 const ValueDecl *MD = E->getMemberDecl();
4849 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4850 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4851 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4852 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004853 if (!HandleLValueMember(this->Info, E, Result, FD))
4854 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004855 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004856 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4857 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004858 } else
4859 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004860
Richard Smith1b78b3d2012-01-25 22:15:11 +00004861 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004862 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004863 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004864 RefValue))
4865 return false;
4866 return Success(RefValue, E);
4867 }
4868 return true;
4869 }
4870
4871 bool VisitBinaryOperator(const BinaryOperator *E) {
4872 switch (E->getOpcode()) {
4873 default:
4874 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4875
4876 case BO_PtrMemD:
4877 case BO_PtrMemI:
4878 return HandleMemberPointerAccess(this->Info, E, Result);
4879 }
4880 }
4881
4882 bool VisitCastExpr(const CastExpr *E) {
4883 switch (E->getCastKind()) {
4884 default:
4885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4886
4887 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004888 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004889 if (!this->Visit(E->getSubExpr()))
4890 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004891
4892 // Now figure out the necessary offset to add to the base LV to get from
4893 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004894 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4895 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004896 }
4897 }
4898};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004899}
Richard Smith027bf112011-11-17 22:56:20 +00004900
4901//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004902// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004903//
4904// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4905// function designators (in C), decl references to void objects (in C), and
4906// temporaries (if building with -Wno-address-of-temporary).
4907//
4908// LValue evaluation produces values comprising a base expression of one of the
4909// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004910// - Declarations
4911// * VarDecl
4912// * FunctionDecl
4913// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004914// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004915// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004916// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004917// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004918// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004919// * ObjCEncodeExpr
4920// * AddrLabelExpr
4921// * BlockExpr
4922// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004923// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004924// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004925// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004926// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4927// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004928// * A MaterializeTemporaryExpr that has static storage duration, with no
4929// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004930// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004931//===----------------------------------------------------------------------===//
4932namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004933class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004934 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004935public:
Richard Smith027bf112011-11-17 22:56:20 +00004936 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4937 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004938
Richard Smith11562c52011-10-28 17:51:58 +00004939 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004940 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004941
Peter Collingbournee9200682011-05-13 03:29:01 +00004942 bool VisitDeclRefExpr(const DeclRefExpr *E);
4943 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004944 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004945 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4946 bool VisitMemberExpr(const MemberExpr *E);
4947 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4948 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004949 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004950 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004951 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4952 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004953 bool VisitUnaryReal(const UnaryOperator *E);
4954 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004955 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4956 return VisitUnaryPreIncDec(UO);
4957 }
4958 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4959 return VisitUnaryPreIncDec(UO);
4960 }
Richard Smith3229b742013-05-05 21:17:10 +00004961 bool VisitBinAssign(const BinaryOperator *BO);
4962 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004963
Peter Collingbournee9200682011-05-13 03:29:01 +00004964 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004965 switch (E->getCastKind()) {
4966 default:
Richard Smith027bf112011-11-17 22:56:20 +00004967 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004968
Eli Friedmance3e02a2011-10-11 00:13:24 +00004969 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004970 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004971 if (!Visit(E->getSubExpr()))
4972 return false;
4973 Result.Designator.setInvalid();
4974 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004975
Richard Smith027bf112011-11-17 22:56:20 +00004976 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004977 if (!Visit(E->getSubExpr()))
4978 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004979 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004980 }
4981 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004982};
4983} // end anonymous namespace
4984
Richard Smith11562c52011-10-28 17:51:58 +00004985/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004986/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004987/// * function designators in C, and
4988/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004989/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004990static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4991 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004992 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004993 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004994}
4995
Peter Collingbournee9200682011-05-13 03:29:01 +00004996bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004998 return Success(FD);
4999 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005000 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005001 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005002 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005003 return Error(E);
5004}
Richard Smith733237d2011-10-24 23:14:33 +00005005
Faisal Vali0528a312016-11-13 06:09:16 +00005006
Richard Smith11562c52011-10-28 17:51:58 +00005007bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00005008 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005009 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5010 // Only if a local variable was declared in the function currently being
5011 // evaluated, do we expect to be able to find its value in the current
5012 // frame. (Otherwise it was likely declared in an enclosing context and
5013 // could either have a valid evaluatable value (for e.g. a constexpr
5014 // variable) or be ill-formed (and trigger an appropriate evaluation
5015 // diagnostic)).
5016 if (Info.CurrentCall->Callee &&
5017 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5018 Frame = Info.CurrentCall;
5019 }
5020 }
Richard Smith3229b742013-05-05 21:17:10 +00005021
Richard Smithfec09922011-11-01 16:57:24 +00005022 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005023 if (Frame) {
5024 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005025 return true;
5026 }
Richard Smithce40ad62011-11-12 22:28:03 +00005027 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005028 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005029
Richard Smith3229b742013-05-05 21:17:10 +00005030 APValue *V;
5031 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005032 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005033 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005034 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005035 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005036 return false;
5037 }
Richard Smith3229b742013-05-05 21:17:10 +00005038 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005039}
5040
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005041bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5042 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005043 // Walk through the expression to find the materialized temporary itself.
5044 SmallVector<const Expr *, 2> CommaLHSs;
5045 SmallVector<SubobjectAdjustment, 2> Adjustments;
5046 const Expr *Inner = E->GetTemporaryExpr()->
5047 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005048
Richard Smith84401042013-06-03 05:03:02 +00005049 // If we passed any comma operators, evaluate their LHSs.
5050 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5051 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5052 return false;
5053
Richard Smithe6c01442013-06-05 00:46:14 +00005054 // A materialized temporary with static storage duration can appear within the
5055 // result of a constant expression evaluation, so we need to preserve its
5056 // value for use outside this evaluation.
5057 APValue *Value;
5058 if (E->getStorageDuration() == SD_Static) {
5059 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005060 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005061 Result.set(E);
5062 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005063 Value = &Info.CurrentCall->
5064 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005065 Result.set(E, Info.CurrentCall->Index);
5066 }
5067
Richard Smithea4ad5d2013-06-06 08:19:16 +00005068 QualType Type = Inner->getType();
5069
Richard Smith84401042013-06-03 05:03:02 +00005070 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005071 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5072 (E->getStorageDuration() == SD_Static &&
5073 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5074 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005075 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005076 }
Richard Smith84401042013-06-03 05:03:02 +00005077
5078 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005079 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5080 --I;
5081 switch (Adjustments[I].Kind) {
5082 case SubobjectAdjustment::DerivedToBaseAdjustment:
5083 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5084 Type, Result))
5085 return false;
5086 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5087 break;
5088
5089 case SubobjectAdjustment::FieldAdjustment:
5090 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5091 return false;
5092 Type = Adjustments[I].Field->getType();
5093 break;
5094
5095 case SubobjectAdjustment::MemberPointerAdjustment:
5096 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5097 Adjustments[I].Ptr.RHS))
5098 return false;
5099 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5100 break;
5101 }
5102 }
5103
5104 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005105}
5106
Peter Collingbournee9200682011-05-13 03:29:01 +00005107bool
5108LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005109 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5110 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005111 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5112 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005113 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005114}
5115
Richard Smith6e525142011-12-27 12:18:28 +00005116bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005117 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005118 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005119
Faisal Valie690b7a2016-07-02 22:34:24 +00005120 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005121 << E->getExprOperand()->getType()
5122 << E->getExprOperand()->getSourceRange();
5123 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005124}
5125
Francois Pichet0066db92012-04-16 04:08:35 +00005126bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5127 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005128}
Francois Pichet0066db92012-04-16 04:08:35 +00005129
Peter Collingbournee9200682011-05-13 03:29:01 +00005130bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005131 // Handle static data members.
5132 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005133 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005134 return VisitVarDecl(E, VD);
5135 }
5136
Richard Smith254a73d2011-10-28 22:34:42 +00005137 // Handle static member functions.
5138 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5139 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005140 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005141 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005142 }
5143 }
5144
Richard Smithd62306a2011-11-10 06:34:14 +00005145 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005146 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005147}
5148
Peter Collingbournee9200682011-05-13 03:29:01 +00005149bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005150 // FIXME: Deal with vectors as array subscript bases.
5151 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005152 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005153
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005154 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005155 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005156
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005157 APSInt Index;
5158 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005159 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005160
Richard Smith642a2362017-01-30 23:30:26 +00005161 int64_t Offset;
5162 if (!getExtValue(Info, E, Index, Offset))
5163 return false;
5164 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Offset);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005165}
Eli Friedman9a156e52008-11-12 09:44:48 +00005166
Peter Collingbournee9200682011-05-13 03:29:01 +00005167bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005168 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005169}
5170
Richard Smith66c96992012-02-18 22:04:06 +00005171bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5172 if (!Visit(E->getSubExpr()))
5173 return false;
5174 // __real is a no-op on scalar lvalues.
5175 if (E->getSubExpr()->getType()->isAnyComplexType())
5176 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5177 return true;
5178}
5179
5180bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5181 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5182 "lvalue __imag__ on scalar?");
5183 if (!Visit(E->getSubExpr()))
5184 return false;
5185 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5186 return true;
5187}
5188
Richard Smith243ef902013-05-05 23:31:59 +00005189bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005190 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005191 return Error(UO);
5192
5193 if (!this->Visit(UO->getSubExpr()))
5194 return false;
5195
Richard Smith243ef902013-05-05 23:31:59 +00005196 return handleIncDec(
5197 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005198 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005199}
5200
5201bool LValueExprEvaluator::VisitCompoundAssignOperator(
5202 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005203 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005204 return Error(CAO);
5205
Richard Smith3229b742013-05-05 21:17:10 +00005206 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005207
5208 // The overall lvalue result is the result of evaluating the LHS.
5209 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005210 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005211 Evaluate(RHS, this->Info, CAO->getRHS());
5212 return false;
5213 }
5214
Richard Smith3229b742013-05-05 21:17:10 +00005215 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5216 return false;
5217
Richard Smith43e77732013-05-07 04:50:00 +00005218 return handleCompoundAssignment(
5219 this->Info, CAO,
5220 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5221 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005222}
5223
5224bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005225 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005226 return Error(E);
5227
Richard Smith3229b742013-05-05 21:17:10 +00005228 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005229
5230 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005231 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005232 Evaluate(NewVal, this->Info, E->getRHS());
5233 return false;
5234 }
5235
Richard Smith3229b742013-05-05 21:17:10 +00005236 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5237 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005238
5239 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005240 NewVal);
5241}
5242
Eli Friedman9a156e52008-11-12 09:44:48 +00005243//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005244// Pointer Evaluation
5245//===----------------------------------------------------------------------===//
5246
George Burgess IVe3763372016-12-22 02:50:20 +00005247/// \brief Attempts to compute the number of bytes available at the pointer
5248/// returned by a function with the alloc_size attribute. Returns true if we
5249/// were successful. Places an unsigned number into `Result`.
5250///
5251/// This expects the given CallExpr to be a call to a function with an
5252/// alloc_size attribute.
5253static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5254 const CallExpr *Call,
5255 llvm::APInt &Result) {
5256 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5257
5258 // alloc_size args are 1-indexed, 0 means not present.
5259 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5260 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5261 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5262 if (Call->getNumArgs() <= SizeArgNo)
5263 return false;
5264
5265 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5266 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5267 return false;
5268 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5269 return false;
5270 Into = Into.zextOrSelf(BitsInSizeT);
5271 return true;
5272 };
5273
5274 APSInt SizeOfElem;
5275 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5276 return false;
5277
5278 if (!AllocSize->getNumElemsParam()) {
5279 Result = std::move(SizeOfElem);
5280 return true;
5281 }
5282
5283 APSInt NumberOfElems;
5284 // Argument numbers start at 1
5285 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5286 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5287 return false;
5288
5289 bool Overflow;
5290 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5291 if (Overflow)
5292 return false;
5293
5294 Result = std::move(BytesAvailable);
5295 return true;
5296}
5297
5298/// \brief Convenience function. LVal's base must be a call to an alloc_size
5299/// function.
5300static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5301 const LValue &LVal,
5302 llvm::APInt &Result) {
5303 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5304 "Can't get the size of a non alloc_size function");
5305 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5306 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5307 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5308}
5309
5310/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5311/// a function with the alloc_size attribute. If it was possible to do so, this
5312/// function will return true, make Result's Base point to said function call,
5313/// and mark Result's Base as invalid.
5314static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5315 LValue &Result) {
5316 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5317 return false;
5318
5319 // Because we do no form of static analysis, we only support const variables.
5320 //
5321 // Additionally, we can't support parameters, nor can we support static
5322 // variables (in the latter case, use-before-assign isn't UB; in the former,
5323 // we have no clue what they'll be assigned to).
5324 const auto *VD =
5325 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5326 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5327 return false;
5328
5329 const Expr *Init = VD->getAnyInitializer();
5330 if (!Init)
5331 return false;
5332
5333 const Expr *E = Init->IgnoreParens();
5334 if (!tryUnwrapAllocSizeCall(E))
5335 return false;
5336
5337 // Store E instead of E unwrapped so that the type of the LValue's base is
5338 // what the user wanted.
5339 Result.setInvalid(E);
5340
5341 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5342 Result.addUnsizedArray(Info, Pointee);
5343 return true;
5344}
5345
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005346namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005347class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005348 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005349 LValue &Result;
5350
Peter Collingbournee9200682011-05-13 03:29:01 +00005351 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005352 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005353 return true;
5354 }
George Burgess IVe3763372016-12-22 02:50:20 +00005355
5356 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005357public:
Mike Stump11289f42009-09-09 15:08:12 +00005358
John McCall45d55e42010-05-07 21:00:08 +00005359 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005360 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005361
Richard Smith2e312c82012-03-03 22:46:17 +00005362 bool Success(const APValue &V, const Expr *E) {
5363 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005364 return true;
5365 }
Richard Smithfddd3842011-12-30 21:15:51 +00005366 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005367 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5368 Result.set((Expr*)nullptr, 0, false, true, Offset);
5369 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005370 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005371
John McCall45d55e42010-05-07 21:00:08 +00005372 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005373 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005374 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005375 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005376 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005377 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005378 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005379 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005380 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005381 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005382 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005383 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005384 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005385 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005386 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005387 }
Richard Smithd62306a2011-11-10 06:34:14 +00005388 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005389 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005390 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005391 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005392 if (!Info.CurrentCall->This) {
5393 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005394 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005395 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005396 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005397 return false;
5398 }
Richard Smithd62306a2011-11-10 06:34:14 +00005399 Result = *Info.CurrentCall->This;
5400 return true;
5401 }
John McCallc07a0c72011-02-17 10:25:35 +00005402
Eli Friedman449fe542009-03-23 04:56:01 +00005403 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005404};
Chris Lattner05706e882008-07-11 18:11:29 +00005405} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005406
John McCall45d55e42010-05-07 21:00:08 +00005407static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005408 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005409 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005410}
5411
John McCall45d55e42010-05-07 21:00:08 +00005412bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005413 if (E->getOpcode() != BO_Add &&
5414 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005415 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005416
Chris Lattner05706e882008-07-11 18:11:29 +00005417 const Expr *PExp = E->getLHS();
5418 const Expr *IExp = E->getRHS();
5419 if (IExp->getType()->isPointerType())
5420 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005421
Richard Smith253c2a32012-01-27 01:14:48 +00005422 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005423 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005424 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005425
John McCall45d55e42010-05-07 21:00:08 +00005426 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005427 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005428 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005429
Richard Smith642a2362017-01-30 23:30:26 +00005430 int64_t AdditionalOffset;
5431 if (!getExtValue(Info, E, Offset, AdditionalOffset))
5432 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00005433 if (E->getOpcode() == BO_Sub)
5434 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005435
Ted Kremenek28831752012-08-23 20:46:57 +00005436 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005437 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5438 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005439}
Eli Friedman9a156e52008-11-12 09:44:48 +00005440
John McCall45d55e42010-05-07 21:00:08 +00005441bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5442 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005443}
Mike Stump11289f42009-09-09 15:08:12 +00005444
Peter Collingbournee9200682011-05-13 03:29:01 +00005445bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5446 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005447
Eli Friedman847a2bc2009-12-27 05:43:15 +00005448 switch (E->getCastKind()) {
5449 default:
5450 break;
5451
John McCalle3027922010-08-25 11:45:40 +00005452 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005453 case CK_CPointerToObjCPointerCast:
5454 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005455 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005456 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005457 if (!Visit(SubExpr))
5458 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005459 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5460 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5461 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005462 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005463 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005464 if (SubExpr->getType()->isVoidPointerType())
5465 CCEDiag(E, diag::note_constexpr_invalid_cast)
5466 << 3 << SubExpr->getType();
5467 else
5468 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5469 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005470 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5471 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005472 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005473
Anders Carlsson18275092010-10-31 20:41:46 +00005474 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005475 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005476 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005477 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005478 if (!Result.Base && Result.Offset.isZero())
5479 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005480
Richard Smithd62306a2011-11-10 06:34:14 +00005481 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005482 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005483 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5484 castAs<PointerType>()->getPointeeType(),
5485 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005486
Richard Smith027bf112011-11-17 22:56:20 +00005487 case CK_BaseToDerived:
5488 if (!Visit(E->getSubExpr()))
5489 return false;
5490 if (!Result.Base && Result.Offset.isZero())
5491 return true;
5492 return HandleBaseToDerivedCast(Info, E, Result);
5493
Richard Smith0b0a0b62011-10-29 20:57:55 +00005494 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005495 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005496 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005497
John McCalle3027922010-08-25 11:45:40 +00005498 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005499 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5500
Richard Smith2e312c82012-03-03 22:46:17 +00005501 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005502 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005503 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005504
John McCall45d55e42010-05-07 21:00:08 +00005505 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005506 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5507 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005508 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005509 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005510 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005511 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005512 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005513 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005514 return true;
5515 } else {
5516 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005517 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005518 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005519 }
5520 }
John McCalle3027922010-08-25 11:45:40 +00005521 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005522 if (SubExpr->isGLValue()) {
5523 if (!EvaluateLValue(SubExpr, Result, Info))
5524 return false;
5525 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005526 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005527 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005528 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005529 return false;
5530 }
Richard Smith96e0c102011-11-04 02:25:55 +00005531 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005532 if (const ConstantArrayType *CAT
5533 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5534 Result.addArray(Info, E, CAT);
5535 else
5536 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005537 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005538
John McCalle3027922010-08-25 11:45:40 +00005539 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005540 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVe3763372016-12-22 02:50:20 +00005541
5542 case CK_LValueToRValue: {
5543 LValue LVal;
5544 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5545 return false;
5546
5547 APValue RVal;
5548 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5549 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5550 LVal, RVal))
5551 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5552 return Success(RVal, E);
5553 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005554 }
5555
Richard Smith11562c52011-10-28 17:51:58 +00005556 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005557}
Chris Lattner05706e882008-07-11 18:11:29 +00005558
Hal Finkel0dd05d42014-10-03 17:18:37 +00005559static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5560 // C++ [expr.alignof]p3:
5561 // When alignof is applied to a reference type, the result is the
5562 // alignment of the referenced type.
5563 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5564 T = Ref->getPointeeType();
5565
5566 // __alignof is defined to return the preferred alignment.
5567 return Info.Ctx.toCharUnitsFromBits(
5568 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5569}
5570
5571static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5572 E = E->IgnoreParens();
5573
5574 // The kinds of expressions that we have special-case logic here for
5575 // should be kept up to date with the special checks for those
5576 // expressions in Sema.
5577
5578 // alignof decl is always accepted, even if it doesn't make sense: we default
5579 // to 1 in those cases.
5580 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5581 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5582 /*RefAsPointee*/true);
5583
5584 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5585 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5586 /*RefAsPointee*/true);
5587
5588 return GetAlignOfType(Info, E->getType());
5589}
5590
George Burgess IVe3763372016-12-22 02:50:20 +00005591// To be clear: this happily visits unsupported builtins. Better name welcomed.
5592bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5593 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5594 return true;
5595
5596 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5597 return false;
5598
5599 Result.setInvalid(E);
5600 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5601 Result.addUnsizedArray(Info, PointeeTy);
5602 return true;
5603}
5604
Peter Collingbournee9200682011-05-13 03:29:01 +00005605bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005606 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005607 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005608
Richard Smith6328cbd2016-11-16 00:57:23 +00005609 if (unsigned BuiltinOp = E->getBuiltinCallee())
5610 return VisitBuiltinCallExpr(E, BuiltinOp);
5611
George Burgess IVe3763372016-12-22 02:50:20 +00005612 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005613}
5614
5615bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5616 unsigned BuiltinOp) {
5617 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005618 case Builtin::BI__builtin_addressof:
5619 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005620 case Builtin::BI__builtin_assume_aligned: {
5621 // We need to be very careful here because: if the pointer does not have the
5622 // asserted alignment, then the behavior is undefined, and undefined
5623 // behavior is non-constant.
5624 if (!EvaluatePointer(E->getArg(0), Result, Info))
5625 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005626
Hal Finkel0dd05d42014-10-03 17:18:37 +00005627 LValue OffsetResult(Result);
5628 APSInt Alignment;
5629 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5630 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005631 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005632
5633 if (E->getNumArgs() > 2) {
5634 APSInt Offset;
5635 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5636 return false;
5637
Richard Smith642a2362017-01-30 23:30:26 +00005638 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005639 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5640 }
5641
5642 // If there is a base object, then it must have the correct alignment.
5643 if (OffsetResult.Base) {
5644 CharUnits BaseAlignment;
5645 if (const ValueDecl *VD =
5646 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5647 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5648 } else {
5649 BaseAlignment =
5650 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5651 }
5652
5653 if (BaseAlignment < Align) {
5654 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005655 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005656 CCEDiag(E->getArg(0),
5657 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005658 << (unsigned)BaseAlignment.getQuantity()
5659 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005660 return false;
5661 }
5662 }
5663
5664 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005665 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005666 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005667
Richard Smith642a2362017-01-30 23:30:26 +00005668 (OffsetResult.Base
5669 ? CCEDiag(E->getArg(0),
5670 diag::note_constexpr_baa_insufficient_alignment) << 1
5671 : CCEDiag(E->getArg(0),
5672 diag::note_constexpr_baa_value_insufficient_alignment))
5673 << (int)OffsetResult.Offset.getQuantity()
5674 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005675 return false;
5676 }
5677
5678 return true;
5679 }
Richard Smithe9507952016-11-12 01:39:56 +00005680
5681 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005682 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005683 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005684 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005685 if (Info.getLangOpts().CPlusPlus11)
5686 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5687 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005688 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005689 else
5690 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5691 // Fall through.
5692 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005693 case Builtin::BI__builtin_wcschr:
5694 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005695 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005696 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005697 if (!Visit(E->getArg(0)))
5698 return false;
5699 APSInt Desired;
5700 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5701 return false;
5702 uint64_t MaxLength = uint64_t(-1);
5703 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005704 BuiltinOp != Builtin::BIwcschr &&
5705 BuiltinOp != Builtin::BI__builtin_strchr &&
5706 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005707 APSInt N;
5708 if (!EvaluateInteger(E->getArg(2), N, Info))
5709 return false;
5710 MaxLength = N.getExtValue();
5711 }
5712
Richard Smith8110c9d2016-11-29 19:45:17 +00005713 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005714
Richard Smith8110c9d2016-11-29 19:45:17 +00005715 // Figure out what value we're actually looking for (after converting to
5716 // the corresponding unsigned type if necessary).
5717 uint64_t DesiredVal;
5718 bool StopAtNull = false;
5719 switch (BuiltinOp) {
5720 case Builtin::BIstrchr:
5721 case Builtin::BI__builtin_strchr:
5722 // strchr compares directly to the passed integer, and therefore
5723 // always fails if given an int that is not a char.
5724 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5725 E->getArg(1)->getType(),
5726 Desired),
5727 Desired))
5728 return ZeroInitialization(E);
5729 StopAtNull = true;
5730 // Fall through.
5731 case Builtin::BImemchr:
5732 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005733 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005734 // memchr compares by converting both sides to unsigned char. That's also
5735 // correct for strchr if we get this far (to cope with plain char being
5736 // unsigned in the strchr case).
5737 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5738 break;
Richard Smithe9507952016-11-12 01:39:56 +00005739
Richard Smith8110c9d2016-11-29 19:45:17 +00005740 case Builtin::BIwcschr:
5741 case Builtin::BI__builtin_wcschr:
5742 StopAtNull = true;
5743 // Fall through.
5744 case Builtin::BIwmemchr:
5745 case Builtin::BI__builtin_wmemchr:
5746 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5747 DesiredVal = Desired.getZExtValue();
5748 break;
5749 }
Richard Smithe9507952016-11-12 01:39:56 +00005750
5751 for (; MaxLength; --MaxLength) {
5752 APValue Char;
5753 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5754 !Char.isInt())
5755 return false;
5756 if (Char.getInt().getZExtValue() == DesiredVal)
5757 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005758 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005759 break;
5760 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5761 return false;
5762 }
5763 // Not found: return nullptr.
5764 return ZeroInitialization(E);
5765 }
5766
Richard Smith6cbd65d2013-07-11 02:27:57 +00005767 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005768 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005769 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005770}
Chris Lattner05706e882008-07-11 18:11:29 +00005771
5772//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005773// Member Pointer Evaluation
5774//===----------------------------------------------------------------------===//
5775
5776namespace {
5777class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005778 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005779 MemberPtr &Result;
5780
5781 bool Success(const ValueDecl *D) {
5782 Result = MemberPtr(D);
5783 return true;
5784 }
5785public:
5786
5787 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5788 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5789
Richard Smith2e312c82012-03-03 22:46:17 +00005790 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005791 Result.setFrom(V);
5792 return true;
5793 }
Richard Smithfddd3842011-12-30 21:15:51 +00005794 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005795 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005796 }
5797
5798 bool VisitCastExpr(const CastExpr *E);
5799 bool VisitUnaryAddrOf(const UnaryOperator *E);
5800};
5801} // end anonymous namespace
5802
5803static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5804 EvalInfo &Info) {
5805 assert(E->isRValue() && E->getType()->isMemberPointerType());
5806 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5807}
5808
5809bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5810 switch (E->getCastKind()) {
5811 default:
5812 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5813
5814 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005815 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005816 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005817
5818 case CK_BaseToDerivedMemberPointer: {
5819 if (!Visit(E->getSubExpr()))
5820 return false;
5821 if (E->path_empty())
5822 return true;
5823 // Base-to-derived member pointer casts store the path in derived-to-base
5824 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5825 // the wrong end of the derived->base arc, so stagger the path by one class.
5826 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5827 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5828 PathI != PathE; ++PathI) {
5829 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5830 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5831 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005832 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005833 }
5834 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5835 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005836 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005837 return true;
5838 }
5839
5840 case CK_DerivedToBaseMemberPointer:
5841 if (!Visit(E->getSubExpr()))
5842 return false;
5843 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5844 PathE = E->path_end(); PathI != PathE; ++PathI) {
5845 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5846 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5847 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005848 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005849 }
5850 return true;
5851 }
5852}
5853
5854bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5855 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5856 // member can be formed.
5857 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5858}
5859
5860//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005861// Record Evaluation
5862//===----------------------------------------------------------------------===//
5863
5864namespace {
5865 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005866 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005867 const LValue &This;
5868 APValue &Result;
5869 public:
5870
5871 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5872 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5873
Richard Smith2e312c82012-03-03 22:46:17 +00005874 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005875 Result = V;
5876 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005877 }
Richard Smithb8348f52016-05-12 22:16:28 +00005878 bool ZeroInitialization(const Expr *E) {
5879 return ZeroInitialization(E, E->getType());
5880 }
5881 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005882
Richard Smith52a980a2015-08-28 02:43:42 +00005883 bool VisitCallExpr(const CallExpr *E) {
5884 return handleCallExpr(E, Result, &This);
5885 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005886 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005887 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005888 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5889 return VisitCXXConstructExpr(E, E->getType());
5890 }
Faisal Valic72a08c2017-01-09 03:02:53 +00005891 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00005892 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005893 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005894 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005895 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005896}
Richard Smithd62306a2011-11-10 06:34:14 +00005897
Richard Smithfddd3842011-12-30 21:15:51 +00005898/// Perform zero-initialization on an object of non-union class type.
5899/// C++11 [dcl.init]p5:
5900/// To zero-initialize an object or reference of type T means:
5901/// [...]
5902/// -- if T is a (possibly cv-qualified) non-union class type,
5903/// each non-static data member and each base-class subobject is
5904/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005905static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5906 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005907 const LValue &This, APValue &Result) {
5908 assert(!RD->isUnion() && "Expected non-union class type");
5909 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5910 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005911 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005912
John McCalld7bca762012-05-01 00:38:49 +00005913 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005914 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5915
5916 if (CD) {
5917 unsigned Index = 0;
5918 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005919 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005920 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5921 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005922 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5923 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005924 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005925 Result.getStructBase(Index)))
5926 return false;
5927 }
5928 }
5929
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005930 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005931 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005932 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005933 continue;
5934
5935 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005936 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005937 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005938
David Blaikie2d7c57e2012-04-30 02:36:29 +00005939 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005940 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005941 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005942 return false;
5943 }
5944
5945 return true;
5946}
5947
Richard Smithb8348f52016-05-12 22:16:28 +00005948bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5949 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005950 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005951 if (RD->isUnion()) {
5952 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5953 // object's first non-static named data member is zero-initialized
5954 RecordDecl::field_iterator I = RD->field_begin();
5955 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005956 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005957 return true;
5958 }
5959
5960 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005961 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005962 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005963 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005964 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005965 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005966 }
5967
Richard Smith5d108602012-02-17 00:44:16 +00005968 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005969 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005970 return false;
5971 }
5972
Richard Smitha8105bc2012-01-06 16:39:00 +00005973 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005974}
5975
Richard Smithe97cbd72011-11-11 04:05:33 +00005976bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5977 switch (E->getCastKind()) {
5978 default:
5979 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5980
5981 case CK_ConstructorConversion:
5982 return Visit(E->getSubExpr());
5983
5984 case CK_DerivedToBase:
5985 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005986 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005987 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005988 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005989 if (!DerivedObject.isStruct())
5990 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005991
5992 // Derived-to-base rvalue conversion: just slice off the derived part.
5993 APValue *Value = &DerivedObject;
5994 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5995 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5996 PathE = E->path_end(); PathI != PathE; ++PathI) {
5997 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5998 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5999 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6000 RD = Base;
6001 }
6002 Result = *Value;
6003 return true;
6004 }
6005 }
6006}
6007
Richard Smithd62306a2011-11-10 06:34:14 +00006008bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006009 if (E->isTransparent())
6010 return Visit(E->getInit(0));
6011
Richard Smithd62306a2011-11-10 06:34:14 +00006012 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006013 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006014 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6015
6016 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006017 const FieldDecl *Field = E->getInitializedFieldInUnion();
6018 Result = APValue(Field);
6019 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006020 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006021
6022 // If the initializer list for a union does not contain any elements, the
6023 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006024 // FIXME: The element should be initialized from an initializer list.
6025 // Is this difference ever observable for initializer lists which
6026 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006027 ImplicitValueInitExpr VIE(Field->getType());
6028 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6029
Richard Smithd62306a2011-11-10 06:34:14 +00006030 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006031 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6032 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006033
6034 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6035 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6036 isa<CXXDefaultInitExpr>(InitExpr));
6037
Richard Smithb228a862012-02-15 02:18:13 +00006038 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006039 }
6040
Richard Smith872307e2016-03-08 22:17:41 +00006041 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006042 if (Result.isUninit())
6043 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6044 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006045 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006046 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006047
6048 // Initialize base classes.
6049 if (CXXRD) {
6050 for (const auto &Base : CXXRD->bases()) {
6051 assert(ElementNo < E->getNumInits() && "missing init for base class");
6052 const Expr *Init = E->getInit(ElementNo);
6053
6054 LValue Subobject = This;
6055 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6056 return false;
6057
6058 APValue &FieldVal = Result.getStructBase(ElementNo);
6059 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006060 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006061 return false;
6062 Success = false;
6063 }
6064 ++ElementNo;
6065 }
6066 }
6067
6068 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006069 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006070 // Anonymous bit-fields are not considered members of the class for
6071 // purposes of aggregate initialization.
6072 if (Field->isUnnamedBitfield())
6073 continue;
6074
6075 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006076
Richard Smith253c2a32012-01-27 01:14:48 +00006077 bool HaveInit = ElementNo < E->getNumInits();
6078
6079 // FIXME: Diagnostics here should point to the end of the initializer
6080 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006081 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006082 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006083 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006084
6085 // Perform an implicit value-initialization for members beyond the end of
6086 // the initializer list.
6087 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006088 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006089
Richard Smith852c9db2013-04-20 22:23:05 +00006090 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6091 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6092 isa<CXXDefaultInitExpr>(Init));
6093
Richard Smith49ca8aa2013-08-06 07:09:20 +00006094 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6095 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6096 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006097 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006098 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006099 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006100 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006101 }
6102 }
6103
Richard Smith253c2a32012-01-27 01:14:48 +00006104 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006105}
6106
Richard Smithb8348f52016-05-12 22:16:28 +00006107bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6108 QualType T) {
6109 // Note that E's type is not necessarily the type of our class here; we might
6110 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006111 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006112 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6113
Richard Smithfddd3842011-12-30 21:15:51 +00006114 bool ZeroInit = E->requiresZeroInitialization();
6115 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006116 // If we've already performed zero-initialization, we're already done.
6117 if (!Result.isUninit())
6118 return true;
6119
Richard Smithda3f4fd2014-03-05 23:32:50 +00006120 // We can get here in two different ways:
6121 // 1) We're performing value-initialization, and should zero-initialize
6122 // the object, or
6123 // 2) We're performing default-initialization of an object with a trivial
6124 // constexpr default constructor, in which case we should start the
6125 // lifetimes of all the base subobjects (there can be no data member
6126 // subobjects in this case) per [basic.life]p1.
6127 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006128 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006129 }
6130
Craig Topper36250ad2014-05-12 05:36:57 +00006131 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006132 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006133
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006134 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006135 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006136
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006137 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006138 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006139 if (const MaterializeTemporaryExpr *ME
6140 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6141 return Visit(ME->GetTemporaryExpr());
6142
Richard Smithb8348f52016-05-12 22:16:28 +00006143 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006144 return false;
6145
Craig Topper5fc8fc22014-08-27 06:28:36 +00006146 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006147 return HandleConstructorCall(E, This, Args,
6148 cast<CXXConstructorDecl>(Definition), Info,
6149 Result);
6150}
6151
6152bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6153 const CXXInheritedCtorInitExpr *E) {
6154 if (!Info.CurrentCall) {
6155 assert(Info.checkingPotentialConstantExpression());
6156 return false;
6157 }
6158
6159 const CXXConstructorDecl *FD = E->getConstructor();
6160 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6161 return false;
6162
6163 const FunctionDecl *Definition = nullptr;
6164 auto Body = FD->getBody(Definition);
6165
6166 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6167 return false;
6168
6169 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006170 cast<CXXConstructorDecl>(Definition), Info,
6171 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006172}
6173
Richard Smithcc1b96d2013-06-12 22:31:48 +00006174bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6175 const CXXStdInitializerListExpr *E) {
6176 const ConstantArrayType *ArrayType =
6177 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6178
6179 LValue Array;
6180 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6181 return false;
6182
6183 // Get a pointer to the first element of the array.
6184 Array.addArray(Info, E, ArrayType);
6185
6186 // FIXME: Perform the checks on the field types in SemaInit.
6187 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6188 RecordDecl::field_iterator Field = Record->field_begin();
6189 if (Field == Record->field_end())
6190 return Error(E);
6191
6192 // Start pointer.
6193 if (!Field->getType()->isPointerType() ||
6194 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6195 ArrayType->getElementType()))
6196 return Error(E);
6197
6198 // FIXME: What if the initializer_list type has base classes, etc?
6199 Result = APValue(APValue::UninitStruct(), 0, 2);
6200 Array.moveInto(Result.getStructField(0));
6201
6202 if (++Field == Record->field_end())
6203 return Error(E);
6204
6205 if (Field->getType()->isPointerType() &&
6206 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6207 ArrayType->getElementType())) {
6208 // End pointer.
6209 if (!HandleLValueArrayAdjustment(Info, E, Array,
6210 ArrayType->getElementType(),
6211 ArrayType->getSize().getZExtValue()))
6212 return false;
6213 Array.moveInto(Result.getStructField(1));
6214 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6215 // Length.
6216 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6217 else
6218 return Error(E);
6219
6220 if (++Field != Record->field_end())
6221 return Error(E);
6222
6223 return true;
6224}
6225
Faisal Valic72a08c2017-01-09 03:02:53 +00006226bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6227 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6228 if (ClosureClass->isInvalidDecl()) return false;
6229
6230 if (Info.checkingPotentialConstantExpression()) return true;
6231 if (E->capture_size()) {
6232 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6233 << "can not evaluate lambda expressions with captures";
6234 return false;
6235 }
6236 // FIXME: Implement captures.
6237 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6238 return true;
6239}
6240
Richard Smithd62306a2011-11-10 06:34:14 +00006241static bool EvaluateRecord(const Expr *E, const LValue &This,
6242 APValue &Result, EvalInfo &Info) {
6243 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006244 "can't evaluate expression as a record rvalue");
6245 return RecordExprEvaluator(Info, This, Result).Visit(E);
6246}
6247
6248//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006249// Temporary Evaluation
6250//
6251// Temporaries are represented in the AST as rvalues, but generally behave like
6252// lvalues. The full-object of which the temporary is a subobject is implicitly
6253// materialized so that a reference can bind to it.
6254//===----------------------------------------------------------------------===//
6255namespace {
6256class TemporaryExprEvaluator
6257 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6258public:
6259 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6260 LValueExprEvaluatorBaseTy(Info, Result) {}
6261
6262 /// Visit an expression which constructs the value of this temporary.
6263 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006264 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006265 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6266 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006267 }
6268
6269 bool VisitCastExpr(const CastExpr *E) {
6270 switch (E->getCastKind()) {
6271 default:
6272 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6273
6274 case CK_ConstructorConversion:
6275 return VisitConstructExpr(E->getSubExpr());
6276 }
6277 }
6278 bool VisitInitListExpr(const InitListExpr *E) {
6279 return VisitConstructExpr(E);
6280 }
6281 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6282 return VisitConstructExpr(E);
6283 }
6284 bool VisitCallExpr(const CallExpr *E) {
6285 return VisitConstructExpr(E);
6286 }
Richard Smith513955c2014-12-17 19:24:30 +00006287 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6288 return VisitConstructExpr(E);
6289 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006290 bool VisitLambdaExpr(const LambdaExpr *E) {
6291 return VisitConstructExpr(E);
6292 }
Richard Smith027bf112011-11-17 22:56:20 +00006293};
6294} // end anonymous namespace
6295
6296/// Evaluate an expression of record type as a temporary.
6297static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006298 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006299 return TemporaryExprEvaluator(Info, Result).Visit(E);
6300}
6301
6302//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006303// Vector Evaluation
6304//===----------------------------------------------------------------------===//
6305
6306namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006307 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006308 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006309 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006310 public:
Mike Stump11289f42009-09-09 15:08:12 +00006311
Richard Smith2d406342011-10-22 21:10:00 +00006312 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6313 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006314
Craig Topper9798b932015-09-29 04:30:05 +00006315 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006316 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6317 // FIXME: remove this APValue copy.
6318 Result = APValue(V.data(), V.size());
6319 return true;
6320 }
Richard Smith2e312c82012-03-03 22:46:17 +00006321 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006322 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006323 Result = V;
6324 return true;
6325 }
Richard Smithfddd3842011-12-30 21:15:51 +00006326 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006327
Richard Smith2d406342011-10-22 21:10:00 +00006328 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006329 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006330 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006331 bool VisitInitListExpr(const InitListExpr *E);
6332 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006333 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006334 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006335 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006336 };
6337} // end anonymous namespace
6338
6339static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006340 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006341 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006342}
6343
George Burgess IV533ff002015-12-11 00:23:35 +00006344bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006345 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006346 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006347
Richard Smith161f09a2011-12-06 22:44:34 +00006348 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006349 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006350
Eli Friedmanc757de22011-03-25 00:43:55 +00006351 switch (E->getCastKind()) {
6352 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006353 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006354 if (SETy->isIntegerType()) {
6355 APSInt IntResult;
6356 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006357 return false;
6358 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006359 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006360 APFloat FloatResult(0.0);
6361 if (!EvaluateFloat(SE, FloatResult, Info))
6362 return false;
6363 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006364 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006365 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006366 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006367
6368 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006369 SmallVector<APValue, 4> Elts(NElts, Val);
6370 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006371 }
Eli Friedman803acb32011-12-22 03:51:45 +00006372 case CK_BitCast: {
6373 // Evaluate the operand into an APInt we can extract from.
6374 llvm::APInt SValInt;
6375 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6376 return false;
6377 // Extract the elements
6378 QualType EltTy = VTy->getElementType();
6379 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6380 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6381 SmallVector<APValue, 4> Elts;
6382 if (EltTy->isRealFloatingType()) {
6383 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006384 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006385 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006386 FloatEltSize = 80;
6387 for (unsigned i = 0; i < NElts; i++) {
6388 llvm::APInt Elt;
6389 if (BigEndian)
6390 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6391 else
6392 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006393 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006394 }
6395 } else if (EltTy->isIntegerType()) {
6396 for (unsigned i = 0; i < NElts; i++) {
6397 llvm::APInt Elt;
6398 if (BigEndian)
6399 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6400 else
6401 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6402 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6403 }
6404 } else {
6405 return Error(E);
6406 }
6407 return Success(Elts, E);
6408 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006409 default:
Richard Smith11562c52011-10-28 17:51:58 +00006410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006411 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006412}
6413
Richard Smith2d406342011-10-22 21:10:00 +00006414bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006415VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006416 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006417 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006418 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006419
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006420 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006421 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006422
Eli Friedmanb9c71292012-01-03 23:24:20 +00006423 // The number of initializers can be less than the number of
6424 // vector elements. For OpenCL, this can be due to nested vector
6425 // initialization. For GCC compatibility, missing trailing elements
6426 // should be initialized with zeroes.
6427 unsigned CountInits = 0, CountElts = 0;
6428 while (CountElts < NumElements) {
6429 // Handle nested vector initialization.
6430 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006431 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006432 APValue v;
6433 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6434 return Error(E);
6435 unsigned vlen = v.getVectorLength();
6436 for (unsigned j = 0; j < vlen; j++)
6437 Elements.push_back(v.getVectorElt(j));
6438 CountElts += vlen;
6439 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006440 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006441 if (CountInits < NumInits) {
6442 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006443 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006444 } else // trailing integer zero.
6445 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6446 Elements.push_back(APValue(sInt));
6447 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006448 } else {
6449 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006450 if (CountInits < NumInits) {
6451 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006452 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006453 } else // trailing float zero.
6454 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6455 Elements.push_back(APValue(f));
6456 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006457 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006458 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006459 }
Richard Smith2d406342011-10-22 21:10:00 +00006460 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006461}
6462
Richard Smith2d406342011-10-22 21:10:00 +00006463bool
Richard Smithfddd3842011-12-30 21:15:51 +00006464VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006465 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006466 QualType EltTy = VT->getElementType();
6467 APValue ZeroElement;
6468 if (EltTy->isIntegerType())
6469 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6470 else
6471 ZeroElement =
6472 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6473
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006474 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006475 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006476}
6477
Richard Smith2d406342011-10-22 21:10:00 +00006478bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006479 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006480 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006481}
6482
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006483//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006484// Array Evaluation
6485//===----------------------------------------------------------------------===//
6486
6487namespace {
6488 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006489 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006490 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006491 APValue &Result;
6492 public:
6493
Richard Smithd62306a2011-11-10 06:34:14 +00006494 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6495 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006496
6497 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006498 assert((V.isArray() || V.isLValue()) &&
6499 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006500 Result = V;
6501 return true;
6502 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006503
Richard Smithfddd3842011-12-30 21:15:51 +00006504 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006505 const ConstantArrayType *CAT =
6506 Info.Ctx.getAsConstantArrayType(E->getType());
6507 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006508 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006509
6510 Result = APValue(APValue::UninitArray(), 0,
6511 CAT->getSize().getZExtValue());
6512 if (!Result.hasArrayFiller()) return true;
6513
Richard Smithfddd3842011-12-30 21:15:51 +00006514 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006515 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006516 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006517 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006518 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006519 }
6520
Richard Smith52a980a2015-08-28 02:43:42 +00006521 bool VisitCallExpr(const CallExpr *E) {
6522 return handleCallExpr(E, Result, &This);
6523 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006524 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006525 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006526 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006527 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6528 const LValue &Subobject,
6529 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006530 };
6531} // end anonymous namespace
6532
Richard Smithd62306a2011-11-10 06:34:14 +00006533static bool EvaluateArray(const Expr *E, const LValue &This,
6534 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006535 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006536 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006537}
6538
6539bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6540 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6541 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006542 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006543
Richard Smithca2cfbf2011-12-22 01:07:19 +00006544 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6545 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006546 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006547 LValue LV;
6548 if (!EvaluateLValue(E->getInit(0), LV, Info))
6549 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006550 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006551 LV.moveInto(Val);
6552 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006553 }
6554
Richard Smith253c2a32012-01-27 01:14:48 +00006555 bool Success = true;
6556
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006557 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6558 "zero-initialized array shouldn't have any initialized elts");
6559 APValue Filler;
6560 if (Result.isArray() && Result.hasArrayFiller())
6561 Filler = Result.getArrayFiller();
6562
Richard Smith9543c5e2013-04-22 14:44:29 +00006563 unsigned NumEltsToInit = E->getNumInits();
6564 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006565 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006566
6567 // If the initializer might depend on the array index, run it for each
6568 // array element. For now, just whitelist non-class value-initialization.
6569 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6570 NumEltsToInit = NumElts;
6571
6572 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006573
6574 // If the array was previously zero-initialized, preserve the
6575 // zero-initialized values.
6576 if (!Filler.isUninit()) {
6577 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6578 Result.getArrayInitializedElt(I) = Filler;
6579 if (Result.hasArrayFiller())
6580 Result.getArrayFiller() = Filler;
6581 }
6582
Richard Smithd62306a2011-11-10 06:34:14 +00006583 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006584 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006585 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6586 const Expr *Init =
6587 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006588 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006589 Info, Subobject, Init) ||
6590 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006591 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006592 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006593 return false;
6594 Success = false;
6595 }
Richard Smithd62306a2011-11-10 06:34:14 +00006596 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006597
Richard Smith9543c5e2013-04-22 14:44:29 +00006598 if (!Result.hasArrayFiller())
6599 return Success;
6600
6601 // If we get here, we have a trivial filler, which we can just evaluate
6602 // once and splat over the rest of the array elements.
6603 assert(FillerExpr && "no array filler for incomplete init list");
6604 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6605 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006606}
6607
Richard Smith410306b2016-12-12 02:53:20 +00006608bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6609 if (E->getCommonExpr() &&
6610 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6611 Info, E->getCommonExpr()->getSourceExpr()))
6612 return false;
6613
6614 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6615
6616 uint64_t Elements = CAT->getSize().getZExtValue();
6617 Result = APValue(APValue::UninitArray(), Elements, Elements);
6618
6619 LValue Subobject = This;
6620 Subobject.addArray(Info, E, CAT);
6621
6622 bool Success = true;
6623 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6624 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6625 Info, Subobject, E->getSubExpr()) ||
6626 !HandleLValueArrayAdjustment(Info, E, Subobject,
6627 CAT->getElementType(), 1)) {
6628 if (!Info.noteFailure())
6629 return false;
6630 Success = false;
6631 }
6632 }
6633
6634 return Success;
6635}
6636
Richard Smith027bf112011-11-17 22:56:20 +00006637bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006638 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6639}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006640
Richard Smith9543c5e2013-04-22 14:44:29 +00006641bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6642 const LValue &Subobject,
6643 APValue *Value,
6644 QualType Type) {
6645 bool HadZeroInit = !Value->isUninit();
6646
6647 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6648 unsigned N = CAT->getSize().getZExtValue();
6649
6650 // Preserve the array filler if we had prior zero-initialization.
6651 APValue Filler =
6652 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6653 : APValue();
6654
6655 *Value = APValue(APValue::UninitArray(), N, N);
6656
6657 if (HadZeroInit)
6658 for (unsigned I = 0; I != N; ++I)
6659 Value->getArrayInitializedElt(I) = Filler;
6660
6661 // Initialize the elements.
6662 LValue ArrayElt = Subobject;
6663 ArrayElt.addArray(Info, E, CAT);
6664 for (unsigned I = 0; I != N; ++I)
6665 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6666 CAT->getElementType()) ||
6667 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6668 CAT->getElementType(), 1))
6669 return false;
6670
6671 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006672 }
Richard Smith027bf112011-11-17 22:56:20 +00006673
Richard Smith9543c5e2013-04-22 14:44:29 +00006674 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006675 return Error(E);
6676
Richard Smithb8348f52016-05-12 22:16:28 +00006677 return RecordExprEvaluator(Info, Subobject, *Value)
6678 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006679}
6680
Richard Smithf3e9e432011-11-07 09:22:26 +00006681//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006682// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006683//
6684// As a GNU extension, we support casting pointers to sufficiently-wide integer
6685// types and back in constant folding. Integer values are thus represented
6686// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006687//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006688
6689namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006690class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006691 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006692 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006693public:
Richard Smith2e312c82012-03-03 22:46:17 +00006694 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006695 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006696
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006697 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006698 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006699 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006700 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006701 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006702 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006703 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006704 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006705 return true;
6706 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006707 bool Success(const llvm::APSInt &SI, const Expr *E) {
6708 return Success(SI, E, Result);
6709 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006710
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006711 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006712 assert(E->getType()->isIntegralOrEnumerationType() &&
6713 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006714 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006715 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006716 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006717 Result.getInt().setIsUnsigned(
6718 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006719 return true;
6720 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006721 bool Success(const llvm::APInt &I, const Expr *E) {
6722 return Success(I, E, Result);
6723 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006724
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006725 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006726 assert(E->getType()->isIntegralOrEnumerationType() &&
6727 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006728 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006729 return true;
6730 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006731 bool Success(uint64_t Value, const Expr *E) {
6732 return Success(Value, E, Result);
6733 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006734
Ken Dyckdbc01912011-03-11 02:13:43 +00006735 bool Success(CharUnits Size, const Expr *E) {
6736 return Success(Size.getQuantity(), E);
6737 }
6738
Richard Smith2e312c82012-03-03 22:46:17 +00006739 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006740 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006741 Result = V;
6742 return true;
6743 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006744 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006745 }
Mike Stump11289f42009-09-09 15:08:12 +00006746
Richard Smithfddd3842011-12-30 21:15:51 +00006747 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006748
Peter Collingbournee9200682011-05-13 03:29:01 +00006749 //===--------------------------------------------------------------------===//
6750 // Visitor Methods
6751 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006752
Chris Lattner7174bf32008-07-12 00:38:25 +00006753 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006754 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006755 }
6756 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006757 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006758 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006759
6760 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6761 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006762 if (CheckReferencedDecl(E, E->getDecl()))
6763 return true;
6764
6765 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006766 }
6767 bool VisitMemberExpr(const MemberExpr *E) {
6768 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006769 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006770 return true;
6771 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006772
6773 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006774 }
6775
Peter Collingbournee9200682011-05-13 03:29:01 +00006776 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006777 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006778 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006779 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006780 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006781
Peter Collingbournee9200682011-05-13 03:29:01 +00006782 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006783 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006784
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006785 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006786 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006787 }
Mike Stump11289f42009-09-09 15:08:12 +00006788
Ted Kremeneke65b0862012-03-06 20:05:56 +00006789 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6790 return Success(E->getValue(), E);
6791 }
Richard Smith410306b2016-12-12 02:53:20 +00006792
6793 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6794 if (Info.ArrayInitIndex == uint64_t(-1)) {
6795 // We were asked to evaluate this subexpression independent of the
6796 // enclosing ArrayInitLoopExpr. We can't do that.
6797 Info.FFDiag(E);
6798 return false;
6799 }
6800 return Success(Info.ArrayInitIndex, E);
6801 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006802
Richard Smith4ce706a2011-10-11 21:43:33 +00006803 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006804 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006805 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006806 }
6807
Douglas Gregor29c42f22012-02-24 07:38:34 +00006808 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6809 return Success(E->getValue(), E);
6810 }
6811
John Wiegley6242b6a2011-04-28 00:16:57 +00006812 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6813 return Success(E->getValue(), E);
6814 }
6815
John Wiegleyf9f65842011-04-25 06:54:41 +00006816 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6817 return Success(E->getValue(), E);
6818 }
6819
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006820 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006821 bool VisitUnaryImag(const UnaryOperator *E);
6822
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006823 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006824 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006825
Eli Friedman4e7a2412009-02-27 04:45:43 +00006826 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006827};
Chris Lattner05706e882008-07-11 18:11:29 +00006828} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006829
Richard Smith11562c52011-10-28 17:51:58 +00006830/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6831/// produce either the integer value or a pointer.
6832///
6833/// GCC has a heinous extension which folds casts between pointer types and
6834/// pointer-sized integral types. We support this by allowing the evaluation of
6835/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6836/// Some simple arithmetic on such values is supported (they are treated much
6837/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006838static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006839 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006840 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006841 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006842}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006843
Richard Smithf57d8cb2011-12-09 22:58:01 +00006844static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006845 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006846 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006847 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006848 if (!Val.isInt()) {
6849 // FIXME: It would be better to produce the diagnostic for casting
6850 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006851 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006852 return false;
6853 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006854 Result = Val.getInt();
6855 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006856}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006857
Richard Smithf57d8cb2011-12-09 22:58:01 +00006858/// Check whether the given declaration can be directly converted to an integral
6859/// rvalue. If not, no diagnostic is produced; there are other things we can
6860/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006861bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006862 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006863 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006864 // Check for signedness/width mismatches between E type and ECD value.
6865 bool SameSign = (ECD->getInitVal().isSigned()
6866 == E->getType()->isSignedIntegerOrEnumerationType());
6867 bool SameWidth = (ECD->getInitVal().getBitWidth()
6868 == Info.Ctx.getIntWidth(E->getType()));
6869 if (SameSign && SameWidth)
6870 return Success(ECD->getInitVal(), E);
6871 else {
6872 // Get rid of mismatch (otherwise Success assertions will fail)
6873 // by computing a new value matching the type of E.
6874 llvm::APSInt Val = ECD->getInitVal();
6875 if (!SameSign)
6876 Val.setIsSigned(!ECD->getInitVal().isSigned());
6877 if (!SameWidth)
6878 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6879 return Success(Val, E);
6880 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006882 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006883}
6884
Chris Lattner86ee2862008-10-06 06:40:35 +00006885/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6886/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006887static int EvaluateBuiltinClassifyType(const CallExpr *E,
6888 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006889 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006890 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006891 enum gcc_type_class {
6892 no_type_class = -1,
6893 void_type_class, integer_type_class, char_type_class,
6894 enumeral_type_class, boolean_type_class,
6895 pointer_type_class, reference_type_class, offset_type_class,
6896 real_type_class, complex_type_class,
6897 function_type_class, method_type_class,
6898 record_type_class, union_type_class,
6899 array_type_class, string_type_class,
6900 lang_type_class
6901 };
Mike Stump11289f42009-09-09 15:08:12 +00006902
6903 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006904 // ideal, however it is what gcc does.
6905 if (E->getNumArgs() == 0)
6906 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006907
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006908 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6909 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6910
6911 switch (CanTy->getTypeClass()) {
6912#define TYPE(ID, BASE)
6913#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6914#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6915#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6916#include "clang/AST/TypeNodes.def"
6917 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6918
6919 case Type::Builtin:
6920 switch (BT->getKind()) {
6921#define BUILTIN_TYPE(ID, SINGLETON_ID)
6922#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6923#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6924#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6925#include "clang/AST/BuiltinTypes.def"
6926 case BuiltinType::Void:
6927 return void_type_class;
6928
6929 case BuiltinType::Bool:
6930 return boolean_type_class;
6931
6932 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6933 case BuiltinType::UChar:
6934 case BuiltinType::UShort:
6935 case BuiltinType::UInt:
6936 case BuiltinType::ULong:
6937 case BuiltinType::ULongLong:
6938 case BuiltinType::UInt128:
6939 return integer_type_class;
6940
6941 case BuiltinType::NullPtr:
6942 return pointer_type_class;
6943
6944 case BuiltinType::WChar_U:
6945 case BuiltinType::Char16:
6946 case BuiltinType::Char32:
6947 case BuiltinType::ObjCId:
6948 case BuiltinType::ObjCClass:
6949 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006950#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6951 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006952#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006953 case BuiltinType::OCLSampler:
6954 case BuiltinType::OCLEvent:
6955 case BuiltinType::OCLClkEvent:
6956 case BuiltinType::OCLQueue:
6957 case BuiltinType::OCLNDRange:
6958 case BuiltinType::OCLReserveID:
6959 case BuiltinType::Dependent:
6960 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6961 };
6962
6963 case Type::Enum:
6964 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6965 break;
6966
6967 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006968 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006969 break;
6970
6971 case Type::MemberPointer:
6972 if (CanTy->isMemberDataPointerType())
6973 return offset_type_class;
6974 else {
6975 // We expect member pointers to be either data or function pointers,
6976 // nothing else.
6977 assert(CanTy->isMemberFunctionPointerType());
6978 return method_type_class;
6979 }
6980
6981 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006982 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006983
6984 case Type::FunctionNoProto:
6985 case Type::FunctionProto:
6986 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6987
6988 case Type::Record:
6989 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6990 switch (RT->getDecl()->getTagKind()) {
6991 case TagTypeKind::TTK_Struct:
6992 case TagTypeKind::TTK_Class:
6993 case TagTypeKind::TTK_Interface:
6994 return record_type_class;
6995
6996 case TagTypeKind::TTK_Enum:
6997 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6998
6999 case TagTypeKind::TTK_Union:
7000 return union_type_class;
7001 }
7002 }
David Blaikie83d382b2011-09-23 05:06:16 +00007003 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007004
7005 case Type::ConstantArray:
7006 case Type::VariableArray:
7007 case Type::IncompleteArray:
7008 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7009
7010 case Type::BlockPointer:
7011 case Type::LValueReference:
7012 case Type::RValueReference:
7013 case Type::Vector:
7014 case Type::ExtVector:
7015 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007016 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007017 case Type::ObjCObject:
7018 case Type::ObjCInterface:
7019 case Type::ObjCObjectPointer:
7020 case Type::Pipe:
7021 case Type::Atomic:
7022 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7023 }
7024
7025 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007026}
7027
Richard Smith5fab0c92011-12-28 19:48:30 +00007028/// EvaluateBuiltinConstantPForLValue - Determine the result of
7029/// __builtin_constant_p when applied to the given lvalue.
7030///
7031/// An lvalue is only "constant" if it is a pointer or reference to the first
7032/// character of a string literal.
7033template<typename LValue>
7034static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007035 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007036 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7037}
7038
7039/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7040/// GCC as we can manage.
7041static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7042 QualType ArgType = Arg->getType();
7043
7044 // __builtin_constant_p always has one operand. The rules which gcc follows
7045 // are not precisely documented, but are as follows:
7046 //
7047 // - If the operand is of integral, floating, complex or enumeration type,
7048 // and can be folded to a known value of that type, it returns 1.
7049 // - If the operand and can be folded to a pointer to the first character
7050 // of a string literal (or such a pointer cast to an integral type), it
7051 // returns 1.
7052 //
7053 // Otherwise, it returns 0.
7054 //
7055 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7056 // its support for this does not currently work.
7057 if (ArgType->isIntegralOrEnumerationType()) {
7058 Expr::EvalResult Result;
7059 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7060 return false;
7061
7062 APValue &V = Result.Val;
7063 if (V.getKind() == APValue::Int)
7064 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007065 if (V.getKind() == APValue::LValue)
7066 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007067 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7068 return Arg->isEvaluatable(Ctx);
7069 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7070 LValue LV;
7071 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007072 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007073 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7074 : EvaluatePointer(Arg, LV, Info)) &&
7075 !Status.HasSideEffects)
7076 return EvaluateBuiltinConstantPForLValue(LV);
7077 }
7078
7079 // Anything else isn't considered to be sufficiently constant.
7080 return false;
7081}
7082
John McCall95007602010-05-10 23:27:23 +00007083/// Retrieves the "underlying object type" of the given expression,
7084/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007085static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007086 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7087 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007088 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007089 } else if (const Expr *E = B.get<const Expr*>()) {
7090 if (isa<CompoundLiteralExpr>(E))
7091 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007092 }
7093
7094 return QualType();
7095}
7096
George Burgess IV3a03fab2015-09-04 21:28:13 +00007097/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007098/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007099/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007100/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7101///
7102/// Always returns an RValue with a pointer representation.
7103static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7104 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7105
7106 auto *NoParens = E->IgnoreParens();
7107 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007108 if (Cast == nullptr)
7109 return NoParens;
7110
7111 // We only conservatively allow a few kinds of casts, because this code is
7112 // inherently a simple solution that seeks to support the common case.
7113 auto CastKind = Cast->getCastKind();
7114 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7115 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007116 return NoParens;
7117
7118 auto *SubExpr = Cast->getSubExpr();
7119 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7120 return NoParens;
7121 return ignorePointerCastsAndParens(SubExpr);
7122}
7123
George Burgess IVa51c4072015-10-16 01:49:01 +00007124/// Checks to see if the given LValue's Designator is at the end of the LValue's
7125/// record layout. e.g.
7126/// struct { struct { int a, b; } fst, snd; } obj;
7127/// obj.fst // no
7128/// obj.snd // yes
7129/// obj.fst.a // no
7130/// obj.fst.b // no
7131/// obj.snd.a // no
7132/// obj.snd.b // yes
7133///
7134/// Please note: this function is specialized for how __builtin_object_size
7135/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007136///
7137/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007138static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7139 assert(!LVal.Designator.Invalid);
7140
George Burgess IV4168d752016-06-27 19:40:41 +00007141 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7142 const RecordDecl *Parent = FD->getParent();
7143 Invalid = Parent->isInvalidDecl();
7144 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007145 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007146 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007147 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7148 };
7149
7150 auto &Base = LVal.getLValueBase();
7151 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7152 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007153 bool Invalid;
7154 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7155 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007156 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007157 for (auto *FD : IFD->chain()) {
7158 bool Invalid;
7159 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7160 return Invalid;
7161 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007162 }
7163 }
7164
George Burgess IVe3763372016-12-22 02:50:20 +00007165 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007166 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007167 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7168 assert(isBaseAnAllocSizeCall(Base) &&
7169 "Unsized array in non-alloc_size call?");
7170 // If this is an alloc_size base, we should ignore the initial array index
7171 ++I;
7172 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7173 }
7174
7175 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7176 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007177 if (BaseType->isArrayType()) {
7178 // Because __builtin_object_size treats arrays as objects, we can ignore
7179 // the index iff this is the last array in the Designator.
7180 if (I + 1 == E)
7181 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007182 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7183 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007184 if (Index + 1 != CAT->getSize())
7185 return false;
7186 BaseType = CAT->getElementType();
7187 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007188 const auto *CT = BaseType->castAs<ComplexType>();
7189 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007190 if (Index != 1)
7191 return false;
7192 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007193 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007194 bool Invalid;
7195 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7196 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007197 BaseType = FD->getType();
7198 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007199 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007200 return false;
7201 }
7202 }
7203 return true;
7204}
7205
George Burgess IVe3763372016-12-22 02:50:20 +00007206/// Tests to see if the LValue has a user-specified designator (that isn't
7207/// necessarily valid). Note that this always returns 'true' if the LValue has
7208/// an unsized array as its first designator entry, because there's currently no
7209/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007210static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007211 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007212 return false;
7213
George Burgess IVe3763372016-12-22 02:50:20 +00007214 if (!LVal.Designator.Entries.empty())
7215 return LVal.Designator.isMostDerivedAnUnsizedArray();
7216
George Burgess IVa51c4072015-10-16 01:49:01 +00007217 if (!LVal.InvalidBase)
7218 return true;
7219
George Burgess IVe3763372016-12-22 02:50:20 +00007220 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7221 // the LValueBase.
7222 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7223 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007224}
7225
George Burgess IVe3763372016-12-22 02:50:20 +00007226/// Attempts to detect a user writing into a piece of memory that's impossible
7227/// to figure out the size of by just using types.
7228static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7229 const SubobjectDesignator &Designator = LVal.Designator;
7230 // Notes:
7231 // - Users can only write off of the end when we have an invalid base. Invalid
7232 // bases imply we don't know where the memory came from.
7233 // - We used to be a bit more aggressive here; we'd only be conservative if
7234 // the array at the end was flexible, or if it had 0 or 1 elements. This
7235 // broke some common standard library extensions (PR30346), but was
7236 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7237 // with some sort of whitelist. OTOH, it seems that GCC is always
7238 // conservative with the last element in structs (if it's an array), so our
7239 // current behavior is more compatible than a whitelisting approach would
7240 // be.
7241 return LVal.InvalidBase &&
7242 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7243 Designator.MostDerivedIsArrayElement &&
7244 isDesignatorAtObjectEnd(Ctx, LVal);
7245}
7246
7247/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7248/// Fails if the conversion would cause loss of precision.
7249static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7250 CharUnits &Result) {
7251 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7252 if (Int.ugt(CharUnitsMax))
7253 return false;
7254 Result = CharUnits::fromQuantity(Int.getZExtValue());
7255 return true;
7256}
7257
7258/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7259/// determine how many bytes exist from the beginning of the object to either
7260/// the end of the current subobject, or the end of the object itself, depending
7261/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007262///
George Burgess IVe3763372016-12-22 02:50:20 +00007263/// If this returns false, the value of Result is undefined.
7264static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7265 unsigned Type, const LValue &LVal,
7266 CharUnits &EndOffset) {
7267 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007268
George Burgess IV7fb7e362017-01-03 23:35:19 +00007269 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7270 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7271 return false;
7272 return HandleSizeof(Info, ExprLoc, Ty, Result);
7273 };
7274
George Burgess IVe3763372016-12-22 02:50:20 +00007275 // We want to evaluate the size of the entire object. This is a valid fallback
7276 // for when Type=1 and the designator is invalid, because we're asked for an
7277 // upper-bound.
7278 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7279 // Type=3 wants a lower bound, so we can't fall back to this.
7280 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007281 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007282
7283 llvm::APInt APEndOffset;
7284 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7285 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7286 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7287
7288 if (LVal.InvalidBase)
7289 return false;
7290
7291 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007292 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007293 }
7294
George Burgess IVe3763372016-12-22 02:50:20 +00007295 // We want to evaluate the size of a subobject.
7296 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007297
7298 // The following is a moderately common idiom in C:
7299 //
7300 // struct Foo { int a; char c[1]; };
7301 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7302 // strcpy(&F->c[0], Bar);
7303 //
George Burgess IVe3763372016-12-22 02:50:20 +00007304 // In order to not break too much legacy code, we need to support it.
7305 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7306 // If we can resolve this to an alloc_size call, we can hand that back,
7307 // because we know for certain how many bytes there are to write to.
7308 llvm::APInt APEndOffset;
7309 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7310 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7311 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7312
7313 // If we cannot determine the size of the initial allocation, then we can't
7314 // given an accurate upper-bound. However, we are still able to give
7315 // conservative lower-bounds for Type=3.
7316 if (Type == 1)
7317 return false;
7318 }
7319
7320 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007321 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007322 return false;
7323
George Burgess IVe3763372016-12-22 02:50:20 +00007324 // According to the GCC documentation, we want the size of the subobject
7325 // denoted by the pointer. But that's not quite right -- what we actually
7326 // want is the size of the immediately-enclosing array, if there is one.
7327 int64_t ElemsRemaining;
7328 if (Designator.MostDerivedIsArrayElement &&
7329 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7330 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7331 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7332 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7333 } else {
7334 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7335 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007336
George Burgess IVe3763372016-12-22 02:50:20 +00007337 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7338 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007339}
7340
George Burgess IVe3763372016-12-22 02:50:20 +00007341/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7342/// returns true and stores the result in @p Size.
7343///
7344/// If @p WasError is non-null, this will report whether the failure to evaluate
7345/// is to be treated as an Error in IntExprEvaluator.
7346static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7347 EvalInfo &Info, uint64_t &Size) {
7348 // Determine the denoted object.
7349 LValue LVal;
7350 {
7351 // The operand of __builtin_object_size is never evaluated for side-effects.
7352 // If there are any, but we can determine the pointed-to object anyway, then
7353 // ignore the side-effects.
7354 SpeculativeEvaluationRAII SpeculativeEval(Info);
7355 FoldOffsetRAII Fold(Info);
7356
7357 if (E->isGLValue()) {
7358 // It's possible for us to be given GLValues if we're called via
7359 // Expr::tryEvaluateObjectSize.
7360 APValue RVal;
7361 if (!EvaluateAsRValue(Info, E, RVal))
7362 return false;
7363 LVal.setFrom(Info.Ctx, RVal);
7364 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7365 return false;
7366 }
7367
7368 // If we point to before the start of the object, there are no accessible
7369 // bytes.
7370 if (LVal.getLValueOffset().isNegative()) {
7371 Size = 0;
7372 return true;
7373 }
7374
7375 CharUnits EndOffset;
7376 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7377 return false;
7378
7379 // If we've fallen outside of the end offset, just pretend there's nothing to
7380 // write to/read from.
7381 if (EndOffset <= LVal.getLValueOffset())
7382 Size = 0;
7383 else
7384 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7385 return true;
John McCall95007602010-05-10 23:27:23 +00007386}
7387
Peter Collingbournee9200682011-05-13 03:29:01 +00007388bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007389 if (unsigned BuiltinOp = E->getBuiltinCallee())
7390 return VisitBuiltinCallExpr(E, BuiltinOp);
7391
7392 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7393}
7394
7395bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7396 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007397 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007398 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007399 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007400
7401 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007402 // The type was checked when we built the expression.
7403 unsigned Type =
7404 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7405 assert(Type <= 3 && "unexpected type");
7406
George Burgess IVe3763372016-12-22 02:50:20 +00007407 uint64_t Size;
7408 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7409 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007410
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007411 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007412 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007413
Richard Smith01ade172012-05-23 04:13:20 +00007414 // Expression had no side effects, but we couldn't statically determine the
7415 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007416 switch (Info.EvalMode) {
7417 case EvalInfo::EM_ConstantExpression:
7418 case EvalInfo::EM_PotentialConstantExpression:
7419 case EvalInfo::EM_ConstantFold:
7420 case EvalInfo::EM_EvaluateForOverflow:
7421 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007422 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007423 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007424 return Error(E);
7425 case EvalInfo::EM_ConstantExpressionUnevaluated:
7426 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007427 // Reduce it to a constant now.
7428 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007429 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007430
7431 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007432 }
7433
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007434 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007435 case Builtin::BI__builtin_bswap32:
7436 case Builtin::BI__builtin_bswap64: {
7437 APSInt Val;
7438 if (!EvaluateInteger(E->getArg(0), Val, Info))
7439 return false;
7440
7441 return Success(Val.byteSwap(), E);
7442 }
7443
Richard Smith8889a3d2013-06-13 06:26:32 +00007444 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007445 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007446
7447 // FIXME: BI__builtin_clrsb
7448 // FIXME: BI__builtin_clrsbl
7449 // FIXME: BI__builtin_clrsbll
7450
Richard Smith80b3c8e2013-06-13 05:04:16 +00007451 case Builtin::BI__builtin_clz:
7452 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007453 case Builtin::BI__builtin_clzll:
7454 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007455 APSInt Val;
7456 if (!EvaluateInteger(E->getArg(0), Val, Info))
7457 return false;
7458 if (!Val)
7459 return Error(E);
7460
7461 return Success(Val.countLeadingZeros(), E);
7462 }
7463
Richard Smith8889a3d2013-06-13 06:26:32 +00007464 case Builtin::BI__builtin_constant_p:
7465 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7466
Richard Smith80b3c8e2013-06-13 05:04:16 +00007467 case Builtin::BI__builtin_ctz:
7468 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007469 case Builtin::BI__builtin_ctzll:
7470 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007471 APSInt Val;
7472 if (!EvaluateInteger(E->getArg(0), Val, Info))
7473 return false;
7474 if (!Val)
7475 return Error(E);
7476
7477 return Success(Val.countTrailingZeros(), E);
7478 }
7479
Richard Smith8889a3d2013-06-13 06:26:32 +00007480 case Builtin::BI__builtin_eh_return_data_regno: {
7481 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7482 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7483 return Success(Operand, E);
7484 }
7485
7486 case Builtin::BI__builtin_expect:
7487 return Visit(E->getArg(0));
7488
7489 case Builtin::BI__builtin_ffs:
7490 case Builtin::BI__builtin_ffsl:
7491 case Builtin::BI__builtin_ffsll: {
7492 APSInt Val;
7493 if (!EvaluateInteger(E->getArg(0), Val, Info))
7494 return false;
7495
7496 unsigned N = Val.countTrailingZeros();
7497 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7498 }
7499
7500 case Builtin::BI__builtin_fpclassify: {
7501 APFloat Val(0.0);
7502 if (!EvaluateFloat(E->getArg(5), Val, Info))
7503 return false;
7504 unsigned Arg;
7505 switch (Val.getCategory()) {
7506 case APFloat::fcNaN: Arg = 0; break;
7507 case APFloat::fcInfinity: Arg = 1; break;
7508 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7509 case APFloat::fcZero: Arg = 4; break;
7510 }
7511 return Visit(E->getArg(Arg));
7512 }
7513
7514 case Builtin::BI__builtin_isinf_sign: {
7515 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007516 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007517 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7518 }
7519
Richard Smithea3019d2013-10-15 19:07:14 +00007520 case Builtin::BI__builtin_isinf: {
7521 APFloat Val(0.0);
7522 return EvaluateFloat(E->getArg(0), Val, Info) &&
7523 Success(Val.isInfinity() ? 1 : 0, E);
7524 }
7525
7526 case Builtin::BI__builtin_isfinite: {
7527 APFloat Val(0.0);
7528 return EvaluateFloat(E->getArg(0), Val, Info) &&
7529 Success(Val.isFinite() ? 1 : 0, E);
7530 }
7531
7532 case Builtin::BI__builtin_isnan: {
7533 APFloat Val(0.0);
7534 return EvaluateFloat(E->getArg(0), Val, Info) &&
7535 Success(Val.isNaN() ? 1 : 0, E);
7536 }
7537
7538 case Builtin::BI__builtin_isnormal: {
7539 APFloat Val(0.0);
7540 return EvaluateFloat(E->getArg(0), Val, Info) &&
7541 Success(Val.isNormal() ? 1 : 0, E);
7542 }
7543
Richard Smith8889a3d2013-06-13 06:26:32 +00007544 case Builtin::BI__builtin_parity:
7545 case Builtin::BI__builtin_parityl:
7546 case Builtin::BI__builtin_parityll: {
7547 APSInt Val;
7548 if (!EvaluateInteger(E->getArg(0), Val, Info))
7549 return false;
7550
7551 return Success(Val.countPopulation() % 2, E);
7552 }
7553
Richard Smith80b3c8e2013-06-13 05:04:16 +00007554 case Builtin::BI__builtin_popcount:
7555 case Builtin::BI__builtin_popcountl:
7556 case Builtin::BI__builtin_popcountll: {
7557 APSInt Val;
7558 if (!EvaluateInteger(E->getArg(0), Val, Info))
7559 return false;
7560
7561 return Success(Val.countPopulation(), E);
7562 }
7563
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007564 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007565 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007566 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007567 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007568 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007569 << /*isConstexpr*/0 << /*isConstructor*/0
7570 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007571 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007572 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007573 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007574 case Builtin::BI__builtin_strlen:
7575 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007576 // As an extension, we support __builtin_strlen() as a constant expression,
7577 // and support folding strlen() to a constant.
7578 LValue String;
7579 if (!EvaluatePointer(E->getArg(0), String, Info))
7580 return false;
7581
Richard Smith8110c9d2016-11-29 19:45:17 +00007582 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7583
Richard Smithe6c19f22013-11-15 02:10:04 +00007584 // Fast path: if it's a string literal, search the string value.
7585 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7586 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007587 // The string literal may have embedded null characters. Find the first
7588 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007589 StringRef Str = S->getBytes();
7590 int64_t Off = String.Offset.getQuantity();
7591 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007592 S->getCharByteWidth() == 1 &&
7593 // FIXME: Add fast-path for wchar_t too.
7594 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007595 Str = Str.substr(Off);
7596
7597 StringRef::size_type Pos = Str.find(0);
7598 if (Pos != StringRef::npos)
7599 Str = Str.substr(0, Pos);
7600
7601 return Success(Str.size(), E);
7602 }
7603
7604 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007605 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007606
7607 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007608 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7609 APValue Char;
7610 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7611 !Char.isInt())
7612 return false;
7613 if (!Char.getInt())
7614 return Success(Strlen, E);
7615 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7616 return false;
7617 }
7618 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007619
Richard Smithe151bab2016-11-11 23:43:35 +00007620 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007621 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007622 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007623 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007624 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007625 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007626 // A call to strlen is not a constant expression.
7627 if (Info.getLangOpts().CPlusPlus11)
7628 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7629 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007630 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007631 else
7632 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7633 // Fall through.
7634 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007635 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007636 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007637 case Builtin::BI__builtin_wcsncmp:
7638 case Builtin::BI__builtin_memcmp:
7639 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007640 LValue String1, String2;
7641 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7642 !EvaluatePointer(E->getArg(1), String2, Info))
7643 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007644
7645 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7646
Richard Smithe151bab2016-11-11 23:43:35 +00007647 uint64_t MaxLength = uint64_t(-1);
7648 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007649 BuiltinOp != Builtin::BIwcscmp &&
7650 BuiltinOp != Builtin::BI__builtin_strcmp &&
7651 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007652 APSInt N;
7653 if (!EvaluateInteger(E->getArg(2), N, Info))
7654 return false;
7655 MaxLength = N.getExtValue();
7656 }
7657 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007658 BuiltinOp != Builtin::BIwmemcmp &&
7659 BuiltinOp != Builtin::BI__builtin_memcmp &&
7660 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007661 for (; MaxLength; --MaxLength) {
7662 APValue Char1, Char2;
7663 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7664 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7665 !Char1.isInt() || !Char2.isInt())
7666 return false;
7667 if (Char1.getInt() != Char2.getInt())
7668 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7669 if (StopAtNull && !Char1.getInt())
7670 return Success(0, E);
7671 assert(!(StopAtNull && !Char2.getInt()));
7672 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7673 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7674 return false;
7675 }
7676 // We hit the strncmp / memcmp limit.
7677 return Success(0, E);
7678 }
7679
Richard Smith01ba47d2012-04-13 00:45:38 +00007680 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007681 case Builtin::BI__atomic_is_lock_free:
7682 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007683 APSInt SizeVal;
7684 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7685 return false;
7686
7687 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7688 // of two less than the maximum inline atomic width, we know it is
7689 // lock-free. If the size isn't a power of two, or greater than the
7690 // maximum alignment where we promote atomics, we know it is not lock-free
7691 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7692 // the answer can only be determined at runtime; for example, 16-byte
7693 // atomics have lock-free implementations on some, but not all,
7694 // x86-64 processors.
7695
7696 // Check power-of-two.
7697 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007698 if (Size.isPowerOfTwo()) {
7699 // Check against inlining width.
7700 unsigned InlineWidthBits =
7701 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7702 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7703 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7704 Size == CharUnits::One() ||
7705 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7706 Expr::NPC_NeverValueDependent))
7707 // OK, we will inline appropriately-aligned operations of this size,
7708 // and _Atomic(T) is appropriately-aligned.
7709 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007710
Richard Smith01ba47d2012-04-13 00:45:38 +00007711 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7712 castAs<PointerType>()->getPointeeType();
7713 if (!PointeeType->isIncompleteType() &&
7714 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7715 // OK, we will inline operations on this object.
7716 return Success(1, E);
7717 }
7718 }
7719 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007720
Richard Smith01ba47d2012-04-13 00:45:38 +00007721 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7722 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007723 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007724 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007725}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007726
Richard Smith8b3497e2011-10-31 01:37:14 +00007727static bool HasSameBase(const LValue &A, const LValue &B) {
7728 if (!A.getLValueBase())
7729 return !B.getLValueBase();
7730 if (!B.getLValueBase())
7731 return false;
7732
Richard Smithce40ad62011-11-12 22:28:03 +00007733 if (A.getLValueBase().getOpaqueValue() !=
7734 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007735 const Decl *ADecl = GetLValueBaseDecl(A);
7736 if (!ADecl)
7737 return false;
7738 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007739 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007740 return false;
7741 }
7742
7743 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007744 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007745}
7746
Richard Smithd20f1e62014-10-21 23:01:04 +00007747/// \brief Determine whether this is a pointer past the end of the complete
7748/// object referred to by the lvalue.
7749static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7750 const LValue &LV) {
7751 // A null pointer can be viewed as being "past the end" but we don't
7752 // choose to look at it that way here.
7753 if (!LV.getLValueBase())
7754 return false;
7755
7756 // If the designator is valid and refers to a subobject, we're not pointing
7757 // past the end.
7758 if (!LV.getLValueDesignator().Invalid &&
7759 !LV.getLValueDesignator().isOnePastTheEnd())
7760 return false;
7761
David Majnemerc378ca52015-08-29 08:32:55 +00007762 // A pointer to an incomplete type might be past-the-end if the type's size is
7763 // zero. We cannot tell because the type is incomplete.
7764 QualType Ty = getType(LV.getLValueBase());
7765 if (Ty->isIncompleteType())
7766 return true;
7767
Richard Smithd20f1e62014-10-21 23:01:04 +00007768 // We're a past-the-end pointer if we point to the byte after the object,
7769 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007770 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007771 return LV.getLValueOffset() == Size;
7772}
7773
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007774namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007775
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007776/// \brief Data recursive integer evaluator of certain binary operators.
7777///
7778/// We use a data recursive algorithm for binary operators so that we are able
7779/// to handle extreme cases of chained binary operators without causing stack
7780/// overflow.
7781class DataRecursiveIntBinOpEvaluator {
7782 struct EvalResult {
7783 APValue Val;
7784 bool Failed;
7785
7786 EvalResult() : Failed(false) { }
7787
7788 void swap(EvalResult &RHS) {
7789 Val.swap(RHS.Val);
7790 Failed = RHS.Failed;
7791 RHS.Failed = false;
7792 }
7793 };
7794
7795 struct Job {
7796 const Expr *E;
7797 EvalResult LHSResult; // meaningful only for binary operator expression.
7798 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007799
David Blaikie73726062015-08-12 23:09:24 +00007800 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007801 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007802
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007803 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007804 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007805 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007806
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007807 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007808 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007809 };
7810
7811 SmallVector<Job, 16> Queue;
7812
7813 IntExprEvaluator &IntEval;
7814 EvalInfo &Info;
7815 APValue &FinalResult;
7816
7817public:
7818 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7819 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7820
7821 /// \brief True if \param E is a binary operator that we are going to handle
7822 /// data recursively.
7823 /// We handle binary operators that are comma, logical, or that have operands
7824 /// with integral or enumeration type.
7825 static bool shouldEnqueue(const BinaryOperator *E) {
7826 return E->getOpcode() == BO_Comma ||
7827 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007828 (E->isRValue() &&
7829 E->getType()->isIntegralOrEnumerationType() &&
7830 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007831 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007832 }
7833
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007834 bool Traverse(const BinaryOperator *E) {
7835 enqueue(E);
7836 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007837 while (!Queue.empty())
7838 process(PrevResult);
7839
7840 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007841
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007842 FinalResult.swap(PrevResult.Val);
7843 return true;
7844 }
7845
7846private:
7847 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7848 return IntEval.Success(Value, E, Result);
7849 }
7850 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7851 return IntEval.Success(Value, E, Result);
7852 }
7853 bool Error(const Expr *E) {
7854 return IntEval.Error(E);
7855 }
7856 bool Error(const Expr *E, diag::kind D) {
7857 return IntEval.Error(E, D);
7858 }
7859
7860 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7861 return Info.CCEDiag(E, D);
7862 }
7863
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007864 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7865 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007866 bool &SuppressRHSDiags);
7867
7868 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7869 const BinaryOperator *E, APValue &Result);
7870
7871 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7872 Result.Failed = !Evaluate(Result.Val, Info, E);
7873 if (Result.Failed)
7874 Result.Val = APValue();
7875 }
7876
Richard Trieuba4d0872012-03-21 23:30:30 +00007877 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007878
7879 void enqueue(const Expr *E) {
7880 E = E->IgnoreParens();
7881 Queue.resize(Queue.size()+1);
7882 Queue.back().E = E;
7883 Queue.back().Kind = Job::AnyExprKind;
7884 }
7885};
7886
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007887}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007888
7889bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007890 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007891 bool &SuppressRHSDiags) {
7892 if (E->getOpcode() == BO_Comma) {
7893 // Ignore LHS but note if we could not evaluate it.
7894 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007895 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007896 return true;
7897 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007898
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007899 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007900 bool LHSAsBool;
7901 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007902 // We were able to evaluate the LHS, see if we can get away with not
7903 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007904 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7905 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007906 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007907 }
7908 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007909 LHSResult.Failed = true;
7910
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007911 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007912 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007913 if (!Info.noteSideEffect())
7914 return false;
7915
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007916 // We can't evaluate the LHS; however, sometimes the result
7917 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7918 // Don't ignore RHS and suppress diagnostics from this arm.
7919 SuppressRHSDiags = true;
7920 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007921
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007922 return true;
7923 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007925 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7926 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007927
George Burgess IVa145e252016-05-25 22:38:36 +00007928 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007929 return false; // Ignore RHS;
7930
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007931 return true;
7932}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007933
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007934bool DataRecursiveIntBinOpEvaluator::
7935 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7936 const BinaryOperator *E, APValue &Result) {
7937 if (E->getOpcode() == BO_Comma) {
7938 if (RHSResult.Failed)
7939 return false;
7940 Result = RHSResult.Val;
7941 return true;
7942 }
7943
7944 if (E->isLogicalOp()) {
7945 bool lhsResult, rhsResult;
7946 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7947 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7948
7949 if (LHSIsOK) {
7950 if (RHSIsOK) {
7951 if (E->getOpcode() == BO_LOr)
7952 return Success(lhsResult || rhsResult, E, Result);
7953 else
7954 return Success(lhsResult && rhsResult, E, Result);
7955 }
7956 } else {
7957 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007958 // We can't evaluate the LHS; however, sometimes the result
7959 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7960 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007961 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007962 }
7963 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007964
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007965 return false;
7966 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007967
7968 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7969 E->getRHS()->getType()->isIntegralOrEnumerationType());
7970
7971 if (LHSResult.Failed || RHSResult.Failed)
7972 return false;
7973
7974 const APValue &LHSVal = LHSResult.Val;
7975 const APValue &RHSVal = RHSResult.Val;
7976
7977 // Handle cases like (unsigned long)&a + 4.
7978 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7979 Result = LHSVal;
Richard Smith642a2362017-01-30 23:30:26 +00007980 int64_t Offset;
7981 if (!getExtValue(Info, E, RHSVal.getInt(), Offset))
7982 return false;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007983 if (E->getOpcode() == BO_Add)
Richard Smith642a2362017-01-30 23:30:26 +00007984 Result.getLValueOffset() += CharUnits::fromQuantity(Offset);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007985 else
Richard Smith642a2362017-01-30 23:30:26 +00007986 Result.getLValueOffset() -= CharUnits::fromQuantity(Offset);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007987 return true;
7988 }
7989
7990 // Handle cases like 4 + (unsigned long)&a
7991 if (E->getOpcode() == BO_Add &&
7992 RHSVal.isLValue() && LHSVal.isInt()) {
7993 Result = RHSVal;
Richard Smith642a2362017-01-30 23:30:26 +00007994 int64_t Offset;
7995 if (!getExtValue(Info, E, LHSVal.getInt(), Offset))
7996 return false;
7997 Result.getLValueOffset() += CharUnits::fromQuantity(Offset);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007998 return true;
7999 }
8000
8001 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8002 // Handle (intptr_t)&&A - (intptr_t)&&B.
8003 if (!LHSVal.getLValueOffset().isZero() ||
8004 !RHSVal.getLValueOffset().isZero())
8005 return false;
8006 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8007 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8008 if (!LHSExpr || !RHSExpr)
8009 return false;
8010 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8011 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8012 if (!LHSAddrExpr || !RHSAddrExpr)
8013 return false;
8014 // Make sure both labels come from the same function.
8015 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8016 RHSAddrExpr->getLabel()->getDeclContext())
8017 return false;
8018 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8019 return true;
8020 }
Richard Smith43e77732013-05-07 04:50:00 +00008021
8022 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023 if (!LHSVal.isInt() || !RHSVal.isInt())
8024 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008025
8026 // Set up the width and signedness manually, in case it can't be deduced
8027 // from the operation we're performing.
8028 // FIXME: Don't do this in the cases where we can deduce it.
8029 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8030 E->getType()->isUnsignedIntegerOrEnumerationType());
8031 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8032 RHSVal.getInt(), Value))
8033 return false;
8034 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008035}
8036
Richard Trieuba4d0872012-03-21 23:30:30 +00008037void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008038 Job &job = Queue.back();
8039
8040 switch (job.Kind) {
8041 case Job::AnyExprKind: {
8042 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8043 if (shouldEnqueue(Bop)) {
8044 job.Kind = Job::BinOpKind;
8045 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008046 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008047 }
8048 }
8049
8050 EvaluateExpr(job.E, Result);
8051 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008052 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008053 }
8054
8055 case Job::BinOpKind: {
8056 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008057 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008058 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008059 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008060 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008061 }
8062 if (SuppressRHSDiags)
8063 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008064 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008065 job.Kind = Job::BinOpVisitedLHSKind;
8066 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008067 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008068 }
8069
8070 case Job::BinOpVisitedLHSKind: {
8071 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8072 EvalResult RHS;
8073 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008074 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008075 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008076 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008077 }
8078 }
8079
8080 llvm_unreachable("Invalid Job::Kind!");
8081}
8082
George Burgess IV8c892b52016-05-25 22:31:54 +00008083namespace {
8084/// Used when we determine that we should fail, but can keep evaluating prior to
8085/// noting that we had a failure.
8086class DelayedNoteFailureRAII {
8087 EvalInfo &Info;
8088 bool NoteFailure;
8089
8090public:
8091 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8092 : Info(Info), NoteFailure(NoteFailure) {}
8093 ~DelayedNoteFailureRAII() {
8094 if (NoteFailure) {
8095 bool ContinueAfterFailure = Info.noteFailure();
8096 (void)ContinueAfterFailure;
8097 assert(ContinueAfterFailure &&
8098 "Shouldn't have kept evaluating on failure.");
8099 }
8100 }
8101};
8102}
8103
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008104bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008105 // We don't call noteFailure immediately because the assignment happens after
8106 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008107 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008108 return Error(E);
8109
George Burgess IV8c892b52016-05-25 22:31:54 +00008110 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008111 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8112 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008113
Anders Carlssonacc79812008-11-16 07:17:21 +00008114 QualType LHSTy = E->getLHS()->getType();
8115 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008116
Chandler Carruthb29a7432014-10-11 11:03:30 +00008117 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008118 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008119 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008120 if (E->isAssignmentOp()) {
8121 LValue LV;
8122 EvaluateLValue(E->getLHS(), LV, Info);
8123 LHSOK = false;
8124 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008125 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8126 if (LHSOK) {
8127 LHS.makeComplexFloat();
8128 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8129 }
8130 } else {
8131 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8132 }
George Burgess IVa145e252016-05-25 22:38:36 +00008133 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008134 return false;
8135
Chandler Carruthb29a7432014-10-11 11:03:30 +00008136 if (E->getRHS()->getType()->isRealFloatingType()) {
8137 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8138 return false;
8139 RHS.makeComplexFloat();
8140 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8141 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008142 return false;
8143
8144 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008145 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008146 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008147 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008148 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8149
John McCalle3027922010-08-25 11:45:40 +00008150 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008151 return Success((CR_r == APFloat::cmpEqual &&
8152 CR_i == APFloat::cmpEqual), E);
8153 else {
John McCalle3027922010-08-25 11:45:40 +00008154 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008155 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008156 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008157 CR_r == APFloat::cmpLessThan ||
8158 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008159 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008160 CR_i == APFloat::cmpLessThan ||
8161 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008162 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008163 } else {
John McCalle3027922010-08-25 11:45:40 +00008164 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008165 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8166 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8167 else {
John McCalle3027922010-08-25 11:45:40 +00008168 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008169 "Invalid compex comparison.");
8170 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8171 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8172 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008173 }
8174 }
Mike Stump11289f42009-09-09 15:08:12 +00008175
Anders Carlssonacc79812008-11-16 07:17:21 +00008176 if (LHSTy->isRealFloatingType() &&
8177 RHSTy->isRealFloatingType()) {
8178 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008179
Richard Smith253c2a32012-01-27 01:14:48 +00008180 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008181 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008182 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008183
Richard Smith253c2a32012-01-27 01:14:48 +00008184 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008185 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008186
Anders Carlssonacc79812008-11-16 07:17:21 +00008187 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008188
Anders Carlssonacc79812008-11-16 07:17:21 +00008189 switch (E->getOpcode()) {
8190 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008191 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008192 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008193 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008194 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008195 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008196 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008197 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008198 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008199 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008200 E);
John McCalle3027922010-08-25 11:45:40 +00008201 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008202 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008203 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008204 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008205 || CR == APFloat::cmpLessThan
8206 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008207 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008208 }
Mike Stump11289f42009-09-09 15:08:12 +00008209
Eli Friedmana38da572009-04-28 19:17:36 +00008210 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008211 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008212 LValue LHSValue, RHSValue;
8213
8214 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008215 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008216 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008217
Richard Smith253c2a32012-01-27 01:14:48 +00008218 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008219 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008220
Richard Smith8b3497e2011-10-31 01:37:14 +00008221 // Reject differing bases from the normal codepath; we special-case
8222 // comparisons to null.
8223 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008224 if (E->getOpcode() == BO_Sub) {
8225 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008226 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008227 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008228 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008229 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008230 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008231 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008232 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8233 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8234 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008235 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008236 // Make sure both labels come from the same function.
8237 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8238 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008239 return Error(E);
8240 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008241 }
Richard Smith83c68212011-10-31 05:11:32 +00008242 // Inequalities and subtractions between unrelated pointers have
8243 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008244 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008245 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008246 // A constant address may compare equal to the address of a symbol.
8247 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008248 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008249 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8250 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008251 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008252 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008253 // distinct addresses. In clang, the result of such a comparison is
8254 // unspecified, so it is not a constant expression. However, we do know
8255 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008256 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8257 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008258 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008259 // We can't tell whether weak symbols will end up pointing to the same
8260 // object.
8261 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008262 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008263 // We can't compare the address of the start of one object with the
8264 // past-the-end address of another object, per C++ DR1652.
8265 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8266 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8267 (RHSValue.Base && RHSValue.Offset.isZero() &&
8268 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8269 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008270 // We can't tell whether an object is at the same address as another
8271 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008272 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8273 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008274 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008275 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008276 // (Note that clang defaults to -fmerge-all-constants, which can
8277 // lead to inconsistent results for comparisons involving the address
8278 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008279 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008280 }
Eli Friedman64004332009-03-23 04:38:34 +00008281
Richard Smith1b470412012-02-01 08:10:20 +00008282 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8283 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8284
Richard Smith84f6dcf2012-02-02 01:16:57 +00008285 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8286 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8287
John McCalle3027922010-08-25 11:45:40 +00008288 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008289 // C++11 [expr.add]p6:
8290 // Unless both pointers point to elements of the same array object, or
8291 // one past the last element of the array object, the behavior is
8292 // undefined.
8293 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8294 !AreElementsOfSameArray(getType(LHSValue.Base),
8295 LHSDesignator, RHSDesignator))
8296 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8297
Chris Lattner882bdf22010-04-20 17:13:14 +00008298 QualType Type = E->getLHS()->getType();
8299 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008300
Richard Smithd62306a2011-11-10 06:34:14 +00008301 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008302 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008303 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008304
Richard Smith84c6b3d2013-09-10 21:34:14 +00008305 // As an extension, a type may have zero size (empty struct or union in
8306 // C, array of zero length). Pointer subtraction in such cases has
8307 // undefined behavior, so is not constant.
8308 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008309 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008310 << ElementType;
8311 return false;
8312 }
8313
Richard Smith1b470412012-02-01 08:10:20 +00008314 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8315 // and produce incorrect results when it overflows. Such behavior
8316 // appears to be non-conforming, but is common, so perhaps we should
8317 // assume the standard intended for such cases to be undefined behavior
8318 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008319
Richard Smith1b470412012-02-01 08:10:20 +00008320 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8321 // overflow in the final conversion to ptrdiff_t.
8322 APSInt LHS(
8323 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8324 APSInt RHS(
8325 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8326 APSInt ElemSize(
8327 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8328 APSInt TrueResult = (LHS - RHS) / ElemSize;
8329 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8330
Richard Smith0c6124b2015-12-03 01:36:22 +00008331 if (Result.extend(65) != TrueResult &&
8332 !HandleOverflow(Info, E, TrueResult, E->getType()))
8333 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008334 return Success(Result, E);
8335 }
Richard Smithde21b242012-01-31 06:41:30 +00008336
8337 // C++11 [expr.rel]p3:
8338 // Pointers to void (after pointer conversions) can be compared, with a
8339 // result defined as follows: If both pointers represent the same
8340 // address or are both the null pointer value, the result is true if the
8341 // operator is <= or >= and false otherwise; otherwise the result is
8342 // unspecified.
8343 // We interpret this as applying to pointers to *cv* void.
8344 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008345 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008346 CCEDiag(E, diag::note_constexpr_void_comparison);
8347
Richard Smith84f6dcf2012-02-02 01:16:57 +00008348 // C++11 [expr.rel]p2:
8349 // - If two pointers point to non-static data members of the same object,
8350 // or to subobjects or array elements fo such members, recursively, the
8351 // pointer to the later declared member compares greater provided the
8352 // two members have the same access control and provided their class is
8353 // not a union.
8354 // [...]
8355 // - Otherwise pointer comparisons are unspecified.
8356 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8357 E->isRelationalOp()) {
8358 bool WasArrayIndex;
8359 unsigned Mismatch =
8360 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8361 RHSDesignator, WasArrayIndex);
8362 // At the point where the designators diverge, the comparison has a
8363 // specified value if:
8364 // - we are comparing array indices
8365 // - we are comparing fields of a union, or fields with the same access
8366 // Otherwise, the result is unspecified and thus the comparison is not a
8367 // constant expression.
8368 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8369 Mismatch < RHSDesignator.Entries.size()) {
8370 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8371 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8372 if (!LF && !RF)
8373 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8374 else if (!LF)
8375 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8376 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8377 << RF->getParent() << RF;
8378 else if (!RF)
8379 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8380 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8381 << LF->getParent() << LF;
8382 else if (!LF->getParent()->isUnion() &&
8383 LF->getAccess() != RF->getAccess())
8384 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8385 << LF << LF->getAccess() << RF << RF->getAccess()
8386 << LF->getParent();
8387 }
8388 }
8389
Eli Friedman6c31cb42012-04-16 04:30:08 +00008390 // The comparison here must be unsigned, and performed with the same
8391 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008392 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8393 uint64_t CompareLHS = LHSOffset.getQuantity();
8394 uint64_t CompareRHS = RHSOffset.getQuantity();
8395 assert(PtrSize <= 64 && "Unexpected pointer width");
8396 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8397 CompareLHS &= Mask;
8398 CompareRHS &= Mask;
8399
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008400 // If there is a base and this is a relational operator, we can only
8401 // compare pointers within the object in question; otherwise, the result
8402 // depends on where the object is located in memory.
8403 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8404 QualType BaseTy = getType(LHSValue.Base);
8405 if (BaseTy->isIncompleteType())
8406 return Error(E);
8407 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8408 uint64_t OffsetLimit = Size.getQuantity();
8409 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8410 return Error(E);
8411 }
8412
Richard Smith8b3497e2011-10-31 01:37:14 +00008413 switch (E->getOpcode()) {
8414 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008415 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8416 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8417 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8418 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8419 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8420 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008421 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008422 }
8423 }
Richard Smith7bb00672012-02-01 01:42:44 +00008424
8425 if (LHSTy->isMemberPointerType()) {
8426 assert(E->isEqualityOp() && "unexpected member pointer operation");
8427 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8428
8429 MemberPtr LHSValue, RHSValue;
8430
8431 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008432 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008433 return false;
8434
8435 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8436 return false;
8437
8438 // C++11 [expr.eq]p2:
8439 // If both operands are null, they compare equal. Otherwise if only one is
8440 // null, they compare unequal.
8441 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8442 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8443 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8444 }
8445
8446 // Otherwise if either is a pointer to a virtual member function, the
8447 // result is unspecified.
8448 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8449 if (MD->isVirtual())
8450 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8451 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8452 if (MD->isVirtual())
8453 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8454
8455 // Otherwise they compare equal if and only if they would refer to the
8456 // same member of the same most derived object or the same subobject if
8457 // they were dereferenced with a hypothetical object of the associated
8458 // class type.
8459 bool Equal = LHSValue == RHSValue;
8460 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8461 }
8462
Richard Smithab44d9b2012-02-14 22:35:28 +00008463 if (LHSTy->isNullPtrType()) {
8464 assert(E->isComparisonOp() && "unexpected nullptr operation");
8465 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8466 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8467 // are compared, the result is true of the operator is <=, >= or ==, and
8468 // false otherwise.
8469 BinaryOperator::Opcode Opcode = E->getOpcode();
8470 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8471 }
8472
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008473 assert((!LHSTy->isIntegralOrEnumerationType() ||
8474 !RHSTy->isIntegralOrEnumerationType()) &&
8475 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8476 // We can't continue from here for non-integral types.
8477 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008478}
8479
Peter Collingbournee190dee2011-03-11 19:24:49 +00008480/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8481/// a result as the expression's type.
8482bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8483 const UnaryExprOrTypeTraitExpr *E) {
8484 switch(E->getKind()) {
8485 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008486 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008487 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008488 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008489 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008490 }
Eli Friedman64004332009-03-23 04:38:34 +00008491
Peter Collingbournee190dee2011-03-11 19:24:49 +00008492 case UETT_VecStep: {
8493 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008494
Peter Collingbournee190dee2011-03-11 19:24:49 +00008495 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008496 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008497
Peter Collingbournee190dee2011-03-11 19:24:49 +00008498 // The vec_step built-in functions that take a 3-component
8499 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8500 if (n == 3)
8501 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008502
Peter Collingbournee190dee2011-03-11 19:24:49 +00008503 return Success(n, E);
8504 } else
8505 return Success(1, E);
8506 }
8507
8508 case UETT_SizeOf: {
8509 QualType SrcTy = E->getTypeOfArgument();
8510 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8511 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008512 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8513 SrcTy = Ref->getPointeeType();
8514
Richard Smithd62306a2011-11-10 06:34:14 +00008515 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008516 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008517 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008518 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008519 }
Alexey Bataev00396512015-07-02 03:40:19 +00008520 case UETT_OpenMPRequiredSimdAlign:
8521 assert(E->isArgumentType());
8522 return Success(
8523 Info.Ctx.toCharUnitsFromBits(
8524 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8525 .getQuantity(),
8526 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008527 }
8528
8529 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008530}
8531
Peter Collingbournee9200682011-05-13 03:29:01 +00008532bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008533 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008534 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008535 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008536 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008537 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008538 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008539 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008540 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008541 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008542 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008543 APSInt IdxResult;
8544 if (!EvaluateInteger(Idx, IdxResult, Info))
8545 return false;
8546 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8547 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008548 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008549 CurrentType = AT->getElementType();
8550 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8551 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008552 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008553 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008554
James Y Knight7281c352015-12-29 22:31:18 +00008555 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008556 FieldDecl *MemberDecl = ON.getField();
8557 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008558 if (!RT)
8559 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008560 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008561 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008562 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008563 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008564 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008565 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008566 CurrentType = MemberDecl->getType().getNonReferenceType();
8567 break;
8568 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008569
James Y Knight7281c352015-12-29 22:31:18 +00008570 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008571 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008572
James Y Knight7281c352015-12-29 22:31:18 +00008573 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008574 CXXBaseSpecifier *BaseSpec = ON.getBase();
8575 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008576 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008577
8578 // Find the layout of the class whose base we are looking into.
8579 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008580 if (!RT)
8581 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008582 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008583 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008584 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8585
8586 // Find the base class itself.
8587 CurrentType = BaseSpec->getType();
8588 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8589 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008590 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008591
8592 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008593 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008594 break;
8595 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008596 }
8597 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008598 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008599}
8600
Chris Lattnere13042c2008-07-11 19:10:17 +00008601bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008602 switch (E->getOpcode()) {
8603 default:
8604 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8605 // See C99 6.6p3.
8606 return Error(E);
8607 case UO_Extension:
8608 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8609 // If so, we could clear the diagnostic ID.
8610 return Visit(E->getSubExpr());
8611 case UO_Plus:
8612 // The result is just the value.
8613 return Visit(E->getSubExpr());
8614 case UO_Minus: {
8615 if (!Visit(E->getSubExpr()))
8616 return false;
8617 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008618 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008619 if (Value.isSigned() && Value.isMinSignedValue() &&
8620 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8621 E->getType()))
8622 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008623 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008624 }
8625 case UO_Not: {
8626 if (!Visit(E->getSubExpr()))
8627 return false;
8628 if (!Result.isInt()) return Error(E);
8629 return Success(~Result.getInt(), E);
8630 }
8631 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008632 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008633 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008634 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008635 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008636 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008637 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008638}
Mike Stump11289f42009-09-09 15:08:12 +00008639
Chris Lattner477c4be2008-07-12 01:15:53 +00008640/// HandleCast - This is used to evaluate implicit or explicit casts where the
8641/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008642bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8643 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008644 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008645 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008646
Eli Friedmanc757de22011-03-25 00:43:55 +00008647 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008648 case CK_BaseToDerived:
8649 case CK_DerivedToBase:
8650 case CK_UncheckedDerivedToBase:
8651 case CK_Dynamic:
8652 case CK_ToUnion:
8653 case CK_ArrayToPointerDecay:
8654 case CK_FunctionToPointerDecay:
8655 case CK_NullToPointer:
8656 case CK_NullToMemberPointer:
8657 case CK_BaseToDerivedMemberPointer:
8658 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008659 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008660 case CK_ConstructorConversion:
8661 case CK_IntegralToPointer:
8662 case CK_ToVoid:
8663 case CK_VectorSplat:
8664 case CK_IntegralToFloating:
8665 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008666 case CK_CPointerToObjCPointerCast:
8667 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008668 case CK_AnyPointerToBlockPointerCast:
8669 case CK_ObjCObjectLValueCast:
8670 case CK_FloatingRealToComplex:
8671 case CK_FloatingComplexToReal:
8672 case CK_FloatingComplexCast:
8673 case CK_FloatingComplexToIntegralComplex:
8674 case CK_IntegralRealToComplex:
8675 case CK_IntegralComplexCast:
8676 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008677 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008678 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008679 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008680 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008681 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008682 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008683 llvm_unreachable("invalid cast kind for integral value");
8684
Eli Friedman9faf2f92011-03-25 19:07:11 +00008685 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008686 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008687 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008688 case CK_ARCProduceObject:
8689 case CK_ARCConsumeObject:
8690 case CK_ARCReclaimReturnedObject:
8691 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008692 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008693 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008694
Richard Smith4ef685b2012-01-17 21:17:26 +00008695 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008696 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008697 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008698 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008700
8701 case CK_MemberPointerToBoolean:
8702 case CK_PointerToBoolean:
8703 case CK_IntegralToBoolean:
8704 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008705 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008706 case CK_FloatingComplexToBoolean:
8707 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008708 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008709 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008710 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008711 uint64_t IntResult = BoolResult;
8712 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8713 IntResult = (uint64_t)-1;
8714 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008715 }
8716
Eli Friedmanc757de22011-03-25 00:43:55 +00008717 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008718 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008719 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008720
Eli Friedman742421e2009-02-20 01:15:07 +00008721 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008722 // Allow casts of address-of-label differences if they are no-ops
8723 // or narrowing. (The narrowing case isn't actually guaranteed to
8724 // be constant-evaluatable except in some narrow cases which are hard
8725 // to detect here. We let it through on the assumption the user knows
8726 // what they are doing.)
8727 if (Result.isAddrLabelDiff())
8728 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008729 // Only allow casts of lvalues if they are lossless.
8730 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8731 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008732
Richard Smith911e1422012-01-30 22:27:01 +00008733 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8734 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008735 }
Mike Stump11289f42009-09-09 15:08:12 +00008736
Eli Friedmanc757de22011-03-25 00:43:55 +00008737 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008738 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8739
John McCall45d55e42010-05-07 21:00:08 +00008740 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008741 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008742 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008743
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008744 if (LV.getLValueBase()) {
8745 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008746 // FIXME: Allow a larger integer size than the pointer size, and allow
8747 // narrowing back down to pointer width in subsequent integral casts.
8748 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008749 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008750 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008751
Richard Smithcf74da72011-11-16 07:18:12 +00008752 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008753 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008754 return true;
8755 }
8756
Yaxun Liu402804b2016-12-15 08:09:08 +00008757 uint64_t V;
8758 if (LV.isNullPointer())
8759 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8760 else
8761 V = LV.getLValueOffset().getQuantity();
8762
8763 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008764 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008765 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008766
Eli Friedmanc757de22011-03-25 00:43:55 +00008767 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008768 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008769 if (!EvaluateComplex(SubExpr, C, Info))
8770 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008771 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008772 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008773
Eli Friedmanc757de22011-03-25 00:43:55 +00008774 case CK_FloatingToIntegral: {
8775 APFloat F(0.0);
8776 if (!EvaluateFloat(SubExpr, F, Info))
8777 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008778
Richard Smith357362d2011-12-13 06:39:58 +00008779 APSInt Value;
8780 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8781 return false;
8782 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008783 }
8784 }
Mike Stump11289f42009-09-09 15:08:12 +00008785
Eli Friedmanc757de22011-03-25 00:43:55 +00008786 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008787}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008788
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008789bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8790 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008791 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008792 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8793 return false;
8794 if (!LV.isComplexInt())
8795 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008796 return Success(LV.getComplexIntReal(), E);
8797 }
8798
8799 return Visit(E->getSubExpr());
8800}
8801
Eli Friedman4e7a2412009-02-27 04:45:43 +00008802bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008803 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008804 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008805 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8806 return false;
8807 if (!LV.isComplexInt())
8808 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008809 return Success(LV.getComplexIntImag(), E);
8810 }
8811
Richard Smith4a678122011-10-24 18:44:57 +00008812 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008813 return Success(0, E);
8814}
8815
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008816bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8817 return Success(E->getPackLength(), E);
8818}
8819
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008820bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8821 return Success(E->getValue(), E);
8822}
8823
Chris Lattner05706e882008-07-11 18:11:29 +00008824//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008825// Float Evaluation
8826//===----------------------------------------------------------------------===//
8827
8828namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008829class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008830 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008831 APFloat &Result;
8832public:
8833 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008834 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008835
Richard Smith2e312c82012-03-03 22:46:17 +00008836 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008837 Result = V.getFloat();
8838 return true;
8839 }
Eli Friedman24c01542008-08-22 00:06:13 +00008840
Richard Smithfddd3842011-12-30 21:15:51 +00008841 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008842 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8843 return true;
8844 }
8845
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008846 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008847
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008848 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008849 bool VisitBinaryOperator(const BinaryOperator *E);
8850 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008851 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008852
John McCallb1fb0d32010-05-07 22:08:54 +00008853 bool VisitUnaryReal(const UnaryOperator *E);
8854 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008855
Richard Smithfddd3842011-12-30 21:15:51 +00008856 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008857};
8858} // end anonymous namespace
8859
8860static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008861 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008862 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008863}
8864
Jay Foad39c79802011-01-12 09:06:06 +00008865static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008866 QualType ResultTy,
8867 const Expr *Arg,
8868 bool SNaN,
8869 llvm::APFloat &Result) {
8870 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8871 if (!S) return false;
8872
8873 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8874
8875 llvm::APInt fill;
8876
8877 // Treat empty strings as if they were zero.
8878 if (S->getString().empty())
8879 fill = llvm::APInt(32, 0);
8880 else if (S->getString().getAsInteger(0, fill))
8881 return false;
8882
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008883 if (Context.getTargetInfo().isNan2008()) {
8884 if (SNaN)
8885 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8886 else
8887 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8888 } else {
8889 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8890 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8891 // a different encoding to what became a standard in 2008, and for pre-
8892 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8893 // sNaN. This is now known as "legacy NaN" encoding.
8894 if (SNaN)
8895 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8896 else
8897 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8898 }
8899
John McCall16291492010-02-28 13:00:19 +00008900 return true;
8901}
8902
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008903bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008904 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008905 default:
8906 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8907
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008908 case Builtin::BI__builtin_huge_val:
8909 case Builtin::BI__builtin_huge_valf:
8910 case Builtin::BI__builtin_huge_vall:
8911 case Builtin::BI__builtin_inf:
8912 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008913 case Builtin::BI__builtin_infl: {
8914 const llvm::fltSemantics &Sem =
8915 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008916 Result = llvm::APFloat::getInf(Sem);
8917 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008918 }
Mike Stump11289f42009-09-09 15:08:12 +00008919
John McCall16291492010-02-28 13:00:19 +00008920 case Builtin::BI__builtin_nans:
8921 case Builtin::BI__builtin_nansf:
8922 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008923 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8924 true, Result))
8925 return Error(E);
8926 return true;
John McCall16291492010-02-28 13:00:19 +00008927
Chris Lattner0b7282e2008-10-06 06:31:58 +00008928 case Builtin::BI__builtin_nan:
8929 case Builtin::BI__builtin_nanf:
8930 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008931 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008932 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008933 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8934 false, Result))
8935 return Error(E);
8936 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008937
8938 case Builtin::BI__builtin_fabs:
8939 case Builtin::BI__builtin_fabsf:
8940 case Builtin::BI__builtin_fabsl:
8941 if (!EvaluateFloat(E->getArg(0), Result, Info))
8942 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008943
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008944 if (Result.isNegative())
8945 Result.changeSign();
8946 return true;
8947
Richard Smith8889a3d2013-06-13 06:26:32 +00008948 // FIXME: Builtin::BI__builtin_powi
8949 // FIXME: Builtin::BI__builtin_powif
8950 // FIXME: Builtin::BI__builtin_powil
8951
Mike Stump11289f42009-09-09 15:08:12 +00008952 case Builtin::BI__builtin_copysign:
8953 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008954 case Builtin::BI__builtin_copysignl: {
8955 APFloat RHS(0.);
8956 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8957 !EvaluateFloat(E->getArg(1), RHS, Info))
8958 return false;
8959 Result.copySign(RHS);
8960 return true;
8961 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008962 }
8963}
8964
John McCallb1fb0d32010-05-07 22:08:54 +00008965bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008966 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8967 ComplexValue CV;
8968 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8969 return false;
8970 Result = CV.FloatReal;
8971 return true;
8972 }
8973
8974 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008975}
8976
8977bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008978 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8979 ComplexValue CV;
8980 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8981 return false;
8982 Result = CV.FloatImag;
8983 return true;
8984 }
8985
Richard Smith4a678122011-10-24 18:44:57 +00008986 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008987 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8988 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008989 return true;
8990}
8991
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008992bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008993 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008994 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008995 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008996 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008997 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008998 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8999 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009000 Result.changeSign();
9001 return true;
9002 }
9003}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009004
Eli Friedman24c01542008-08-22 00:06:13 +00009005bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009006 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009008
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009009 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009010 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009011 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009012 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009013 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9014 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009015}
9016
9017bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9018 Result = E->getValue();
9019 return true;
9020}
9021
Peter Collingbournee9200682011-05-13 03:29:01 +00009022bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9023 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009024
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009025 switch (E->getCastKind()) {
9026 default:
Richard Smith11562c52011-10-28 17:51:58 +00009027 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009028
9029 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009030 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009031 return EvaluateInteger(SubExpr, IntResult, Info) &&
9032 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9033 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009034 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009035
9036 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009037 if (!Visit(SubExpr))
9038 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009039 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9040 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009041 }
John McCalld7646252010-11-14 08:17:51 +00009042
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009043 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009044 ComplexValue V;
9045 if (!EvaluateComplex(SubExpr, V, Info))
9046 return false;
9047 Result = V.getComplexFloatReal();
9048 return true;
9049 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009050 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009051}
9052
Eli Friedman24c01542008-08-22 00:06:13 +00009053//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009054// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009055//===----------------------------------------------------------------------===//
9056
9057namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009058class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009059 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009060 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009061
Anders Carlsson537969c2008-11-16 20:27:53 +00009062public:
John McCall93d91dc2010-05-07 17:22:02 +00009063 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009064 : ExprEvaluatorBaseTy(info), Result(Result) {}
9065
Richard Smith2e312c82012-03-03 22:46:17 +00009066 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009067 Result.setFrom(V);
9068 return true;
9069 }
Mike Stump11289f42009-09-09 15:08:12 +00009070
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009071 bool ZeroInitialization(const Expr *E);
9072
Anders Carlsson537969c2008-11-16 20:27:53 +00009073 //===--------------------------------------------------------------------===//
9074 // Visitor Methods
9075 //===--------------------------------------------------------------------===//
9076
Peter Collingbournee9200682011-05-13 03:29:01 +00009077 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009078 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009079 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009080 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009081 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009082};
9083} // end anonymous namespace
9084
John McCall93d91dc2010-05-07 17:22:02 +00009085static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9086 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009087 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009088 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009089}
9090
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009091bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009092 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009093 if (ElemTy->isRealFloatingType()) {
9094 Result.makeComplexFloat();
9095 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9096 Result.FloatReal = Zero;
9097 Result.FloatImag = Zero;
9098 } else {
9099 Result.makeComplexInt();
9100 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9101 Result.IntReal = Zero;
9102 Result.IntImag = Zero;
9103 }
9104 return true;
9105}
9106
Peter Collingbournee9200682011-05-13 03:29:01 +00009107bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9108 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009109
9110 if (SubExpr->getType()->isRealFloatingType()) {
9111 Result.makeComplexFloat();
9112 APFloat &Imag = Result.FloatImag;
9113 if (!EvaluateFloat(SubExpr, Imag, Info))
9114 return false;
9115
9116 Result.FloatReal = APFloat(Imag.getSemantics());
9117 return true;
9118 } else {
9119 assert(SubExpr->getType()->isIntegerType() &&
9120 "Unexpected imaginary literal.");
9121
9122 Result.makeComplexInt();
9123 APSInt &Imag = Result.IntImag;
9124 if (!EvaluateInteger(SubExpr, Imag, Info))
9125 return false;
9126
9127 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9128 return true;
9129 }
9130}
9131
Peter Collingbournee9200682011-05-13 03:29:01 +00009132bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009133
John McCallfcef3cf2010-12-14 17:51:41 +00009134 switch (E->getCastKind()) {
9135 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009136 case CK_BaseToDerived:
9137 case CK_DerivedToBase:
9138 case CK_UncheckedDerivedToBase:
9139 case CK_Dynamic:
9140 case CK_ToUnion:
9141 case CK_ArrayToPointerDecay:
9142 case CK_FunctionToPointerDecay:
9143 case CK_NullToPointer:
9144 case CK_NullToMemberPointer:
9145 case CK_BaseToDerivedMemberPointer:
9146 case CK_DerivedToBaseMemberPointer:
9147 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009148 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009149 case CK_ConstructorConversion:
9150 case CK_IntegralToPointer:
9151 case CK_PointerToIntegral:
9152 case CK_PointerToBoolean:
9153 case CK_ToVoid:
9154 case CK_VectorSplat:
9155 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009156 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009157 case CK_IntegralToBoolean:
9158 case CK_IntegralToFloating:
9159 case CK_FloatingToIntegral:
9160 case CK_FloatingToBoolean:
9161 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009162 case CK_CPointerToObjCPointerCast:
9163 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009164 case CK_AnyPointerToBlockPointerCast:
9165 case CK_ObjCObjectLValueCast:
9166 case CK_FloatingComplexToReal:
9167 case CK_FloatingComplexToBoolean:
9168 case CK_IntegralComplexToReal:
9169 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009170 case CK_ARCProduceObject:
9171 case CK_ARCConsumeObject:
9172 case CK_ARCReclaimReturnedObject:
9173 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009174 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009175 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009176 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009177 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009178 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009179 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009180 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009181 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009182
John McCallfcef3cf2010-12-14 17:51:41 +00009183 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009184 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009185 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009186 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009187
9188 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009189 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009190 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009191 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009192
9193 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009194 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009195 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009196 return false;
9197
John McCallfcef3cf2010-12-14 17:51:41 +00009198 Result.makeComplexFloat();
9199 Result.FloatImag = APFloat(Real.getSemantics());
9200 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009201 }
9202
John McCallfcef3cf2010-12-14 17:51:41 +00009203 case CK_FloatingComplexCast: {
9204 if (!Visit(E->getSubExpr()))
9205 return false;
9206
9207 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9208 QualType From
9209 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9210
Richard Smith357362d2011-12-13 06:39:58 +00009211 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9212 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009213 }
9214
9215 case CK_FloatingComplexToIntegralComplex: {
9216 if (!Visit(E->getSubExpr()))
9217 return false;
9218
9219 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9220 QualType From
9221 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9222 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009223 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9224 To, Result.IntReal) &&
9225 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9226 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009227 }
9228
9229 case CK_IntegralRealToComplex: {
9230 APSInt &Real = Result.IntReal;
9231 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9232 return false;
9233
9234 Result.makeComplexInt();
9235 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9236 return true;
9237 }
9238
9239 case CK_IntegralComplexCast: {
9240 if (!Visit(E->getSubExpr()))
9241 return false;
9242
9243 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9244 QualType From
9245 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9246
Richard Smith911e1422012-01-30 22:27:01 +00009247 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9248 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009249 return true;
9250 }
9251
9252 case CK_IntegralComplexToFloatingComplex: {
9253 if (!Visit(E->getSubExpr()))
9254 return false;
9255
Ted Kremenek28831752012-08-23 20:46:57 +00009256 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009257 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009258 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009259 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009260 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9261 To, Result.FloatReal) &&
9262 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9263 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009264 }
9265 }
9266
9267 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009268}
9269
John McCall93d91dc2010-05-07 17:22:02 +00009270bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009271 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009272 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9273
Chandler Carrutha216cad2014-10-11 00:57:18 +00009274 // Track whether the LHS or RHS is real at the type system level. When this is
9275 // the case we can simplify our evaluation strategy.
9276 bool LHSReal = false, RHSReal = false;
9277
9278 bool LHSOK;
9279 if (E->getLHS()->getType()->isRealFloatingType()) {
9280 LHSReal = true;
9281 APFloat &Real = Result.FloatReal;
9282 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9283 if (LHSOK) {
9284 Result.makeComplexFloat();
9285 Result.FloatImag = APFloat(Real.getSemantics());
9286 }
9287 } else {
9288 LHSOK = Visit(E->getLHS());
9289 }
George Burgess IVa145e252016-05-25 22:38:36 +00009290 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009291 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009292
John McCall93d91dc2010-05-07 17:22:02 +00009293 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009294 if (E->getRHS()->getType()->isRealFloatingType()) {
9295 RHSReal = true;
9296 APFloat &Real = RHS.FloatReal;
9297 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9298 return false;
9299 RHS.makeComplexFloat();
9300 RHS.FloatImag = APFloat(Real.getSemantics());
9301 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009302 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009303
Chandler Carrutha216cad2014-10-11 00:57:18 +00009304 assert(!(LHSReal && RHSReal) &&
9305 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009306 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009307 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009308 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009309 if (Result.isComplexFloat()) {
9310 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9311 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009312 if (LHSReal)
9313 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9314 else if (!RHSReal)
9315 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9316 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009317 } else {
9318 Result.getComplexIntReal() += RHS.getComplexIntReal();
9319 Result.getComplexIntImag() += RHS.getComplexIntImag();
9320 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009321 break;
John McCalle3027922010-08-25 11:45:40 +00009322 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009323 if (Result.isComplexFloat()) {
9324 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9325 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009326 if (LHSReal) {
9327 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9328 Result.getComplexFloatImag().changeSign();
9329 } else if (!RHSReal) {
9330 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9331 APFloat::rmNearestTiesToEven);
9332 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009333 } else {
9334 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9335 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9336 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009337 break;
John McCalle3027922010-08-25 11:45:40 +00009338 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009339 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009340 // This is an implementation of complex multiplication according to the
9341 // constraints laid out in C11 Annex G. The implemantion uses the
9342 // following naming scheme:
9343 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009344 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009345 APFloat &A = LHS.getComplexFloatReal();
9346 APFloat &B = LHS.getComplexFloatImag();
9347 APFloat &C = RHS.getComplexFloatReal();
9348 APFloat &D = RHS.getComplexFloatImag();
9349 APFloat &ResR = Result.getComplexFloatReal();
9350 APFloat &ResI = Result.getComplexFloatImag();
9351 if (LHSReal) {
9352 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9353 ResR = A * C;
9354 ResI = A * D;
9355 } else if (RHSReal) {
9356 ResR = C * A;
9357 ResI = C * B;
9358 } else {
9359 // In the fully general case, we need to handle NaNs and infinities
9360 // robustly.
9361 APFloat AC = A * C;
9362 APFloat BD = B * D;
9363 APFloat AD = A * D;
9364 APFloat BC = B * C;
9365 ResR = AC - BD;
9366 ResI = AD + BC;
9367 if (ResR.isNaN() && ResI.isNaN()) {
9368 bool Recalc = false;
9369 if (A.isInfinity() || B.isInfinity()) {
9370 A = APFloat::copySign(
9371 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9372 B = APFloat::copySign(
9373 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9374 if (C.isNaN())
9375 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9376 if (D.isNaN())
9377 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9378 Recalc = true;
9379 }
9380 if (C.isInfinity() || D.isInfinity()) {
9381 C = APFloat::copySign(
9382 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9383 D = APFloat::copySign(
9384 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9385 if (A.isNaN())
9386 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9387 if (B.isNaN())
9388 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9389 Recalc = true;
9390 }
9391 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9392 AD.isInfinity() || BC.isInfinity())) {
9393 if (A.isNaN())
9394 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9395 if (B.isNaN())
9396 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9397 if (C.isNaN())
9398 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9399 if (D.isNaN())
9400 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9401 Recalc = true;
9402 }
9403 if (Recalc) {
9404 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9405 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9406 }
9407 }
9408 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009409 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009410 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009411 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009412 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9413 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009414 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009415 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9416 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9417 }
9418 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009419 case BO_Div:
9420 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009421 // This is an implementation of complex division according to the
9422 // constraints laid out in C11 Annex G. The implemantion uses the
9423 // following naming scheme:
9424 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009425 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009426 APFloat &A = LHS.getComplexFloatReal();
9427 APFloat &B = LHS.getComplexFloatImag();
9428 APFloat &C = RHS.getComplexFloatReal();
9429 APFloat &D = RHS.getComplexFloatImag();
9430 APFloat &ResR = Result.getComplexFloatReal();
9431 APFloat &ResI = Result.getComplexFloatImag();
9432 if (RHSReal) {
9433 ResR = A / C;
9434 ResI = B / C;
9435 } else {
9436 if (LHSReal) {
9437 // No real optimizations we can do here, stub out with zero.
9438 B = APFloat::getZero(A.getSemantics());
9439 }
9440 int DenomLogB = 0;
9441 APFloat MaxCD = maxnum(abs(C), abs(D));
9442 if (MaxCD.isFinite()) {
9443 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009444 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9445 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009446 }
9447 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009448 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9449 APFloat::rmNearestTiesToEven);
9450 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9451 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009452 if (ResR.isNaN() && ResI.isNaN()) {
9453 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9454 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9455 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9456 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9457 D.isFinite()) {
9458 A = APFloat::copySign(
9459 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9460 B = APFloat::copySign(
9461 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9462 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9463 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9464 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9465 C = APFloat::copySign(
9466 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9467 D = APFloat::copySign(
9468 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9469 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9470 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9471 }
9472 }
9473 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009474 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009475 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9476 return Error(E, diag::note_expr_divide_by_zero);
9477
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009478 ComplexValue LHS = Result;
9479 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9480 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9481 Result.getComplexIntReal() =
9482 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9483 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9484 Result.getComplexIntImag() =
9485 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9486 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9487 }
9488 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009489 }
9490
John McCall93d91dc2010-05-07 17:22:02 +00009491 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009492}
9493
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009494bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9495 // Get the operand value into 'Result'.
9496 if (!Visit(E->getSubExpr()))
9497 return false;
9498
9499 switch (E->getOpcode()) {
9500 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009501 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009502 case UO_Extension:
9503 return true;
9504 case UO_Plus:
9505 // The result is always just the subexpr.
9506 return true;
9507 case UO_Minus:
9508 if (Result.isComplexFloat()) {
9509 Result.getComplexFloatReal().changeSign();
9510 Result.getComplexFloatImag().changeSign();
9511 }
9512 else {
9513 Result.getComplexIntReal() = -Result.getComplexIntReal();
9514 Result.getComplexIntImag() = -Result.getComplexIntImag();
9515 }
9516 return true;
9517 case UO_Not:
9518 if (Result.isComplexFloat())
9519 Result.getComplexFloatImag().changeSign();
9520 else
9521 Result.getComplexIntImag() = -Result.getComplexIntImag();
9522 return true;
9523 }
9524}
9525
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009526bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9527 if (E->getNumInits() == 2) {
9528 if (E->getType()->isComplexType()) {
9529 Result.makeComplexFloat();
9530 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9531 return false;
9532 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9533 return false;
9534 } else {
9535 Result.makeComplexInt();
9536 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9537 return false;
9538 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9539 return false;
9540 }
9541 return true;
9542 }
9543 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9544}
9545
Anders Carlsson537969c2008-11-16 20:27:53 +00009546//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009547// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9548// implicit conversion.
9549//===----------------------------------------------------------------------===//
9550
9551namespace {
9552class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009553 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009554 APValue &Result;
9555public:
9556 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9557 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9558
9559 bool Success(const APValue &V, const Expr *E) {
9560 Result = V;
9561 return true;
9562 }
9563
9564 bool ZeroInitialization(const Expr *E) {
9565 ImplicitValueInitExpr VIE(
9566 E->getType()->castAs<AtomicType>()->getValueType());
9567 return Evaluate(Result, Info, &VIE);
9568 }
9569
9570 bool VisitCastExpr(const CastExpr *E) {
9571 switch (E->getCastKind()) {
9572 default:
9573 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9574 case CK_NonAtomicToAtomic:
9575 return Evaluate(Result, Info, E->getSubExpr());
9576 }
9577 }
9578};
9579} // end anonymous namespace
9580
9581static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9582 assert(E->isRValue() && E->getType()->isAtomicType());
9583 return AtomicExprEvaluator(Info, Result).Visit(E);
9584}
9585
9586//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009587// Void expression evaluation, primarily for a cast to void on the LHS of a
9588// comma operator
9589//===----------------------------------------------------------------------===//
9590
9591namespace {
9592class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009593 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009594public:
9595 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9596
Richard Smith2e312c82012-03-03 22:46:17 +00009597 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009598
9599 bool VisitCastExpr(const CastExpr *E) {
9600 switch (E->getCastKind()) {
9601 default:
9602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9603 case CK_ToVoid:
9604 VisitIgnoredValue(E->getSubExpr());
9605 return true;
9606 }
9607 }
Hal Finkela8443c32014-07-17 14:49:58 +00009608
9609 bool VisitCallExpr(const CallExpr *E) {
9610 switch (E->getBuiltinCallee()) {
9611 default:
9612 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9613 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009614 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009615 // The argument is not evaluated!
9616 return true;
9617 }
9618 }
Richard Smith42d3af92011-12-07 00:43:50 +00009619};
9620} // end anonymous namespace
9621
9622static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9623 assert(E->isRValue() && E->getType()->isVoidType());
9624 return VoidExprEvaluator(Info).Visit(E);
9625}
9626
9627//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009628// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009629//===----------------------------------------------------------------------===//
9630
Richard Smith2e312c82012-03-03 22:46:17 +00009631static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009632 // In C, function designators are not lvalues, but we evaluate them as if they
9633 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009634 QualType T = E->getType();
9635 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009636 LValue LV;
9637 if (!EvaluateLValue(E, LV, Info))
9638 return false;
9639 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009640 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009641 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009642 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009643 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009644 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009645 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009646 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009647 LValue LV;
9648 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009649 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009650 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009651 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009652 llvm::APFloat F(0.0);
9653 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009654 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009655 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009656 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009657 ComplexValue C;
9658 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009659 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009660 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009661 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009662 MemberPtr P;
9663 if (!EvaluateMemberPointer(E, P, Info))
9664 return false;
9665 P.moveInto(Result);
9666 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009667 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009668 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009669 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009670 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9671 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009672 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009673 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009674 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009675 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009676 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009677 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9678 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009679 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009680 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009681 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009682 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009683 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009684 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009685 if (!EvaluateVoid(E, Info))
9686 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009687 } else if (T->isAtomicType()) {
9688 if (!EvaluateAtomic(E, Result, Info))
9689 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009690 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009691 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009692 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009693 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009694 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009695 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009696 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009697
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009698 return true;
9699}
9700
Richard Smithb228a862012-02-15 02:18:13 +00009701/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9702/// cases, the in-place evaluation is essential, since later initializers for
9703/// an object can indirectly refer to subobjects which were initialized earlier.
9704static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009705 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009706 assert(!E->isValueDependent());
9707
Richard Smith7525ff62013-05-09 07:14:00 +00009708 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009709 return false;
9710
9711 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009712 // Evaluate arrays and record types in-place, so that later initializers can
9713 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009714 if (E->getType()->isArrayType())
9715 return EvaluateArray(E, This, Result, Info);
9716 else if (E->getType()->isRecordType())
9717 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009718 }
9719
9720 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009721 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009722}
9723
Richard Smithf57d8cb2011-12-09 22:58:01 +00009724/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9725/// lvalue-to-rvalue cast if it is an lvalue.
9726static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009727 if (E->getType().isNull())
9728 return false;
9729
Richard Smithfddd3842011-12-30 21:15:51 +00009730 if (!CheckLiteralType(Info, E))
9731 return false;
9732
Richard Smith2e312c82012-03-03 22:46:17 +00009733 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009734 return false;
9735
9736 if (E->isGLValue()) {
9737 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009738 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009739 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009740 return false;
9741 }
9742
Richard Smith2e312c82012-03-03 22:46:17 +00009743 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009744 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009745}
Richard Smith11562c52011-10-28 17:51:58 +00009746
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009747static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9748 const ASTContext &Ctx, bool &IsConst) {
9749 // Fast-path evaluations of integer literals, since we sometimes see files
9750 // containing vast quantities of these.
9751 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9752 Result.Val = APValue(APSInt(L->getValue(),
9753 L->getType()->isUnsignedIntegerType()));
9754 IsConst = true;
9755 return true;
9756 }
James Dennett0492ef02014-03-14 17:44:10 +00009757
9758 // This case should be rare, but we need to check it before we check on
9759 // the type below.
9760 if (Exp->getType().isNull()) {
9761 IsConst = false;
9762 return true;
9763 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009764
9765 // FIXME: Evaluating values of large array and record types can cause
9766 // performance problems. Only do so in C++11 for now.
9767 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9768 Exp->getType()->isRecordType()) &&
9769 !Ctx.getLangOpts().CPlusPlus11) {
9770 IsConst = false;
9771 return true;
9772 }
9773 return false;
9774}
9775
9776
Richard Smith7b553f12011-10-29 00:50:52 +00009777/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009778/// any crazy technique (that has nothing to do with language standards) that
9779/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009780/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9781/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009782bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009783 bool IsConst;
9784 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9785 return IsConst;
9786
Richard Smith6d4c6582013-11-05 22:18:15 +00009787 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009788 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009789}
9790
Jay Foad39c79802011-01-12 09:06:06 +00009791bool Expr::EvaluateAsBooleanCondition(bool &Result,
9792 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009793 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009794 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009795 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009796}
9797
Richard Smithce8eca52015-12-08 03:21:47 +00009798static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9799 Expr::SideEffectsKind SEK) {
9800 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9801 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9802}
9803
Richard Smith5fab0c92011-12-28 19:48:30 +00009804bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9805 SideEffectsKind AllowSideEffects) const {
9806 if (!getType()->isIntegralOrEnumerationType())
9807 return false;
9808
Richard Smith11562c52011-10-28 17:51:58 +00009809 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009810 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009811 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009812 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009813
Richard Smith11562c52011-10-28 17:51:58 +00009814 Result = ExprResult.Val.getInt();
9815 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009816}
9817
Richard Trieube234c32016-04-21 21:04:55 +00009818bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9819 SideEffectsKind AllowSideEffects) const {
9820 if (!getType()->isRealFloatingType())
9821 return false;
9822
9823 EvalResult ExprResult;
9824 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9825 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9826 return false;
9827
9828 Result = ExprResult.Val.getFloat();
9829 return true;
9830}
9831
Jay Foad39c79802011-01-12 09:06:06 +00009832bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009833 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009834
John McCall45d55e42010-05-07 21:00:08 +00009835 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009836 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9837 !CheckLValueConstantExpression(Info, getExprLoc(),
9838 Ctx.getLValueReferenceType(getType()), LV))
9839 return false;
9840
Richard Smith2e312c82012-03-03 22:46:17 +00009841 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009842 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009843}
9844
Richard Smithd0b4dd62011-12-19 06:19:21 +00009845bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9846 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009847 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009848 // FIXME: Evaluating initializers for large array and record types can cause
9849 // performance problems. Only do so in C++11 for now.
9850 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009851 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009852 return false;
9853
Richard Smithd0b4dd62011-12-19 06:19:21 +00009854 Expr::EvalStatus EStatus;
9855 EStatus.Diag = &Notes;
9856
Richard Smith0c6124b2015-12-03 01:36:22 +00009857 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9858 ? EvalInfo::EM_ConstantExpression
9859 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009860 InitInfo.setEvaluatingDecl(VD, Value);
9861
9862 LValue LVal;
9863 LVal.set(VD);
9864
Richard Smithfddd3842011-12-30 21:15:51 +00009865 // C++11 [basic.start.init]p2:
9866 // Variables with static storage duration or thread storage duration shall be
9867 // zero-initialized before any other initialization takes place.
9868 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009869 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009870 !VD->getType()->isReferenceType()) {
9871 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009872 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009873 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009874 return false;
9875 }
9876
Richard Smith7525ff62013-05-09 07:14:00 +00009877 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9878 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009879 EStatus.HasSideEffects)
9880 return false;
9881
9882 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9883 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009884}
9885
Richard Smith7b553f12011-10-29 00:50:52 +00009886/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9887/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009888bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009889 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009890 return EvaluateAsRValue(Result, Ctx) &&
9891 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009892}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009893
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009894APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009895 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009896 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009897 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009898 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009899 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009900 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009901 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009902
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009903 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009904}
John McCall864e3962010-05-07 05:32:02 +00009905
Richard Smithe9ff7702013-11-05 22:23:30 +00009906void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009907 bool IsConst;
9908 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009909 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009910 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009911 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9912 }
9913}
9914
Richard Smithe6c01442013-06-05 00:46:14 +00009915bool Expr::EvalResult::isGlobalLValue() const {
9916 assert(Val.isLValue());
9917 return IsGlobalLValue(Val.getLValueBase());
9918}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009919
9920
John McCall864e3962010-05-07 05:32:02 +00009921/// isIntegerConstantExpr - this recursive routine will test if an expression is
9922/// an integer constant expression.
9923
9924/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9925/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009926
9927// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009928// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9929// and a (possibly null) SourceLocation indicating the location of the problem.
9930//
John McCall864e3962010-05-07 05:32:02 +00009931// Note that to reduce code duplication, this helper does no evaluation
9932// itself; the caller checks whether the expression is evaluatable, and
9933// in the rare cases where CheckICE actually cares about the evaluated
9934// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009935
Dan Gohman28ade552010-07-26 21:25:24 +00009936namespace {
9937
Richard Smith9e575da2012-12-28 13:25:52 +00009938enum ICEKind {
9939 /// This expression is an ICE.
9940 IK_ICE,
9941 /// This expression is not an ICE, but if it isn't evaluated, it's
9942 /// a legal subexpression for an ICE. This return value is used to handle
9943 /// the comma operator in C99 mode, and non-constant subexpressions.
9944 IK_ICEIfUnevaluated,
9945 /// This expression is not an ICE, and is not a legal subexpression for one.
9946 IK_NotICE
9947};
9948
John McCall864e3962010-05-07 05:32:02 +00009949struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009950 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009951 SourceLocation Loc;
9952
Richard Smith9e575da2012-12-28 13:25:52 +00009953 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009954};
9955
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009956}
Dan Gohman28ade552010-07-26 21:25:24 +00009957
Richard Smith9e575da2012-12-28 13:25:52 +00009958static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9959
9960static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009961
Craig Toppera31a8822013-08-22 07:09:37 +00009962static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009963 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009964 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009965 !EVResult.Val.isInt())
9966 return ICEDiag(IK_NotICE, E->getLocStart());
9967
John McCall864e3962010-05-07 05:32:02 +00009968 return NoDiag();
9969}
9970
Craig Toppera31a8822013-08-22 07:09:37 +00009971static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009972 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009973 if (!E->getType()->isIntegralOrEnumerationType())
9974 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009975
9976 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009977#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009978#define STMT(Node, Base) case Expr::Node##Class:
9979#define EXPR(Node, Base)
9980#include "clang/AST/StmtNodes.inc"
9981 case Expr::PredefinedExprClass:
9982 case Expr::FloatingLiteralClass:
9983 case Expr::ImaginaryLiteralClass:
9984 case Expr::StringLiteralClass:
9985 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009986 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009987 case Expr::MemberExprClass:
9988 case Expr::CompoundAssignOperatorClass:
9989 case Expr::CompoundLiteralExprClass:
9990 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009991 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009992 case Expr::ArrayInitLoopExprClass:
9993 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009994 case Expr::NoInitExprClass:
9995 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009996 case Expr::ImplicitValueInitExprClass:
9997 case Expr::ParenListExprClass:
9998 case Expr::VAArgExprClass:
9999 case Expr::AddrLabelExprClass:
10000 case Expr::StmtExprClass:
10001 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010002 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010003 case Expr::CXXDynamicCastExprClass:
10004 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010005 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010006 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010007 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010008 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010009 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010010 case Expr::CXXThisExprClass:
10011 case Expr::CXXThrowExprClass:
10012 case Expr::CXXNewExprClass:
10013 case Expr::CXXDeleteExprClass:
10014 case Expr::CXXPseudoDestructorExprClass:
10015 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010016 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010017 case Expr::DependentScopeDeclRefExprClass:
10018 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010019 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010020 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010021 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010022 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010023 case Expr::CXXTemporaryObjectExprClass:
10024 case Expr::CXXUnresolvedConstructExprClass:
10025 case Expr::CXXDependentScopeMemberExprClass:
10026 case Expr::UnresolvedMemberExprClass:
10027 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010028 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010029 case Expr::ObjCArrayLiteralClass:
10030 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010031 case Expr::ObjCEncodeExprClass:
10032 case Expr::ObjCMessageExprClass:
10033 case Expr::ObjCSelectorExprClass:
10034 case Expr::ObjCProtocolExprClass:
10035 case Expr::ObjCIvarRefExprClass:
10036 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010037 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010038 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010039 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010040 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010041 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010042 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010043 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010044 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010045 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010046 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010047 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010048 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010049 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010050 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010051 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010052 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010053 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010054 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010055 case Expr::CoawaitExprClass:
10056 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010057 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010058
Richard Smithf137f932014-01-25 20:50:08 +000010059 case Expr::InitListExprClass: {
10060 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10061 // form "T x = { a };" is equivalent to "T x = a;".
10062 // Unless we're initializing a reference, T is a scalar as it is known to be
10063 // of integral or enumeration type.
10064 if (E->isRValue())
10065 if (cast<InitListExpr>(E)->getNumInits() == 1)
10066 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10067 return ICEDiag(IK_NotICE, E->getLocStart());
10068 }
10069
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010070 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010071 case Expr::GNUNullExprClass:
10072 // GCC considers the GNU __null value to be an integral constant expression.
10073 return NoDiag();
10074
John McCall7c454bb2011-07-15 05:09:51 +000010075 case Expr::SubstNonTypeTemplateParmExprClass:
10076 return
10077 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10078
John McCall864e3962010-05-07 05:32:02 +000010079 case Expr::ParenExprClass:
10080 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010081 case Expr::GenericSelectionExprClass:
10082 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010083 case Expr::IntegerLiteralClass:
10084 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010085 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010086 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010087 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010088 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010089 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010090 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010091 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010092 return NoDiag();
10093 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010094 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010095 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10096 // constant expressions, but they can never be ICEs because an ICE cannot
10097 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010098 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010099 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010100 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010101 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010102 }
Richard Smith6365c912012-02-24 22:12:32 +000010103 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010104 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10105 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010106 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010107 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010108 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010109 // Parameter variables are never constants. Without this check,
10110 // getAnyInitializer() can find a default argument, which leads
10111 // to chaos.
10112 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010113 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010114
10115 // C++ 7.1.5.1p2
10116 // A variable of non-volatile const-qualified integral or enumeration
10117 // type initialized by an ICE can be used in ICEs.
10118 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010119 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010120 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010121
Richard Smithd0b4dd62011-12-19 06:19:21 +000010122 const VarDecl *VD;
10123 // Look for a declaration of this variable that has an initializer, and
10124 // check whether it is an ICE.
10125 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10126 return NoDiag();
10127 else
Richard Smith9e575da2012-12-28 13:25:52 +000010128 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010129 }
10130 }
Richard Smith9e575da2012-12-28 13:25:52 +000010131 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010132 }
John McCall864e3962010-05-07 05:32:02 +000010133 case Expr::UnaryOperatorClass: {
10134 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10135 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010136 case UO_PostInc:
10137 case UO_PostDec:
10138 case UO_PreInc:
10139 case UO_PreDec:
10140 case UO_AddrOf:
10141 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010142 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010143 // C99 6.6/3 allows increment and decrement within unevaluated
10144 // subexpressions of constant expressions, but they can never be ICEs
10145 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010146 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010147 case UO_Extension:
10148 case UO_LNot:
10149 case UO_Plus:
10150 case UO_Minus:
10151 case UO_Not:
10152 case UO_Real:
10153 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010154 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010155 }
Richard Smith9e575da2012-12-28 13:25:52 +000010156
John McCall864e3962010-05-07 05:32:02 +000010157 // OffsetOf falls through here.
10158 }
10159 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010160 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10161 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10162 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10163 // compliance: we should warn earlier for offsetof expressions with
10164 // array subscripts that aren't ICEs, and if the array subscripts
10165 // are ICEs, the value of the offsetof must be an integer constant.
10166 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010167 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010168 case Expr::UnaryExprOrTypeTraitExprClass: {
10169 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10170 if ((Exp->getKind() == UETT_SizeOf) &&
10171 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010172 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010173 return NoDiag();
10174 }
10175 case Expr::BinaryOperatorClass: {
10176 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10177 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010178 case BO_PtrMemD:
10179 case BO_PtrMemI:
10180 case BO_Assign:
10181 case BO_MulAssign:
10182 case BO_DivAssign:
10183 case BO_RemAssign:
10184 case BO_AddAssign:
10185 case BO_SubAssign:
10186 case BO_ShlAssign:
10187 case BO_ShrAssign:
10188 case BO_AndAssign:
10189 case BO_XorAssign:
10190 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010191 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10192 // constant expressions, but they can never be ICEs because an ICE cannot
10193 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010194 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010195
John McCalle3027922010-08-25 11:45:40 +000010196 case BO_Mul:
10197 case BO_Div:
10198 case BO_Rem:
10199 case BO_Add:
10200 case BO_Sub:
10201 case BO_Shl:
10202 case BO_Shr:
10203 case BO_LT:
10204 case BO_GT:
10205 case BO_LE:
10206 case BO_GE:
10207 case BO_EQ:
10208 case BO_NE:
10209 case BO_And:
10210 case BO_Xor:
10211 case BO_Or:
10212 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010213 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10214 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010215 if (Exp->getOpcode() == BO_Div ||
10216 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010217 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010218 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010219 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010220 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010221 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010222 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010223 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010224 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010225 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010226 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010227 }
10228 }
10229 }
John McCalle3027922010-08-25 11:45:40 +000010230 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010231 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010232 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10233 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010234 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10235 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010236 } else {
10237 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010238 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010239 }
10240 }
Richard Smith9e575da2012-12-28 13:25:52 +000010241 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010242 }
John McCalle3027922010-08-25 11:45:40 +000010243 case BO_LAnd:
10244 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010245 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10246 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010247 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010248 // Rare case where the RHS has a comma "side-effect"; we need
10249 // to actually check the condition to see whether the side
10250 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010251 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010252 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010253 return RHSResult;
10254 return NoDiag();
10255 }
10256
Richard Smith9e575da2012-12-28 13:25:52 +000010257 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010258 }
10259 }
10260 }
10261 case Expr::ImplicitCastExprClass:
10262 case Expr::CStyleCastExprClass:
10263 case Expr::CXXFunctionalCastExprClass:
10264 case Expr::CXXStaticCastExprClass:
10265 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010266 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010267 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010268 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010269 if (isa<ExplicitCastExpr>(E)) {
10270 if (const FloatingLiteral *FL
10271 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10272 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10273 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10274 APSInt IgnoredVal(DestWidth, !DestSigned);
10275 bool Ignored;
10276 // If the value does not fit in the destination type, the behavior is
10277 // undefined, so we are not required to treat it as a constant
10278 // expression.
10279 if (FL->getValue().convertToInteger(IgnoredVal,
10280 llvm::APFloat::rmTowardZero,
10281 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010282 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010283 return NoDiag();
10284 }
10285 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010286 switch (cast<CastExpr>(E)->getCastKind()) {
10287 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010288 case CK_AtomicToNonAtomic:
10289 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010290 case CK_NoOp:
10291 case CK_IntegralToBoolean:
10292 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010293 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010294 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010295 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010296 }
John McCall864e3962010-05-07 05:32:02 +000010297 }
John McCallc07a0c72011-02-17 10:25:35 +000010298 case Expr::BinaryConditionalOperatorClass: {
10299 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10300 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010301 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010302 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010303 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10304 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10305 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010306 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010307 return FalseResult;
10308 }
John McCall864e3962010-05-07 05:32:02 +000010309 case Expr::ConditionalOperatorClass: {
10310 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10311 // If the condition (ignoring parens) is a __builtin_constant_p call,
10312 // then only the true side is actually considered in an integer constant
10313 // expression, and it is fully evaluated. This is an important GNU
10314 // extension. See GCC PR38377 for discussion.
10315 if (const CallExpr *CallCE
10316 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010317 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010318 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010319 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010320 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010321 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010322
Richard Smithf57d8cb2011-12-09 22:58:01 +000010323 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10324 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010325
Richard Smith9e575da2012-12-28 13:25:52 +000010326 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010327 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010328 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010329 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010330 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010331 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010332 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010333 return NoDiag();
10334 // Rare case where the diagnostics depend on which side is evaluated
10335 // Note that if we get here, CondResult is 0, and at least one of
10336 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010337 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010338 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010339 return TrueResult;
10340 }
10341 case Expr::CXXDefaultArgExprClass:
10342 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010343 case Expr::CXXDefaultInitExprClass:
10344 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010345 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010346 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010347 }
10348 }
10349
David Blaikiee4d798f2012-01-20 21:50:17 +000010350 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010351}
10352
Richard Smithf57d8cb2011-12-09 22:58:01 +000010353/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010354static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010355 const Expr *E,
10356 llvm::APSInt *Value,
10357 SourceLocation *Loc) {
10358 if (!E->getType()->isIntegralOrEnumerationType()) {
10359 if (Loc) *Loc = E->getExprLoc();
10360 return false;
10361 }
10362
Richard Smith66e05fe2012-01-18 05:21:49 +000010363 APValue Result;
10364 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010365 return false;
10366
Richard Smith98710fc2014-11-13 23:03:19 +000010367 if (!Result.isInt()) {
10368 if (Loc) *Loc = E->getExprLoc();
10369 return false;
10370 }
10371
Richard Smith66e05fe2012-01-18 05:21:49 +000010372 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010373 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010374}
10375
Craig Toppera31a8822013-08-22 07:09:37 +000010376bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10377 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010378 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010379 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010380
Richard Smith9e575da2012-12-28 13:25:52 +000010381 ICEDiag D = CheckICE(this, Ctx);
10382 if (D.Kind != IK_ICE) {
10383 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010384 return false;
10385 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010386 return true;
10387}
10388
Craig Toppera31a8822013-08-22 07:09:37 +000010389bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010390 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010391 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010392 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10393
10394 if (!isIntegerConstantExpr(Ctx, Loc))
10395 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010396 // The only possible side-effects here are due to UB discovered in the
10397 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10398 // required to treat the expression as an ICE, so we produce the folded
10399 // value.
10400 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010401 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010402 return true;
10403}
Richard Smith66e05fe2012-01-18 05:21:49 +000010404
Craig Toppera31a8822013-08-22 07:09:37 +000010405bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010406 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010407}
10408
Craig Toppera31a8822013-08-22 07:09:37 +000010409bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010410 SourceLocation *Loc) const {
10411 // We support this checking in C++98 mode in order to diagnose compatibility
10412 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010413 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010414
Richard Smith98a0a492012-02-14 21:38:30 +000010415 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010416 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010417 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010418 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010419 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010420
10421 APValue Scratch;
10422 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10423
10424 if (!Diags.empty()) {
10425 IsConstExpr = false;
10426 if (Loc) *Loc = Diags[0].first;
10427 } else if (!IsConstExpr) {
10428 // FIXME: This shouldn't happen.
10429 if (Loc) *Loc = getExprLoc();
10430 }
10431
10432 return IsConstExpr;
10433}
Richard Smith253c2a32012-01-27 01:14:48 +000010434
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010435bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10436 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010437 ArrayRef<const Expr*> Args,
10438 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010439 Expr::EvalStatus Status;
10440 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10441
George Burgess IV177399e2017-01-09 04:12:14 +000010442 LValue ThisVal;
10443 const LValue *ThisPtr = nullptr;
10444 if (This) {
10445#ifndef NDEBUG
10446 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10447 assert(MD && "Don't provide `this` for non-methods.");
10448 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10449#endif
10450 if (EvaluateObjectArgument(Info, This, ThisVal))
10451 ThisPtr = &ThisVal;
10452 if (Info.EvalStatus.HasSideEffects)
10453 return false;
10454 }
10455
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010456 ArgVector ArgValues(Args.size());
10457 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10458 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010459 if ((*I)->isValueDependent() ||
10460 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010461 // If evaluation fails, throw away the argument entirely.
10462 ArgValues[I - Args.begin()] = APValue();
10463 if (Info.EvalStatus.HasSideEffects)
10464 return false;
10465 }
10466
10467 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010468 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010469 ArgValues.data());
10470 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10471}
10472
Richard Smith253c2a32012-01-27 01:14:48 +000010473bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010474 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010475 PartialDiagnosticAt> &Diags) {
10476 // FIXME: It would be useful to check constexpr function templates, but at the
10477 // moment the constant expression evaluator cannot cope with the non-rigorous
10478 // ASTs which we build for dependent expressions.
10479 if (FD->isDependentContext())
10480 return true;
10481
10482 Expr::EvalStatus Status;
10483 Status.Diag = &Diags;
10484
Richard Smith6d4c6582013-11-05 22:18:15 +000010485 EvalInfo Info(FD->getASTContext(), Status,
10486 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010487
10488 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010489 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010490
Richard Smith7525ff62013-05-09 07:14:00 +000010491 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010492 // is a temporary being used as the 'this' pointer.
10493 LValue This;
10494 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010495 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010496
Richard Smith253c2a32012-01-27 01:14:48 +000010497 ArrayRef<const Expr*> Args;
10498
Richard Smith2e312c82012-03-03 22:46:17 +000010499 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010500 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10501 // Evaluate the call as a constant initializer, to allow the construction
10502 // of objects of non-literal types.
10503 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010504 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10505 } else {
10506 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010507 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010508 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010509 }
Richard Smith253c2a32012-01-27 01:14:48 +000010510
10511 return Diags.empty();
10512}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010513
10514bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10515 const FunctionDecl *FD,
10516 SmallVectorImpl<
10517 PartialDiagnosticAt> &Diags) {
10518 Expr::EvalStatus Status;
10519 Status.Diag = &Diags;
10520
10521 EvalInfo Info(FD->getASTContext(), Status,
10522 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10523
10524 // Fabricate a call stack frame to give the arguments a plausible cover story.
10525 ArrayRef<const Expr*> Args;
10526 ArgVector ArgValues(0);
10527 bool Success = EvaluateArgs(Args, ArgValues, Info);
10528 (void)Success;
10529 assert(Success &&
10530 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010531 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010532
10533 APValue ResultScratch;
10534 Evaluate(ResultScratch, Info, E);
10535 return Diags.empty();
10536}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010537
10538bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10539 unsigned Type) const {
10540 if (!getType()->isPointerType())
10541 return false;
10542
10543 Expr::EvalStatus Status;
10544 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010545 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010546}