blob: bac2356cc43fd3dbd935de417324705138584b43 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
68 // this actually matters for arrays of unknown bound. Using the type of
69 // the most recent declaration isn't clearly correct in general. Eg:
70 //
71 // extern int arr[]; void f() { extern int arr[3]; };
72 // constexpr int *p = &arr[1]; // valid?
73 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
Richard Smith84401042013-06-03 05:03:02 +000074
75 const Expr *Base = B.get<const Expr*>();
76
77 // For a materialized temporary, the type of the temporary we materialized
78 // may not be the type of the expression.
79 if (const MaterializeTemporaryExpr *MTE =
80 dyn_cast<MaterializeTemporaryExpr>(Base)) {
81 SmallVector<const Expr *, 2> CommaLHSs;
82 SmallVector<SubobjectAdjustment, 2> Adjustments;
83 const Expr *Temp = MTE->GetTemporaryExpr();
84 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85 Adjustments);
86 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000087 // for it directly. Otherwise use the type after adjustment.
88 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000089 return Inner->getType();
90 }
91
92 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000093 }
94
Richard Smithd62306a2011-11-10 06:34:14 +000095 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000096 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000097 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000098 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000099 APValue::BaseOrMemberType Value;
100 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000101 return Value;
102 }
103
104 /// Get an LValue path entry, which is known to not be an array index, as a
105 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000106 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000107 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000108 }
109 /// Get an LValue path entry, which is known to not be an array index, as a
110 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000111 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000112 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000113 }
114 /// Determine whether this LValue path entry for a base class names a virtual
115 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119
George Burgess IVe3763372016-12-22 02:50:20 +0000120 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122 const FunctionDecl *Callee = CE->getDirectCallee();
123 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124 }
125
126 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127 /// This will look through a single cast.
128 ///
129 /// Returns null if we couldn't unwrap a function with alloc_size.
130 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131 if (!E->getType()->isPointerType())
132 return nullptr;
133
134 E = E->IgnoreParens();
135 // If we're doing a variable assignment from e.g. malloc(N), there will
136 // probably be a cast of some kind. Ignore it.
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return getAllocSizeAttr(CE) ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
Richard Smith6f4f0f12017-10-20 22:56:25 +0000152 /// The bound to claim that an array of unknown bound has.
153 /// The value in MostDerivedArraySize is undefined in this case. So, set it
154 /// to an arbitrary value that's likely to loudly break things if it's used.
155 static const uint64_t AssumedSizeForUnsizedArray =
156 std::numeric_limits<uint64_t>::max() / 2;
157
George Burgess IVe3763372016-12-22 02:50:20 +0000158 /// Determines if an LValue with the given LValueBase will have an unsized
159 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// Find the path length and type of the most-derived subobject in the given
161 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000162 static unsigned
163 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
164 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000165 uint64_t &ArraySize, QualType &Type, bool &IsArray,
166 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000167 // This only accepts LValueBases from APValues, and APValues don't support
168 // arrays that lack size info.
169 assert(!isBaseAnAllocSizeCall(Base) &&
170 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000171 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000172 Type = getType(Base);
173
Richard Smith80815602011-11-07 05:07:52 +0000174 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000175 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000176 const ArrayType *AT = Ctx.getAsArrayType(Type);
177 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000179 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000180
181 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
182 ArraySize = CAT->getSize().getZExtValue();
183 } else {
184 assert(I == 0 && "unexpected unsized array designator");
185 FirstEntryIsUnsizedArray = true;
186 ArraySize = AssumedSizeForUnsizedArray;
187 }
Richard Smith66c96992012-02-18 22:04:06 +0000188 } else if (Type->isAnyComplexType()) {
189 const ComplexType *CT = Type->castAs<ComplexType>();
190 Type = CT->getElementType();
191 ArraySize = 2;
192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000194 } else if (const FieldDecl *FD = getAsField(Path[I])) {
195 Type = FD->getType();
196 ArraySize = 0;
197 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000198 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 } else {
Richard Smith80815602011-11-07 05:07:52 +0000200 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000201 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 }
Richard Smith80815602011-11-07 05:07:52 +0000204 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000206 }
207
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 // The order of this enum is important for diagnostics.
209 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000210 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000211 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 };
213
Richard Smith96e0c102011-11-04 02:25:55 +0000214 /// A path from a glvalue to a subobject of that glvalue.
215 struct SubobjectDesignator {
216 /// True if the subobject was named in a manner not supported by C++11. Such
217 /// lvalues can still be folded, but they are not core constant expressions
218 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000219 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000220
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000222 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000223
Daniel Jasperffdee092017-05-02 19:21:42 +0000224 /// Indicator of whether the first entry is an unsized array.
225 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000226
George Burgess IVa51c4072015-10-16 01:49:01 +0000227 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000228 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000229
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 /// The length of the path to the most-derived object of which this is a
231 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000232 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000233
George Burgess IVa51c4072015-10-16 01:49:01 +0000234 /// The size of the array of which the most-derived object is an element.
235 /// This will always be 0 if the most-derived object is not an array
236 /// element. 0 is not an indicator of whether or not the most-derived object
237 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000238 ///
239 /// If the current array is an unsized array, the value of this is
240 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 uint64_t MostDerivedArraySize;
242
243 /// The type of the most derived object referred to by this address.
244 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000245
Richard Smith80815602011-11-07 05:07:52 +0000246 typedef APValue::LValuePathEntry PathEntry;
247
Richard Smith96e0c102011-11-04 02:25:55 +0000248 /// The entries on the path from the glvalue to the designated subobject.
249 SmallVector<PathEntry, 8> Entries;
250
Richard Smitha8105bc2012-01-06 16:39:00 +0000251 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000252
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000254 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000255 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000256 MostDerivedPathLength(0), MostDerivedArraySize(0),
257 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000258
259 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000260 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000261 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000262 MostDerivedPathLength(0), MostDerivedArraySize(0) {
263 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000264 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000266 ArrayRef<PathEntry> VEntries = V.getLValuePath();
267 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000268 if (V.getLValueBase()) {
269 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000270 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000271 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000273 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000274 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000275 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000276 }
Richard Smith80815602011-11-07 05:07:52 +0000277 }
278 }
279
Richard Smith96e0c102011-11-04 02:25:55 +0000280 void setInvalid() {
281 Invalid = true;
282 Entries.clear();
283 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000284
George Burgess IVe3763372016-12-22 02:50:20 +0000285 /// Determine whether the most derived subobject is an array without a
286 /// known bound.
287 bool isMostDerivedAnUnsizedArray() const {
288 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000290 }
291
292 /// Determine what the most derived array's size is. Results in an assertion
293 /// failure if the most derived array lacks a size.
294 uint64_t getMostDerivedArraySize() const {
295 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
296 return MostDerivedArraySize;
297 }
298
Richard Smitha8105bc2012-01-06 16:39:00 +0000299 /// Determine whether this is a one-past-the-end pointer.
300 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000301 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 if (IsOnePastTheEnd)
303 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000305 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
306 return true;
307 return false;
308 }
309
310 /// Check that this refers to a valid subobject.
311 bool isValidSubobject() const {
312 if (Invalid)
313 return false;
314 return !isOnePastTheEnd();
315 }
316 /// Check that this refers to a valid subobject, and if not, produce a
317 /// relevant diagnostic and set the designator as invalid.
318 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
319
320 /// Update this designator to refer to the first element within this array.
321 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000322 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000323 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000324 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000325
326 // This is a most-derived object.
327 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000328 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000329 MostDerivedArraySize = CAT->getSize().getZExtValue();
330 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000331 }
George Burgess IVe3763372016-12-22 02:50:20 +0000332 /// Update this designator to refer to the first element within the array of
333 /// elements of type T. This is an array of unknown size.
334 void addUnsizedArrayUnchecked(QualType ElemTy) {
335 PathEntry Entry;
336 Entry.ArrayIndex = 0;
337 Entries.push_back(Entry);
338
339 MostDerivedType = ElemTy;
340 MostDerivedIsArrayElement = true;
341 // The value in MostDerivedArraySize is undefined in this case. So, set it
342 // to an arbitrary value that's likely to loudly break things if it's
343 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000344 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000345 MostDerivedPathLength = Entries.size();
346 }
Richard Smith96e0c102011-11-04 02:25:55 +0000347 /// Update this designator to refer to the given base or member of this
348 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000349 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000350 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000351 APValue::BaseOrMemberType Value(D, Virtual);
352 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000353 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000354
355 // If this isn't a base class, it's a new most-derived object.
356 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
357 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000358 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000359 MostDerivedArraySize = 0;
360 MostDerivedPathLength = Entries.size();
361 }
Richard Smith96e0c102011-11-04 02:25:55 +0000362 }
Richard Smith66c96992012-02-18 22:04:06 +0000363 /// Update this designator to refer to the given complex component.
364 void addComplexUnchecked(QualType EltTy, bool Imag) {
365 PathEntry Entry;
366 Entry.ArrayIndex = Imag;
367 Entries.push_back(Entry);
368
369 // This is technically a most-derived object, though in practice this
370 // is unlikely to matter.
371 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000372 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000373 MostDerivedArraySize = 2;
374 MostDerivedPathLength = Entries.size();
375 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000376 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000377 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
378 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000379 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000380 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
381 if (Invalid || !N) return;
382 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
383 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000384 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000385 // Can't verify -- trust that the user is doing the right thing (or if
386 // not, trust that the caller will catch the bad behavior).
387 // FIXME: Should we reject if this overflows, at least?
388 Entries.back().ArrayIndex += TruncatedN;
389 return;
390 }
391
392 // [expr.add]p4: For the purposes of these operators, a pointer to a
393 // nonarray object behaves the same as a pointer to the first element of
394 // an array of length one with the type of the object as its element type.
395 bool IsArray = MostDerivedPathLength == Entries.size() &&
396 MostDerivedIsArrayElement;
397 uint64_t ArrayIndex =
398 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
399 uint64_t ArraySize =
400 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
401
402 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
403 // Calculate the actual index in a wide enough type, so we can include
404 // it in the note.
405 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
406 (llvm::APInt&)N += ArrayIndex;
407 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
408 diagnosePointerArithmetic(Info, E, N);
409 setInvalid();
410 return;
411 }
412
413 ArrayIndex += TruncatedN;
414 assert(ArrayIndex <= ArraySize &&
415 "bounds check succeeded for out-of-bounds index");
416
417 if (IsArray)
418 Entries.back().ArrayIndex = ArrayIndex;
419 else
420 IsOnePastTheEnd = (ArrayIndex != 0);
421 }
Richard Smith96e0c102011-11-04 02:25:55 +0000422 };
423
Richard Smith254a73d2011-10-28 22:34:42 +0000424 /// A stack frame in the constexpr call stack.
425 struct CallStackFrame {
426 EvalInfo &Info;
427
428 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000429 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000430
Richard Smithf6f003a2011-12-16 19:06:07 +0000431 /// Callee - The function which was called.
432 const FunctionDecl *Callee;
433
Richard Smithd62306a2011-11-10 06:34:14 +0000434 /// This - The binding for the this pointer in this call, if any.
435 const LValue *This;
436
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000437 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000438 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000439 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000440
Eli Friedman4830ec82012-06-25 21:21:08 +0000441 // Note that we intentionally use std::map here so that references to
442 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000443 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000444 typedef MapTy::const_iterator temp_iterator;
445 /// Temporaries - Temporary lvalues materialized within this stack frame.
446 MapTy Temporaries;
447
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000448 /// CallLoc - The location of the call expression for this call.
449 SourceLocation CallLoc;
450
451 /// Index - The call index of this call.
452 unsigned Index;
453
Faisal Vali051e3a22017-02-16 04:12:21 +0000454 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
455 // on the overall stack usage of deeply-recursing constexpr evaluataions.
456 // (We should cache this map rather than recomputing it repeatedly.)
457 // But let's try this and see how it goes; we can look into caching the map
458 // as a later change.
459
460 /// LambdaCaptureFields - Mapping from captured variables/this to
461 /// corresponding data members in the closure class.
462 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
463 FieldDecl *LambdaThisCaptureField;
464
Richard Smithf6f003a2011-12-16 19:06:07 +0000465 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
466 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000467 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000468 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000469
470 APValue *getTemporary(const void *Key) {
471 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000472 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000473 }
474 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000475 };
476
Richard Smith852c9db2013-04-20 22:23:05 +0000477 /// Temporarily override 'this'.
478 class ThisOverrideRAII {
479 public:
480 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
481 : Frame(Frame), OldThis(Frame.This) {
482 if (Enable)
483 Frame.This = NewThis;
484 }
485 ~ThisOverrideRAII() {
486 Frame.This = OldThis;
487 }
488 private:
489 CallStackFrame &Frame;
490 const LValue *OldThis;
491 };
492
Richard Smith92b1ce02011-12-12 09:28:41 +0000493 /// A partial diagnostic which we might know in advance that we are not going
494 /// to emit.
495 class OptionalDiagnostic {
496 PartialDiagnostic *Diag;
497
498 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000499 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
500 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000501
502 template<typename T>
503 OptionalDiagnostic &operator<<(const T &v) {
504 if (Diag)
505 *Diag << v;
506 return *this;
507 }
Richard Smithfe800032012-01-31 04:08:20 +0000508
509 OptionalDiagnostic &operator<<(const APSInt &I) {
510 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000511 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000512 I.toString(Buffer);
513 *Diag << StringRef(Buffer.data(), Buffer.size());
514 }
515 return *this;
516 }
517
518 OptionalDiagnostic &operator<<(const APFloat &F) {
519 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000520 // FIXME: Force the precision of the source value down so we don't
521 // print digits which are usually useless (we don't really care here if
522 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000523 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000524 // representation which rounds to the correct value, but it's a bit
525 // tricky to implement.
526 unsigned precision =
527 llvm::APFloat::semanticsPrecision(F.getSemantics());
528 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000529 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000530 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000531 *Diag << StringRef(Buffer.data(), Buffer.size());
532 }
533 return *this;
534 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000535 };
536
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 /// A cleanup, and a flag indicating whether it is lifetime-extended.
538 class Cleanup {
539 llvm::PointerIntPair<APValue*, 1, bool> Value;
540
541 public:
542 Cleanup(APValue *Val, bool IsLifetimeExtended)
543 : Value(Val, IsLifetimeExtended) {}
544
545 bool isLifetimeExtended() const { return Value.getInt(); }
546 void endLifetime() {
547 *Value.getPointer() = APValue();
548 }
549 };
550
Richard Smithb228a862012-02-15 02:18:13 +0000551 /// EvalInfo - This is a private struct used by the evaluator to capture
552 /// information about a subexpression as it is folded. It retains information
553 /// about the AST context, but also maintains information about the folded
554 /// expression.
555 ///
556 /// If an expression could be evaluated, it is still possible it is not a C
557 /// "integer constant expression" or constant expression. If not, this struct
558 /// captures information about how and why not.
559 ///
560 /// One bit of information passed *into* the request for constant folding
561 /// indicates whether the subexpression is "evaluated" or not according to C
562 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
563 /// evaluate the expression regardless of what the RHS is, but C only allows
564 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000565 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000566 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000567
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000568 /// EvalStatus - Contains information about the evaluation.
569 Expr::EvalStatus &EvalStatus;
570
571 /// CurrentCall - The top of the constexpr call stack.
572 CallStackFrame *CurrentCall;
573
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000574 /// CallStackDepth - The number of calls in the call stack right now.
575 unsigned CallStackDepth;
576
Richard Smithb228a862012-02-15 02:18:13 +0000577 /// NextCallIndex - The next call index to assign.
578 unsigned NextCallIndex;
579
Richard Smitha3d3bd22013-05-08 02:12:03 +0000580 /// StepsLeft - The remaining number of evaluation steps we're permitted
581 /// to perform. This is essentially a limit for the number of statements
582 /// we will evaluate.
583 unsigned StepsLeft;
584
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000585 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000586 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000587 CallStackFrame BottomFrame;
588
Richard Smith08d6a2c2013-07-24 07:11:57 +0000589 /// A stack of values whose lifetimes end at the end of some surrounding
590 /// evaluation frame.
591 llvm::SmallVector<Cleanup, 16> CleanupStack;
592
Richard Smithd62306a2011-11-10 06:34:14 +0000593 /// EvaluatingDecl - This is the declaration whose initializer is being
594 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000595 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000596
597 /// EvaluatingDeclValue - This is the value being constructed for the
598 /// declaration whose initializer is being evaluated, if any.
599 APValue *EvaluatingDeclValue;
600
Erik Pilkington42925492017-10-04 00:18:55 +0000601 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
602 /// the call index that that lvalue was allocated in.
603 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
604
605 /// EvaluatingConstructors - Set of objects that are currently being
606 /// constructed.
607 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
608
609 struct EvaluatingConstructorRAII {
610 EvalInfo &EI;
611 EvaluatingObject Object;
612 bool DidInsert;
613 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
614 : EI(EI), Object(Object) {
615 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
616 }
617 ~EvaluatingConstructorRAII() {
618 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
619 }
620 };
621
622 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
623 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
624 }
625
Richard Smith410306b2016-12-12 02:53:20 +0000626 /// The current array initialization index, if we're performing array
627 /// initialization.
628 uint64_t ArrayInitIndex = -1;
629
Richard Smith357362d2011-12-13 06:39:58 +0000630 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
631 /// notes attached to it will also be stored, otherwise they will not be.
632 bool HasActiveDiagnostic;
633
Richard Smith0c6124b2015-12-03 01:36:22 +0000634 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
635 /// fold (not just why it's not strictly a constant expression)?
636 bool HasFoldFailureDiagnostic;
637
George Burgess IV8c892b52016-05-25 22:31:54 +0000638 /// \brief Whether or not we're currently speculatively evaluating.
639 bool IsSpeculativelyEvaluating;
640
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 enum EvaluationMode {
642 /// Evaluate as a constant expression. Stop if we find that the expression
643 /// is not a constant expression.
644 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000645
Richard Smith6d4c6582013-11-05 22:18:15 +0000646 /// Evaluate as a potential constant expression. Keep going if we hit a
647 /// construct that we can't evaluate yet (because we don't yet know the
648 /// value of something) but stop if we hit something that could never be
649 /// a constant expression.
650 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000651
Richard Smith6d4c6582013-11-05 22:18:15 +0000652 /// Fold the expression to a constant. Stop if we hit a side-effect that
653 /// we can't model.
654 EM_ConstantFold,
655
656 /// Evaluate the expression looking for integer overflow and similar
657 /// issues. Don't worry about side-effects, and try to visit all
658 /// subexpressions.
659 EM_EvaluateForOverflow,
660
661 /// Evaluate in any way we know how. Don't worry about side-effects that
662 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000663 EM_IgnoreSideEffects,
664
665 /// Evaluate as a constant expression. Stop if we find that the expression
666 /// is not a constant expression. Some expressions can be retried in the
667 /// optimizer if we don't constant fold them here, but in an unevaluated
668 /// context we try to fold them immediately since the optimizer never
669 /// gets a chance to look at it.
670 EM_ConstantExpressionUnevaluated,
671
672 /// Evaluate as a potential constant expression. Keep going if we hit a
673 /// construct that we can't evaluate yet (because we don't yet know the
674 /// value of something) but stop if we hit something that could never be
675 /// a constant expression. Some expressions can be retried in the
676 /// optimizer if we don't constant fold them here, but in an unevaluated
677 /// context we try to fold them immediately since the optimizer never
678 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000679 EM_PotentialConstantExpressionUnevaluated,
680
George Burgess IVf9013bf2017-02-10 22:52:29 +0000681 /// Evaluate as a constant expression. In certain scenarios, if:
682 /// - we find a MemberExpr with a base that can't be evaluated, or
683 /// - we find a variable initialized with a call to a function that has
684 /// the alloc_size attribute on it
685 /// then we may consider evaluation to have succeeded.
686 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000687 /// In either case, the LValue returned shall have an invalid base; in the
688 /// former, the base will be the invalid MemberExpr, in the latter, the
689 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
690 /// said CallExpr.
691 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 } EvalMode;
693
694 /// Are we checking whether the expression is a potential constant
695 /// expression?
696 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 return EvalMode == EM_PotentialConstantExpression ||
698 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 }
700
701 /// Are we checking an expression for overflow?
702 // FIXME: We should check for any kind of undefined or suspicious behavior
703 // in such constructs, not just overflow.
704 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
705
706 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000707 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000708 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000709 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000710 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
711 EvaluatingDecl((const ValueDecl *)nullptr),
712 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000713 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
714 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000715
Richard Smith7525ff62013-05-09 07:14:00 +0000716 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
717 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000718 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000719 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000720 }
721
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000723
Richard Smith357362d2011-12-13 06:39:58 +0000724 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000725 // Don't perform any constexpr calls (other than the call we're checking)
726 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000728 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000729 if (NextCallIndex == 0) {
730 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000731 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000732 return false;
733 }
Richard Smith357362d2011-12-13 06:39:58 +0000734 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
735 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000736 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000737 << getLangOpts().ConstexprCallDepth;
738 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000739 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000740
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallStackFrame *getCallFrame(unsigned CallIndex) {
742 assert(CallIndex && "no call index in getCallFrame");
743 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
744 // be null in this loop.
745 CallStackFrame *Frame = CurrentCall;
746 while (Frame->Index > CallIndex)
747 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000748 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000749 }
750
Richard Smitha3d3bd22013-05-08 02:12:03 +0000751 bool nextStep(const Stmt *S) {
752 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000753 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000754 return false;
755 }
756 --StepsLeft;
757 return true;
758 }
759
Richard Smith357362d2011-12-13 06:39:58 +0000760 private:
761 /// Add a diagnostic to the diagnostics list.
762 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
763 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
764 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
765 return EvalStatus.Diag->back().second;
766 }
767
Richard Smithf6f003a2011-12-16 19:06:07 +0000768 /// Add notes containing a call stack to the current point of evaluation.
769 void addCallStack(unsigned Limit);
770
Faisal Valie690b7a2016-07-02 22:34:24 +0000771 private:
772 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
773 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000774
Richard Smith92b1ce02011-12-12 09:28:41 +0000775 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 // If we have a prior diagnostic, it will be noting that the expression
777 // isn't a constant expression. This diagnostic is more important,
778 // unless we require this evaluation to produce a constant expression.
779 //
780 // FIXME: We might want to show both diagnostics to the user in
781 // EM_ConstantFold mode.
782 if (!EvalStatus.Diag->empty()) {
783 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000784 case EM_ConstantFold:
785 case EM_IgnoreSideEffects:
786 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000787 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000788 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000789 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000790 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000791 case EM_ConstantExpression:
792 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000793 case EM_ConstantExpressionUnevaluated:
794 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000795 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 HasActiveDiagnostic = false;
797 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000798 }
799 }
800
Richard Smithf6f003a2011-12-16 19:06:07 +0000801 unsigned CallStackNotes = CallStackDepth - 1;
802 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
803 if (Limit)
804 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000805 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000806 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000807
Richard Smith357362d2011-12-13 06:39:58 +0000808 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000809 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000810 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000811 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
812 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000814 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000815 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000816 }
Richard Smith357362d2011-12-13 06:39:58 +0000817 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000818 return OptionalDiagnostic();
819 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000820 public:
821 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
822 OptionalDiagnostic
823 FFDiag(SourceLocation Loc,
824 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
825 unsigned ExtraNotes = 0) {
826 return Diag(Loc, DiagId, ExtraNotes, false);
827 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000828
Faisal Valie690b7a2016-07-02 22:34:24 +0000829 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000830 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000831 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000832 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000833 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000834 HasActiveDiagnostic = false;
835 return OptionalDiagnostic();
836 }
837
Richard Smith92b1ce02011-12-12 09:28:41 +0000838 /// Diagnose that the evaluation does not produce a C++11 core constant
839 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 ///
841 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
842 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000843 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000844 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000845 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 // Don't override a previous diagnostic. Don't bother collecting
847 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000848 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000849 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000850 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000851 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000852 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000853 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000854 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
855 = diag::note_invalid_subexpr_in_const_expr,
856 unsigned ExtraNotes = 0) {
857 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
858 }
Richard Smith357362d2011-12-13 06:39:58 +0000859 /// Add a note to a prior diagnostic.
860 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
861 if (!HasActiveDiagnostic)
862 return OptionalDiagnostic();
863 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000864 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000865
866 /// Add a stack of notes to a prior diagnostic.
867 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
868 if (HasActiveDiagnostic) {
869 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
870 Diags.begin(), Diags.end());
871 }
872 }
Richard Smith253c2a32012-01-27 01:14:48 +0000873
Richard Smith6d4c6582013-11-05 22:18:15 +0000874 /// Should we continue evaluation after encountering a side-effect that we
875 /// couldn't model?
876 bool keepEvaluatingAfterSideEffect() {
877 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000878 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000879 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 case EM_EvaluateForOverflow:
881 case EM_IgnoreSideEffects:
882 return true;
883
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000885 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000886 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000887 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 return false;
889 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000890 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000891 }
892
893 /// Note that we have had a side-effect, and determine whether we should
894 /// keep evaluating.
895 bool noteSideEffect() {
896 EvalStatus.HasSideEffects = true;
897 return keepEvaluatingAfterSideEffect();
898 }
899
Richard Smithce8eca52015-12-08 03:21:47 +0000900 /// Should we continue evaluation after encountering undefined behavior?
901 bool keepEvaluatingAfterUndefinedBehavior() {
902 switch (EvalMode) {
903 case EM_EvaluateForOverflow:
904 case EM_IgnoreSideEffects:
905 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000906 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000907 return true;
908
909 case EM_PotentialConstantExpression:
910 case EM_PotentialConstantExpressionUnevaluated:
911 case EM_ConstantExpression:
912 case EM_ConstantExpressionUnevaluated:
913 return false;
914 }
915 llvm_unreachable("Missed EvalMode case");
916 }
917
918 /// Note that we hit something that was technically undefined behavior, but
919 /// that we can evaluate past it (such as signed overflow or floating-point
920 /// division by zero.)
921 bool noteUndefinedBehavior() {
922 EvalStatus.HasUndefinedBehavior = true;
923 return keepEvaluatingAfterUndefinedBehavior();
924 }
925
Richard Smith253c2a32012-01-27 01:14:48 +0000926 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000927 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000928 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 if (!StepsLeft)
930 return false;
931
932 switch (EvalMode) {
933 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000934 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 case EM_EvaluateForOverflow:
936 return true;
937
938 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000939 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 case EM_ConstantFold:
941 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000942 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 return false;
944 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000945 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000946 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000947
George Burgess IV8c892b52016-05-25 22:31:54 +0000948 /// Notes that we failed to evaluate an expression that other expressions
949 /// directly depend on, and determine if we should keep evaluating. This
950 /// should only be called if we actually intend to keep evaluating.
951 ///
952 /// Call noteSideEffect() instead if we may be able to ignore the value that
953 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
954 ///
955 /// (Foo(), 1) // use noteSideEffect
956 /// (Foo() || true) // use noteSideEffect
957 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000958 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000959 // Failure when evaluating some expression often means there is some
960 // subexpression whose evaluation was skipped. Therefore, (because we
961 // don't track whether we skipped an expression when unwinding after an
962 // evaluation failure) every evaluation failure that bubbles up from a
963 // subexpression implies that a side-effect has potentially happened. We
964 // skip setting the HasSideEffects flag to true until we decide to
965 // continue evaluating after that point, which happens here.
966 bool KeepGoing = keepEvaluatingAfterFailure();
967 EvalStatus.HasSideEffects |= KeepGoing;
968 return KeepGoing;
969 }
970
Richard Smith410306b2016-12-12 02:53:20 +0000971 class ArrayInitLoopIndex {
972 EvalInfo &Info;
973 uint64_t OuterIndex;
974
975 public:
976 ArrayInitLoopIndex(EvalInfo &Info)
977 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
978 Info.ArrayInitIndex = 0;
979 }
980 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
981
982 operator uint64_t&() { return Info.ArrayInitIndex; }
983 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000984 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000985
986 /// Object used to treat all foldable expressions as constant expressions.
987 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000989 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000990 bool HadNoPriorDiags;
991 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000992
Richard Smith6d4c6582013-11-05 22:18:15 +0000993 explicit FoldConstant(EvalInfo &Info, bool Enabled)
994 : Info(Info),
995 Enabled(Enabled),
996 HadNoPriorDiags(Info.EvalStatus.Diag &&
997 Info.EvalStatus.Diag->empty() &&
998 !Info.EvalStatus.HasSideEffects),
999 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001000 if (Enabled &&
1001 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1002 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001003 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001005 void keepDiagnostics() { Enabled = false; }
1006 ~FoldConstant() {
1007 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 !Info.EvalStatus.HasSideEffects)
1009 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001010 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001011 }
1012 };
Richard Smith17100ba2012-02-16 02:46:34 +00001013
George Burgess IV3a03fab2015-09-04 21:28:13 +00001014 /// RAII object used to treat the current evaluation as the correct pointer
1015 /// offset fold for the current EvalMode
1016 struct FoldOffsetRAII {
1017 EvalInfo &Info;
1018 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001019 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001020 : Info(Info), OldMode(Info.EvalMode) {
1021 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001022 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001023 }
1024
1025 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1026 };
1027
George Burgess IV8c892b52016-05-25 22:31:54 +00001028 /// RAII object used to optionally suppress diagnostics and side-effects from
1029 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001030 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001031 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001032 Expr::EvalStatus OldStatus;
1033 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001034
George Burgess IV8c892b52016-05-25 22:31:54 +00001035 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001036 Info = Other.Info;
1037 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001038 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001039 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001040 }
1041
1042 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001043 if (!Info)
1044 return;
1045
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001046 Info->EvalStatus = OldStatus;
1047 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001048 }
1049
Richard Smith17100ba2012-02-16 02:46:34 +00001050 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001051 SpeculativeEvaluationRAII() = default;
1052
1053 SpeculativeEvaluationRAII(
1054 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001055 : Info(&Info), OldStatus(Info.EvalStatus),
1056 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001057 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001058 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001059 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001060
1061 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1062 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1063 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001064 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001065
1066 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1067 maybeRestoreState();
1068 moveFromAndCancel(std::move(Other));
1069 return *this;
1070 }
1071
1072 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001073 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001074
1075 /// RAII object wrapping a full-expression or block scope, and handling
1076 /// the ending of the lifetime of temporaries created within it.
1077 template<bool IsFullExpression>
1078 class ScopeRAII {
1079 EvalInfo &Info;
1080 unsigned OldStackSize;
1081 public:
1082 ScopeRAII(EvalInfo &Info)
1083 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1084 ~ScopeRAII() {
1085 // Body moved to a static method to encourage the compiler to inline away
1086 // instances of this class.
1087 cleanup(Info, OldStackSize);
1088 }
1089 private:
1090 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1091 unsigned NewEnd = OldStackSize;
1092 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1093 I != N; ++I) {
1094 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1095 // Full-expression cleanup of a lifetime-extended temporary: nothing
1096 // to do, just move this cleanup to the right place in the stack.
1097 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1098 ++NewEnd;
1099 } else {
1100 // End the lifetime of the object.
1101 Info.CleanupStack[I].endLifetime();
1102 }
1103 }
1104 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1105 Info.CleanupStack.end());
1106 }
1107 };
1108 typedef ScopeRAII<false> BlockScopeRAII;
1109 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001110}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001111
Richard Smitha8105bc2012-01-06 16:39:00 +00001112bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1113 CheckSubobjectKind CSK) {
1114 if (Invalid)
1115 return false;
1116 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001117 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001118 << CSK;
1119 setInvalid();
1120 return false;
1121 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001122 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1123 // must actually be at least one array element; even a VLA cannot have a
1124 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 return true;
1126}
1127
Richard Smith6f4f0f12017-10-20 22:56:25 +00001128void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1129 const Expr *E) {
1130 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1131 // Do not set the designator as invalid: we can represent this situation,
1132 // and correct handling of __builtin_object_size requires us to do so.
1133}
1134
Richard Smitha8105bc2012-01-06 16:39:00 +00001135void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001136 const Expr *E,
1137 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001138 // If we're complaining, we must be able to statically determine the size of
1139 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001140 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001141 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001142 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001143 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001144 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001145 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001146 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001147 setInvalid();
1148}
1149
Richard Smithf6f003a2011-12-16 19:06:07 +00001150CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1151 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001152 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001153 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1154 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001155 Info.CurrentCall = this;
1156 ++Info.CallStackDepth;
1157}
1158
1159CallStackFrame::~CallStackFrame() {
1160 assert(Info.CurrentCall == this && "calls retired out of order");
1161 --Info.CallStackDepth;
1162 Info.CurrentCall = Caller;
1163}
1164
Richard Smith08d6a2c2013-07-24 07:11:57 +00001165APValue &CallStackFrame::createTemporary(const void *Key,
1166 bool IsLifetimeExtended) {
1167 APValue &Result = Temporaries[Key];
1168 assert(Result.isUninit() && "temporary created multiple times");
1169 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1170 return Result;
1171}
1172
Richard Smith84401042013-06-03 05:03:02 +00001173static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001174
1175void EvalInfo::addCallStack(unsigned Limit) {
1176 // Determine which calls to skip, if any.
1177 unsigned ActiveCalls = CallStackDepth - 1;
1178 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1179 if (Limit && Limit < ActiveCalls) {
1180 SkipStart = Limit / 2 + Limit % 2;
1181 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001182 }
1183
Richard Smithf6f003a2011-12-16 19:06:07 +00001184 // Walk the call stack and add the diagnostics.
1185 unsigned CallIdx = 0;
1186 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1187 Frame = Frame->Caller, ++CallIdx) {
1188 // Skip this call?
1189 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1190 if (CallIdx == SkipStart) {
1191 // Note that we're skipping calls.
1192 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1193 << unsigned(ActiveCalls - Limit);
1194 }
1195 continue;
1196 }
1197
Richard Smith5179eb72016-06-28 19:03:57 +00001198 // Use a different note for an inheriting constructor, because from the
1199 // user's perspective it's not really a function at all.
1200 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1201 if (CD->isInheritingConstructor()) {
1202 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1203 << CD->getParent();
1204 continue;
1205 }
1206 }
1207
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001208 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001209 llvm::raw_svector_ostream Out(Buffer);
1210 describeCall(Frame, Out);
1211 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1212 }
1213}
1214
1215namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001216 struct ComplexValue {
1217 private:
1218 bool IsInt;
1219
1220 public:
1221 APSInt IntReal, IntImag;
1222 APFloat FloatReal, FloatImag;
1223
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001224 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001225
1226 void makeComplexFloat() { IsInt = false; }
1227 bool isComplexFloat() const { return !IsInt; }
1228 APFloat &getComplexFloatReal() { return FloatReal; }
1229 APFloat &getComplexFloatImag() { return FloatImag; }
1230
1231 void makeComplexInt() { IsInt = true; }
1232 bool isComplexInt() const { return IsInt; }
1233 APSInt &getComplexIntReal() { return IntReal; }
1234 APSInt &getComplexIntImag() { return IntImag; }
1235
Richard Smith2e312c82012-03-03 22:46:17 +00001236 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001237 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001238 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001239 else
Richard Smith2e312c82012-03-03 22:46:17 +00001240 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001241 }
Richard Smith2e312c82012-03-03 22:46:17 +00001242 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001243 assert(v.isComplexFloat() || v.isComplexInt());
1244 if (v.isComplexFloat()) {
1245 makeComplexFloat();
1246 FloatReal = v.getComplexFloatReal();
1247 FloatImag = v.getComplexFloatImag();
1248 } else {
1249 makeComplexInt();
1250 IntReal = v.getComplexIntReal();
1251 IntImag = v.getComplexIntImag();
1252 }
1253 }
John McCall93d91dc2010-05-07 17:22:02 +00001254 };
John McCall45d55e42010-05-07 21:00:08 +00001255
1256 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001257 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001258 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001259 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001260 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001261 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001262 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001263
Richard Smithce40ad62011-11-12 22:28:03 +00001264 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001265 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001266 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001267 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001268 SubobjectDesignator &getLValueDesignator() { return Designator; }
1269 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001270 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001271
Richard Smith2e312c82012-03-03 22:46:17 +00001272 void moveInto(APValue &V) const {
1273 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1275 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001276 else {
1277 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001278 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001279 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001280 }
John McCall45d55e42010-05-07 21:00:08 +00001281 }
Richard Smith2e312c82012-03-03 22:46:17 +00001282 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001283 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001284 Base = V.getLValueBase();
1285 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001286 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001287 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001288 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001289 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001290 }
1291
Tim Northover01503332017-05-26 02:16:00 +00001292 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001293#ifndef NDEBUG
1294 // We only allow a few types of invalid bases. Enforce that here.
1295 if (BInvalid) {
1296 const auto *E = B.get<const Expr *>();
1297 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1298 "Unexpected type of invalid base");
1299 }
1300#endif
1301
Richard Smithce40ad62011-11-12 22:28:03 +00001302 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001303 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001304 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001305 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001306 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001307 IsNullPtr = false;
1308 }
1309
1310 void setNull(QualType PointerTy, uint64_t TargetVal) {
1311 Base = (Expr *)nullptr;
1312 Offset = CharUnits::fromQuantity(TargetVal);
1313 InvalidBase = false;
1314 CallIndex = 0;
1315 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1316 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001317 }
1318
George Burgess IV3a03fab2015-09-04 21:28:13 +00001319 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1320 set(B, I, true);
1321 }
1322
Richard Smitha8105bc2012-01-06 16:39:00 +00001323 // Check that this LValue is not based on a null pointer. If it is, produce
1324 // a diagnostic and mark the designator as invalid.
1325 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1326 CheckSubobjectKind CSK) {
1327 if (Designator.Invalid)
1328 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001329 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001330 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001331 << CSK;
1332 Designator.setInvalid();
1333 return false;
1334 }
1335 return true;
1336 }
1337
1338 // Check this LValue refers to an object. If not, set the designator to be
1339 // invalid and emit a diagnostic.
1340 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001341 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001342 Designator.checkSubobject(Info, E, CSK);
1343 }
1344
1345 void addDecl(EvalInfo &Info, const Expr *E,
1346 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001347 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1348 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001349 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001350 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1351 if (!Designator.Entries.empty()) {
1352 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1353 Designator.setInvalid();
1354 return;
1355 }
Richard Smithefdb5032017-11-15 03:03:56 +00001356 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1357 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1358 Designator.FirstEntryIsAnUnsizedArray = true;
1359 Designator.addUnsizedArrayUnchecked(ElemTy);
1360 }
George Burgess IVe3763372016-12-22 02:50:20 +00001361 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001362 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001363 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1364 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001365 }
Richard Smith66c96992012-02-18 22:04:06 +00001366 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1368 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001369 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001370 void clearIsNullPointer() {
1371 IsNullPtr = false;
1372 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001373 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1374 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001375 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1376 // but we're not required to diagnose it and it's valid in C++.)
1377 if (!Index)
1378 return;
1379
1380 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1381 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1382 // offsets.
1383 uint64_t Offset64 = Offset.getQuantity();
1384 uint64_t ElemSize64 = ElementSize.getQuantity();
1385 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1386 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1387
1388 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001389 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001390 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001391 }
1392 void adjustOffset(CharUnits N) {
1393 Offset += N;
1394 if (N.getQuantity())
1395 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001396 }
John McCall45d55e42010-05-07 21:00:08 +00001397 };
Richard Smith027bf112011-11-17 22:56:20 +00001398
1399 struct MemberPtr {
1400 MemberPtr() {}
1401 explicit MemberPtr(const ValueDecl *Decl) :
1402 DeclAndIsDerivedMember(Decl, false), Path() {}
1403
1404 /// The member or (direct or indirect) field referred to by this member
1405 /// pointer, or 0 if this is a null member pointer.
1406 const ValueDecl *getDecl() const {
1407 return DeclAndIsDerivedMember.getPointer();
1408 }
1409 /// Is this actually a member of some type derived from the relevant class?
1410 bool isDerivedMember() const {
1411 return DeclAndIsDerivedMember.getInt();
1412 }
1413 /// Get the class which the declaration actually lives in.
1414 const CXXRecordDecl *getContainingRecord() const {
1415 return cast<CXXRecordDecl>(
1416 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1417 }
1418
Richard Smith2e312c82012-03-03 22:46:17 +00001419 void moveInto(APValue &V) const {
1420 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001421 }
Richard Smith2e312c82012-03-03 22:46:17 +00001422 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001423 assert(V.isMemberPointer());
1424 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1425 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1426 Path.clear();
1427 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1428 Path.insert(Path.end(), P.begin(), P.end());
1429 }
1430
1431 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1432 /// whether the member is a member of some class derived from the class type
1433 /// of the member pointer.
1434 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1435 /// Path - The path of base/derived classes from the member declaration's
1436 /// class (exclusive) to the class type of the member pointer (inclusive).
1437 SmallVector<const CXXRecordDecl*, 4> Path;
1438
1439 /// Perform a cast towards the class of the Decl (either up or down the
1440 /// hierarchy).
1441 bool castBack(const CXXRecordDecl *Class) {
1442 assert(!Path.empty());
1443 const CXXRecordDecl *Expected;
1444 if (Path.size() >= 2)
1445 Expected = Path[Path.size() - 2];
1446 else
1447 Expected = getContainingRecord();
1448 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1449 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1450 // if B does not contain the original member and is not a base or
1451 // derived class of the class containing the original member, the result
1452 // of the cast is undefined.
1453 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1454 // (D::*). We consider that to be a language defect.
1455 return false;
1456 }
1457 Path.pop_back();
1458 return true;
1459 }
1460 /// Perform a base-to-derived member pointer cast.
1461 bool castToDerived(const CXXRecordDecl *Derived) {
1462 if (!getDecl())
1463 return true;
1464 if (!isDerivedMember()) {
1465 Path.push_back(Derived);
1466 return true;
1467 }
1468 if (!castBack(Derived))
1469 return false;
1470 if (Path.empty())
1471 DeclAndIsDerivedMember.setInt(false);
1472 return true;
1473 }
1474 /// Perform a derived-to-base member pointer cast.
1475 bool castToBase(const CXXRecordDecl *Base) {
1476 if (!getDecl())
1477 return true;
1478 if (Path.empty())
1479 DeclAndIsDerivedMember.setInt(true);
1480 if (isDerivedMember()) {
1481 Path.push_back(Base);
1482 return true;
1483 }
1484 return castBack(Base);
1485 }
1486 };
Richard Smith357362d2011-12-13 06:39:58 +00001487
Richard Smith7bb00672012-02-01 01:42:44 +00001488 /// Compare two member pointers, which are assumed to be of the same type.
1489 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1490 if (!LHS.getDecl() || !RHS.getDecl())
1491 return !LHS.getDecl() && !RHS.getDecl();
1492 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1493 return false;
1494 return LHS.Path == RHS.Path;
1495 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001496}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001497
Richard Smith2e312c82012-03-03 22:46:17 +00001498static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001499static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1500 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001501 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001502static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1503 bool InvalidBaseOK = false);
1504static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1505 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001506static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1507 EvalInfo &Info);
1508static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001509static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001510static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001511 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001512static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001513static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001514static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1515 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001516static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001517
1518//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001519// Misc utilities
1520//===----------------------------------------------------------------------===//
1521
Richard Smithd6cc1982017-01-31 02:23:02 +00001522/// Negate an APSInt in place, converting it to a signed form if necessary, and
1523/// preserving its value (by extending by up to one bit as needed).
1524static void negateAsSigned(APSInt &Int) {
1525 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1526 Int = Int.extend(Int.getBitWidth() + 1);
1527 Int.setIsSigned(true);
1528 }
1529 Int = -Int;
1530}
1531
Richard Smith84401042013-06-03 05:03:02 +00001532/// Produce a string describing the given constexpr call.
1533static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1534 unsigned ArgIndex = 0;
1535 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1536 !isa<CXXConstructorDecl>(Frame->Callee) &&
1537 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1538
1539 if (!IsMemberCall)
1540 Out << *Frame->Callee << '(';
1541
1542 if (Frame->This && IsMemberCall) {
1543 APValue Val;
1544 Frame->This->moveInto(Val);
1545 Val.printPretty(Out, Frame->Info.Ctx,
1546 Frame->This->Designator.MostDerivedType);
1547 // FIXME: Add parens around Val if needed.
1548 Out << "->" << *Frame->Callee << '(';
1549 IsMemberCall = false;
1550 }
1551
1552 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1553 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1554 if (ArgIndex > (unsigned)IsMemberCall)
1555 Out << ", ";
1556
1557 const ParmVarDecl *Param = *I;
1558 const APValue &Arg = Frame->Arguments[ArgIndex];
1559 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1560
1561 if (ArgIndex == 0 && IsMemberCall)
1562 Out << "->" << *Frame->Callee << '(';
1563 }
1564
1565 Out << ')';
1566}
1567
Richard Smithd9f663b2013-04-22 15:31:51 +00001568/// Evaluate an expression to see if it had side-effects, and discard its
1569/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001570/// \return \c true if the caller should keep evaluating.
1571static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001572 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001573 if (!Evaluate(Scratch, Info, E))
1574 // We don't need the value, but we might have skipped a side effect here.
1575 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001576 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001577}
1578
Richard Smithd62306a2011-11-10 06:34:14 +00001579/// Should this call expression be treated as a string literal?
1580static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001581 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001582 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1583 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1584}
1585
Richard Smithce40ad62011-11-12 22:28:03 +00001586static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001587 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1588 // constant expression of pointer type that evaluates to...
1589
1590 // ... a null pointer value, or a prvalue core constant expression of type
1591 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001592 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001593
Richard Smithce40ad62011-11-12 22:28:03 +00001594 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1595 // ... the address of an object with static storage duration,
1596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1597 return VD->hasGlobalStorage();
1598 // ... the address of a function,
1599 return isa<FunctionDecl>(D);
1600 }
1601
1602 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001603 switch (E->getStmtClass()) {
1604 default:
1605 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001606 case Expr::CompoundLiteralExprClass: {
1607 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1608 return CLE->isFileScope() && CLE->isLValue();
1609 }
Richard Smithe6c01442013-06-05 00:46:14 +00001610 case Expr::MaterializeTemporaryExprClass:
1611 // A materialized temporary might have been lifetime-extended to static
1612 // storage duration.
1613 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001614 // A string literal has static storage duration.
1615 case Expr::StringLiteralClass:
1616 case Expr::PredefinedExprClass:
1617 case Expr::ObjCStringLiteralClass:
1618 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001619 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001620 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001621 return true;
1622 case Expr::CallExprClass:
1623 return IsStringLiteralCall(cast<CallExpr>(E));
1624 // For GCC compatibility, &&label has static storage duration.
1625 case Expr::AddrLabelExprClass:
1626 return true;
1627 // A Block literal expression may be used as the initialization value for
1628 // Block variables at global or local static scope.
1629 case Expr::BlockExprClass:
1630 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001631 case Expr::ImplicitValueInitExprClass:
1632 // FIXME:
1633 // We can never form an lvalue with an implicit value initialization as its
1634 // base through expression evaluation, so these only appear in one case: the
1635 // implicit variable declaration we invent when checking whether a constexpr
1636 // constructor can produce a constant expression. We must assume that such
1637 // an expression might be a global lvalue.
1638 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001639 }
John McCall95007602010-05-10 23:27:23 +00001640}
1641
Richard Smithb228a862012-02-15 02:18:13 +00001642static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1643 assert(Base && "no location for a null lvalue");
1644 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1645 if (VD)
1646 Info.Note(VD->getLocation(), diag::note_declared_at);
1647 else
Ted Kremenek28831752012-08-23 20:46:57 +00001648 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001649 diag::note_constexpr_temporary_here);
1650}
1651
Richard Smith80815602011-11-07 05:07:52 +00001652/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001653/// value for an address or reference constant expression. Return true if we
1654/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001655static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1656 QualType Type, const LValue &LVal) {
1657 bool IsReferenceType = Type->isReferenceType();
1658
Richard Smith357362d2011-12-13 06:39:58 +00001659 APValue::LValueBase Base = LVal.getLValueBase();
1660 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1661
Richard Smith0dea49e2012-02-18 04:58:18 +00001662 // Check that the object is a global. Note that the fake 'this' object we
1663 // manufacture when checking potential constant expressions is conservatively
1664 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001665 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001666 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001667 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001668 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001669 << IsReferenceType << !Designator.Entries.empty()
1670 << !!VD << VD;
1671 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001672 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001673 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001674 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001675 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001676 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001677 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001678 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001679 LVal.getLValueCallIndex() == 0) &&
1680 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001681
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001682 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1683 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001684 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001685 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001686 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001687
Hans Wennborg82dd8772014-06-25 22:19:48 +00001688 // A dllimport variable never acts like a constant.
1689 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001690 return false;
1691 }
1692 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1693 // __declspec(dllimport) must be handled very carefully:
1694 // We must never initialize an expression with the thunk in C++.
1695 // Doing otherwise would allow the same id-expression to yield
1696 // different addresses for the same function in different translation
1697 // units. However, this means that we must dynamically initialize the
1698 // expression with the contents of the import address table at runtime.
1699 //
1700 // The C language has no notion of ODR; furthermore, it has no notion of
1701 // dynamic initialization. This means that we are permitted to
1702 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001703 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001704 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001705 }
1706 }
1707
Richard Smitha8105bc2012-01-06 16:39:00 +00001708 // Allow address constant expressions to be past-the-end pointers. This is
1709 // an extension: the standard requires them to point to an object.
1710 if (!IsReferenceType)
1711 return true;
1712
1713 // A reference constant expression must refer to an object.
1714 if (!Base) {
1715 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001716 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001717 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001718 }
1719
Richard Smith357362d2011-12-13 06:39:58 +00001720 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001721 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001722 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001723 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001724 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001725 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001726 }
1727
Richard Smith80815602011-11-07 05:07:52 +00001728 return true;
1729}
1730
Reid Klecknercd016d82017-07-07 22:04:29 +00001731/// Member pointers are constant expressions unless they point to a
1732/// non-virtual dllimport member function.
1733static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1734 SourceLocation Loc,
1735 QualType Type,
1736 const APValue &Value) {
1737 const ValueDecl *Member = Value.getMemberPointerDecl();
1738 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1739 if (!FD)
1740 return true;
1741 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1742}
1743
Richard Smithfddd3842011-12-30 21:15:51 +00001744/// Check that this core constant expression is of literal type, and if not,
1745/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001746static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001747 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001748 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001749 return true;
1750
Richard Smith7525ff62013-05-09 07:14:00 +00001751 // C++1y: A constant initializer for an object o [...] may also invoke
1752 // constexpr constructors for o and its subobjects even if those objects
1753 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001754 //
1755 // C++11 missed this detail for aggregates, so classes like this:
1756 // struct foo_t { union { int i; volatile int j; } u; };
1757 // are not (obviously) initializable like so:
1758 // __attribute__((__require_constant_initialization__))
1759 // static const foo_t x = {{0}};
1760 // because "i" is a subobject with non-literal initialization (due to the
1761 // volatile member of the union). See:
1762 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1763 // Therefore, we use the C++1y behavior.
1764 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001765 return true;
1766
Richard Smithfddd3842011-12-30 21:15:51 +00001767 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001768 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001769 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001770 << E->getType();
1771 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001772 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001773 return false;
1774}
1775
Richard Smith0b0a0b62011-10-29 20:57:55 +00001776/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001777/// constant expression. If not, report an appropriate diagnostic. Does not
1778/// check that the expression is of literal type.
1779static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1780 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001781 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001782 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001783 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001784 return false;
1785 }
1786
Richard Smith77be48a2014-07-31 06:31:19 +00001787 // We allow _Atomic(T) to be initialized from anything that T can be
1788 // initialized from.
1789 if (const AtomicType *AT = Type->getAs<AtomicType>())
1790 Type = AT->getValueType();
1791
Richard Smithb228a862012-02-15 02:18:13 +00001792 // Core issue 1454: For a literal constant expression of array or class type,
1793 // each subobject of its value shall have been initialized by a constant
1794 // expression.
1795 if (Value.isArray()) {
1796 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1797 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1798 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1799 Value.getArrayInitializedElt(I)))
1800 return false;
1801 }
1802 if (!Value.hasArrayFiller())
1803 return true;
1804 return CheckConstantExpression(Info, DiagLoc, EltTy,
1805 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001806 }
Richard Smithb228a862012-02-15 02:18:13 +00001807 if (Value.isUnion() && Value.getUnionField()) {
1808 return CheckConstantExpression(Info, DiagLoc,
1809 Value.getUnionField()->getType(),
1810 Value.getUnionValue());
1811 }
1812 if (Value.isStruct()) {
1813 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1814 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1815 unsigned BaseIndex = 0;
1816 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1817 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1818 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1819 Value.getStructBase(BaseIndex)))
1820 return false;
1821 }
1822 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001823 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001824 if (I->isUnnamedBitfield())
1825 continue;
1826
David Blaikie2d7c57e2012-04-30 02:36:29 +00001827 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1828 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001829 return false;
1830 }
1831 }
1832
1833 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001834 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001835 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001836 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1837 }
1838
Reid Klecknercd016d82017-07-07 22:04:29 +00001839 if (Value.isMemberPointer())
1840 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1841
Richard Smithb228a862012-02-15 02:18:13 +00001842 // Everything else is fine.
1843 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001844}
1845
Benjamin Kramer8407df72015-03-09 16:47:52 +00001846static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001847 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001848}
1849
1850static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001851 if (Value.CallIndex)
1852 return false;
1853 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1854 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001855}
1856
Richard Smithcecf1842011-11-01 21:06:14 +00001857static bool IsWeakLValue(const LValue &Value) {
1858 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001859 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001860}
1861
David Majnemerb5116032014-12-09 23:32:34 +00001862static bool isZeroSized(const LValue &Value) {
1863 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001864 if (Decl && isa<VarDecl>(Decl)) {
1865 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001866 if (Ty->isArrayType())
1867 return Ty->isIncompleteType() ||
1868 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001869 }
1870 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001871}
1872
Richard Smith2e312c82012-03-03 22:46:17 +00001873static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001874 // A null base expression indicates a null pointer. These are always
1875 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001876 if (!Value.getLValueBase()) {
1877 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001878 return true;
1879 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001880
Richard Smith027bf112011-11-17 22:56:20 +00001881 // We have a non-null base. These are generally known to be true, but if it's
1882 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001883 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001884 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001885 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001886}
1887
Richard Smith2e312c82012-03-03 22:46:17 +00001888static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001889 switch (Val.getKind()) {
1890 case APValue::Uninitialized:
1891 return false;
1892 case APValue::Int:
1893 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001894 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001895 case APValue::Float:
1896 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001897 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001898 case APValue::ComplexInt:
1899 Result = Val.getComplexIntReal().getBoolValue() ||
1900 Val.getComplexIntImag().getBoolValue();
1901 return true;
1902 case APValue::ComplexFloat:
1903 Result = !Val.getComplexFloatReal().isZero() ||
1904 !Val.getComplexFloatImag().isZero();
1905 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001906 case APValue::LValue:
1907 return EvalPointerValueAsBool(Val, Result);
1908 case APValue::MemberPointer:
1909 Result = Val.getMemberPointerDecl();
1910 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001911 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001912 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001913 case APValue::Struct:
1914 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001915 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001916 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001917 }
1918
Richard Smith11562c52011-10-28 17:51:58 +00001919 llvm_unreachable("unknown APValue kind");
1920}
1921
1922static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1923 EvalInfo &Info) {
1924 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001925 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001926 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001927 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001928 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001929}
1930
Richard Smith357362d2011-12-13 06:39:58 +00001931template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001932static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001933 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001934 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001935 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001936 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001937}
1938
1939static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1940 QualType SrcType, const APFloat &Value,
1941 QualType DestType, APSInt &Result) {
1942 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001943 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001944 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smith357362d2011-12-13 06:39:58 +00001946 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001947 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001948 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1949 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001950 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001951 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001952}
1953
Richard Smith357362d2011-12-13 06:39:58 +00001954static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1955 QualType SrcType, QualType DestType,
1956 APFloat &Result) {
1957 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001958 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001959 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1960 APFloat::rmNearestTiesToEven, &ignored)
1961 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001962 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001963 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001964}
1965
Richard Smith911e1422012-01-30 22:27:01 +00001966static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1967 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001968 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001969 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001970 APSInt Result = Value;
1971 // Figure out if this is a truncate, extend or noop cast.
1972 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001974 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001975 return Result;
1976}
1977
Richard Smith357362d2011-12-13 06:39:58 +00001978static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1979 QualType SrcType, const APSInt &Value,
1980 QualType DestType, APFloat &Result) {
1981 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1982 if (Result.convertFromAPInt(Value, Value.isSigned(),
1983 APFloat::rmNearestTiesToEven)
1984 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001985 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001986 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001987}
1988
Richard Smith49ca8aa2013-08-06 07:09:20 +00001989static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1990 APValue &Value, const FieldDecl *FD) {
1991 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1992
1993 if (!Value.isInt()) {
1994 // Trying to store a pointer-cast-to-integer into a bitfield.
1995 // FIXME: In this case, we should provide the diagnostic for casting
1996 // a pointer to an integer.
1997 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001998 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001999 return false;
2000 }
2001
2002 APSInt &Int = Value.getInt();
2003 unsigned OldBitWidth = Int.getBitWidth();
2004 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2005 if (NewBitWidth < OldBitWidth)
2006 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2007 return true;
2008}
2009
Eli Friedman803acb32011-12-22 03:51:45 +00002010static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2011 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002012 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002013 if (!Evaluate(SVal, Info, E))
2014 return false;
2015 if (SVal.isInt()) {
2016 Res = SVal.getInt();
2017 return true;
2018 }
2019 if (SVal.isFloat()) {
2020 Res = SVal.getFloat().bitcastToAPInt();
2021 return true;
2022 }
2023 if (SVal.isVector()) {
2024 QualType VecTy = E->getType();
2025 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2026 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2027 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2028 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2029 Res = llvm::APInt::getNullValue(VecSize);
2030 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2031 APValue &Elt = SVal.getVectorElt(i);
2032 llvm::APInt EltAsInt;
2033 if (Elt.isInt()) {
2034 EltAsInt = Elt.getInt();
2035 } else if (Elt.isFloat()) {
2036 EltAsInt = Elt.getFloat().bitcastToAPInt();
2037 } else {
2038 // Don't try to handle vectors of anything other than int or float
2039 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002040 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002041 return false;
2042 }
2043 unsigned BaseEltSize = EltAsInt.getBitWidth();
2044 if (BigEndian)
2045 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2046 else
2047 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2048 }
2049 return true;
2050 }
2051 // Give up if the input isn't an int, float, or vector. For example, we
2052 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002053 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002054 return false;
2055}
2056
Richard Smith43e77732013-05-07 04:50:00 +00002057/// Perform the given integer operation, which is known to need at most BitWidth
2058/// bits, and check for overflow in the original type (if that type was not an
2059/// unsigned type).
2060template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002061static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2062 const APSInt &LHS, const APSInt &RHS,
2063 unsigned BitWidth, Operation Op,
2064 APSInt &Result) {
2065 if (LHS.isUnsigned()) {
2066 Result = Op(LHS, RHS);
2067 return true;
2068 }
Richard Smith43e77732013-05-07 04:50:00 +00002069
2070 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002071 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002072 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002073 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002074 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002075 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002076 << Result.toString(10) << E->getType();
2077 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002078 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002079 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002080 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002081}
2082
2083/// Perform the given binary integer operation.
2084static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2085 BinaryOperatorKind Opcode, APSInt RHS,
2086 APSInt &Result) {
2087 switch (Opcode) {
2088 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002089 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002090 return false;
2091 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002092 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2093 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002094 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002095 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2096 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002097 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002098 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2099 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002100 case BO_And: Result = LHS & RHS; return true;
2101 case BO_Xor: Result = LHS ^ RHS; return true;
2102 case BO_Or: Result = LHS | RHS; return true;
2103 case BO_Div:
2104 case BO_Rem:
2105 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002106 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002107 return false;
2108 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002109 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2110 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2111 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002112 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2113 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002114 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2115 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002116 return true;
2117 case BO_Shl: {
2118 if (Info.getLangOpts().OpenCL)
2119 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2120 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2121 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2122 RHS.isUnsigned());
2123 else if (RHS.isSigned() && RHS.isNegative()) {
2124 // During constant-folding, a negative shift is an opposite shift. Such
2125 // a shift is not a constant expression.
2126 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2127 RHS = -RHS;
2128 goto shift_right;
2129 }
2130 shift_left:
2131 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2132 // the shifted type.
2133 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2134 if (SA != RHS) {
2135 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2136 << RHS << E->getType() << LHS.getBitWidth();
2137 } else if (LHS.isSigned()) {
2138 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2139 // operand, and must not overflow the corresponding unsigned type.
2140 if (LHS.isNegative())
2141 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2142 else if (LHS.countLeadingZeros() < SA)
2143 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2144 }
2145 Result = LHS << SA;
2146 return true;
2147 }
2148 case BO_Shr: {
2149 if (Info.getLangOpts().OpenCL)
2150 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2151 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2152 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2153 RHS.isUnsigned());
2154 else if (RHS.isSigned() && RHS.isNegative()) {
2155 // During constant-folding, a negative shift is an opposite shift. Such a
2156 // shift is not a constant expression.
2157 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2158 RHS = -RHS;
2159 goto shift_left;
2160 }
2161 shift_right:
2162 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2163 // shifted type.
2164 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2165 if (SA != RHS)
2166 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2167 << RHS << E->getType() << LHS.getBitWidth();
2168 Result = LHS >> SA;
2169 return true;
2170 }
2171
2172 case BO_LT: Result = LHS < RHS; return true;
2173 case BO_GT: Result = LHS > RHS; return true;
2174 case BO_LE: Result = LHS <= RHS; return true;
2175 case BO_GE: Result = LHS >= RHS; return true;
2176 case BO_EQ: Result = LHS == RHS; return true;
2177 case BO_NE: Result = LHS != RHS; return true;
2178 }
2179}
2180
Richard Smith861b5b52013-05-07 23:34:45 +00002181/// Perform the given binary floating-point operation, in-place, on LHS.
2182static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2183 APFloat &LHS, BinaryOperatorKind Opcode,
2184 const APFloat &RHS) {
2185 switch (Opcode) {
2186 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002187 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002188 return false;
2189 case BO_Mul:
2190 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2191 break;
2192 case BO_Add:
2193 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2194 break;
2195 case BO_Sub:
2196 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2197 break;
2198 case BO_Div:
2199 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2200 break;
2201 }
2202
Richard Smith0c6124b2015-12-03 01:36:22 +00002203 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002204 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002205 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002206 }
Richard Smith861b5b52013-05-07 23:34:45 +00002207 return true;
2208}
2209
Richard Smitha8105bc2012-01-06 16:39:00 +00002210/// Cast an lvalue referring to a base subobject to a derived class, by
2211/// truncating the lvalue's path to the given length.
2212static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2213 const RecordDecl *TruncatedType,
2214 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002215 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002216
2217 // Check we actually point to a derived class object.
2218 if (TruncatedElements == D.Entries.size())
2219 return true;
2220 assert(TruncatedElements >= D.MostDerivedPathLength &&
2221 "not casting to a derived class");
2222 if (!Result.checkSubobject(Info, E, CSK_Derived))
2223 return false;
2224
2225 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002226 const RecordDecl *RD = TruncatedType;
2227 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002228 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002229 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2230 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002231 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002232 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002233 else
Richard Smithd62306a2011-11-10 06:34:14 +00002234 Result.Offset -= Layout.getBaseClassOffset(Base);
2235 RD = Base;
2236 }
Richard Smith027bf112011-11-17 22:56:20 +00002237 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002238 return true;
2239}
2240
John McCalld7bca762012-05-01 00:38:49 +00002241static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002242 const CXXRecordDecl *Derived,
2243 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002244 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002245 if (!RL) {
2246 if (Derived->isInvalidDecl()) return false;
2247 RL = &Info.Ctx.getASTRecordLayout(Derived);
2248 }
2249
Richard Smithd62306a2011-11-10 06:34:14 +00002250 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002251 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002252 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002253}
2254
Richard Smitha8105bc2012-01-06 16:39:00 +00002255static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002256 const CXXRecordDecl *DerivedDecl,
2257 const CXXBaseSpecifier *Base) {
2258 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2259
John McCalld7bca762012-05-01 00:38:49 +00002260 if (!Base->isVirtual())
2261 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002262
Richard Smitha8105bc2012-01-06 16:39:00 +00002263 SubobjectDesignator &D = Obj.Designator;
2264 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002265 return false;
2266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267 // Extract most-derived object and corresponding type.
2268 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2269 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2270 return false;
2271
2272 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002273 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002274 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2275 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002276 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002277 return true;
2278}
2279
Richard Smith84401042013-06-03 05:03:02 +00002280static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2281 QualType Type, LValue &Result) {
2282 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2283 PathE = E->path_end();
2284 PathI != PathE; ++PathI) {
2285 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2286 *PathI))
2287 return false;
2288 Type = (*PathI)->getType();
2289 }
2290 return true;
2291}
2292
Richard Smithd62306a2011-11-10 06:34:14 +00002293/// Update LVal to refer to the given field, which must be a member of the type
2294/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002295static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002296 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002297 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002298 if (!RL) {
2299 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002300 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002301 }
Richard Smithd62306a2011-11-10 06:34:14 +00002302
2303 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002304 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002305 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002306 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002307}
2308
Richard Smith1b78b3d2012-01-25 22:15:11 +00002309/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002310static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002311 LValue &LVal,
2312 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002313 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002314 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002315 return false;
2316 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002317}
2318
Richard Smithd62306a2011-11-10 06:34:14 +00002319/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002320static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2321 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002322 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2323 // extension.
2324 if (Type->isVoidType() || Type->isFunctionType()) {
2325 Size = CharUnits::One();
2326 return true;
2327 }
2328
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002329 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002330 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002331 return false;
2332 }
2333
Richard Smithd62306a2011-11-10 06:34:14 +00002334 if (!Type->isConstantSizeType()) {
2335 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002336 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002337 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002338 return false;
2339 }
2340
2341 Size = Info.Ctx.getTypeSizeInChars(Type);
2342 return true;
2343}
2344
2345/// Update a pointer value to model pointer arithmetic.
2346/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002347/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002348/// \param LVal - The pointer value to be updated.
2349/// \param EltTy - The pointee type represented by LVal.
2350/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002351static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2352 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002353 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002354 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002355 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002356 return false;
2357
Yaxun Liu402804b2016-12-15 08:09:08 +00002358 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002359 return true;
2360}
2361
Richard Smithd6cc1982017-01-31 02:23:02 +00002362static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2363 LValue &LVal, QualType EltTy,
2364 int64_t Adjustment) {
2365 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2366 APSInt::get(Adjustment));
2367}
2368
Richard Smith66c96992012-02-18 22:04:06 +00002369/// Update an lvalue to refer to a component of a complex number.
2370/// \param Info - Information about the ongoing evaluation.
2371/// \param LVal - The lvalue to be updated.
2372/// \param EltTy - The complex number's component type.
2373/// \param Imag - False for the real component, true for the imaginary.
2374static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2375 LValue &LVal, QualType EltTy,
2376 bool Imag) {
2377 if (Imag) {
2378 CharUnits SizeOfComponent;
2379 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2380 return false;
2381 LVal.Offset += SizeOfComponent;
2382 }
2383 LVal.addComplex(Info, E, EltTy, Imag);
2384 return true;
2385}
2386
Faisal Vali051e3a22017-02-16 04:12:21 +00002387static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2388 QualType Type, const LValue &LVal,
2389 APValue &RVal);
2390
Richard Smith27908702011-10-24 17:54:18 +00002391/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002392///
2393/// \param Info Information about the ongoing evaluation.
2394/// \param E An expression to be used when printing diagnostics.
2395/// \param VD The variable whose initializer should be obtained.
2396/// \param Frame The frame in which the variable was created. Must be null
2397/// if this variable is not local to the evaluation.
2398/// \param Result Filled in with a pointer to the value of the variable.
2399static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2400 const VarDecl *VD, CallStackFrame *Frame,
2401 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002402
Richard Smith254a73d2011-10-28 22:34:42 +00002403 // If this is a parameter to an active constexpr function call, perform
2404 // argument substitution.
2405 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002406 // Assume arguments of a potential constant expression are unknown
2407 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002408 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002409 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002410 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002411 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002412 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002413 }
Richard Smith3229b742013-05-05 21:17:10 +00002414 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002415 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002416 }
Richard Smith27908702011-10-24 17:54:18 +00002417
Richard Smithd9f663b2013-04-22 15:31:51 +00002418 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002419 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002420 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002421 if (!Result) {
2422 // Assume variables referenced within a lambda's call operator that were
2423 // not declared within the call operator are captures and during checking
2424 // of a potential constant expression, assume they are unknown constant
2425 // expressions.
2426 assert(isLambdaCallOperator(Frame->Callee) &&
2427 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2428 "missing value for local variable");
2429 if (Info.checkingPotentialConstantExpression())
2430 return false;
2431 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002432 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002433 diag::note_unimplemented_constexpr_lambda_feature_ast)
2434 << "captures not currently allowed";
2435 return false;
2436 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002437 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002438 }
2439
Richard Smithd0b4dd62011-12-19 06:19:21 +00002440 // Dig out the initializer, and use the declaration which it's attached to.
2441 const Expr *Init = VD->getAnyInitializer(VD);
2442 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002443 // If we're checking a potential constant expression, the variable could be
2444 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002445 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002446 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002447 return false;
2448 }
2449
Richard Smithd62306a2011-11-10 06:34:14 +00002450 // If we're currently evaluating the initializer of this declaration, use that
2451 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002452 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002453 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002454 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002455 }
2456
Richard Smithcecf1842011-11-01 21:06:14 +00002457 // Never evaluate the initializer of a weak variable. We can't be sure that
2458 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002459 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002460 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002461 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002462 }
Richard Smithcecf1842011-11-01 21:06:14 +00002463
Richard Smithd0b4dd62011-12-19 06:19:21 +00002464 // Check that we can fold the initializer. In C++, we will have already done
2465 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002466 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002467 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002468 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002469 Notes.size() + 1) << VD;
2470 Info.Note(VD->getLocation(), diag::note_declared_at);
2471 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002472 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002473 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002474 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002475 Notes.size() + 1) << VD;
2476 Info.Note(VD->getLocation(), diag::note_declared_at);
2477 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002478 }
Richard Smith27908702011-10-24 17:54:18 +00002479
Richard Smith3229b742013-05-05 21:17:10 +00002480 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002481 return true;
Richard Smith27908702011-10-24 17:54:18 +00002482}
2483
Richard Smith11562c52011-10-28 17:51:58 +00002484static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002485 Qualifiers Quals = T.getQualifiers();
2486 return Quals.hasConst() && !Quals.hasVolatile();
2487}
2488
Richard Smithe97cbd72011-11-11 04:05:33 +00002489/// Get the base index of the given base class within an APValue representing
2490/// the given derived class.
2491static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2492 const CXXRecordDecl *Base) {
2493 Base = Base->getCanonicalDecl();
2494 unsigned Index = 0;
2495 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2496 E = Derived->bases_end(); I != E; ++I, ++Index) {
2497 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2498 return Index;
2499 }
2500
2501 llvm_unreachable("base class missing from derived class's bases list");
2502}
2503
Richard Smith3da88fa2013-04-26 14:36:30 +00002504/// Extract the value of a character from a string literal.
2505static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2506 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002507 // FIXME: Support MakeStringConstant
2508 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2509 std::string Str;
2510 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2511 assert(Index <= Str.size() && "Index too large");
2512 return APSInt::getUnsigned(Str.c_str()[Index]);
2513 }
2514
Alexey Bataevec474782014-10-09 08:45:04 +00002515 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2516 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002517 const StringLiteral *S = cast<StringLiteral>(Lit);
2518 const ConstantArrayType *CAT =
2519 Info.Ctx.getAsConstantArrayType(S->getType());
2520 assert(CAT && "string literal isn't an array");
2521 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002522 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002523
2524 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002525 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002526 if (Index < S->getLength())
2527 Value = S->getCodeUnit(Index);
2528 return Value;
2529}
2530
Richard Smith3da88fa2013-04-26 14:36:30 +00002531// Expand a string literal into an array of characters.
2532static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2533 APValue &Result) {
2534 const StringLiteral *S = cast<StringLiteral>(Lit);
2535 const ConstantArrayType *CAT =
2536 Info.Ctx.getAsConstantArrayType(S->getType());
2537 assert(CAT && "string literal isn't an array");
2538 QualType CharType = CAT->getElementType();
2539 assert(CharType->isIntegerType() && "unexpected character type");
2540
2541 unsigned Elts = CAT->getSize().getZExtValue();
2542 Result = APValue(APValue::UninitArray(),
2543 std::min(S->getLength(), Elts), Elts);
2544 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2545 CharType->isUnsignedIntegerType());
2546 if (Result.hasArrayFiller())
2547 Result.getArrayFiller() = APValue(Value);
2548 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2549 Value = S->getCodeUnit(I);
2550 Result.getArrayInitializedElt(I) = APValue(Value);
2551 }
2552}
2553
2554// Expand an array so that it has more than Index filled elements.
2555static void expandArray(APValue &Array, unsigned Index) {
2556 unsigned Size = Array.getArraySize();
2557 assert(Index < Size);
2558
2559 // Always at least double the number of elements for which we store a value.
2560 unsigned OldElts = Array.getArrayInitializedElts();
2561 unsigned NewElts = std::max(Index+1, OldElts * 2);
2562 NewElts = std::min(Size, std::max(NewElts, 8u));
2563
2564 // Copy the data across.
2565 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2566 for (unsigned I = 0; I != OldElts; ++I)
2567 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2568 for (unsigned I = OldElts; I != NewElts; ++I)
2569 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2570 if (NewValue.hasArrayFiller())
2571 NewValue.getArrayFiller() = Array.getArrayFiller();
2572 Array.swap(NewValue);
2573}
2574
Richard Smithb01fe402014-09-16 01:24:02 +00002575/// Determine whether a type would actually be read by an lvalue-to-rvalue
2576/// conversion. If it's of class type, we may assume that the copy operation
2577/// is trivial. Note that this is never true for a union type with fields
2578/// (because the copy always "reads" the active member) and always true for
2579/// a non-class type.
2580static bool isReadByLvalueToRvalueConversion(QualType T) {
2581 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2582 if (!RD || (RD->isUnion() && !RD->field_empty()))
2583 return true;
2584 if (RD->isEmpty())
2585 return false;
2586
2587 for (auto *Field : RD->fields())
2588 if (isReadByLvalueToRvalueConversion(Field->getType()))
2589 return true;
2590
2591 for (auto &BaseSpec : RD->bases())
2592 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2593 return true;
2594
2595 return false;
2596}
2597
2598/// Diagnose an attempt to read from any unreadable field within the specified
2599/// type, which might be a class type.
2600static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2601 QualType T) {
2602 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2603 if (!RD)
2604 return false;
2605
2606 if (!RD->hasMutableFields())
2607 return false;
2608
2609 for (auto *Field : RD->fields()) {
2610 // If we're actually going to read this field in some way, then it can't
2611 // be mutable. If we're in a union, then assigning to a mutable field
2612 // (even an empty one) can change the active member, so that's not OK.
2613 // FIXME: Add core issue number for the union case.
2614 if (Field->isMutable() &&
2615 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002616 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002617 Info.Note(Field->getLocation(), diag::note_declared_at);
2618 return true;
2619 }
2620
2621 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2622 return true;
2623 }
2624
2625 for (auto &BaseSpec : RD->bases())
2626 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2627 return true;
2628
2629 // All mutable fields were empty, and thus not actually read.
2630 return false;
2631}
2632
Richard Smith861b5b52013-05-07 23:34:45 +00002633/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002634enum AccessKinds {
2635 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002636 AK_Assign,
2637 AK_Increment,
2638 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002639};
2640
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002641namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002642/// A handle to a complete object (an object that is not a subobject of
2643/// another object).
2644struct CompleteObject {
2645 /// The value of the complete object.
2646 APValue *Value;
2647 /// The type of the complete object.
2648 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002649 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002650
Craig Topper36250ad2014-05-12 05:36:57 +00002651 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002652 CompleteObject(APValue *Value, QualType Type,
2653 bool LifetimeStartedInEvaluation)
2654 : Value(Value), Type(Type),
2655 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002656 assert(Value && "missing value for complete object");
2657 }
2658
Aaron Ballman67347662015-02-15 22:00:28 +00002659 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002660};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002661} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002662
Richard Smith3da88fa2013-04-26 14:36:30 +00002663/// Find the designated sub-object of an rvalue.
2664template<typename SubobjectHandler>
2665typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002666findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002667 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002668 if (Sub.Invalid)
2669 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002670 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002671 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002672 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002673 Info.FFDiag(E, Sub.isOnePastTheEnd()
2674 ? diag::note_constexpr_access_past_end
2675 : diag::note_constexpr_access_unsized_array)
2676 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002677 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002678 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002680 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002681
Richard Smith3229b742013-05-05 21:17:10 +00002682 APValue *O = Obj.Value;
2683 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002684 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002685 const bool MayReadMutableMembers =
2686 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002687
Richard Smithd62306a2011-11-10 06:34:14 +00002688 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002689 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2690 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002691 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002692 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002693 return handler.failed();
2694 }
2695
Richard Smith49ca8aa2013-08-06 07:09:20 +00002696 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002697 // If we are reading an object of class type, there may still be more
2698 // things we need to check: if there are any mutable subobjects, we
2699 // cannot perform this read. (This only happens when performing a trivial
2700 // copy or assignment.)
2701 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002702 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002703 return handler.failed();
2704
Richard Smith49ca8aa2013-08-06 07:09:20 +00002705 if (!handler.found(*O, ObjType))
2706 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002707
Richard Smith49ca8aa2013-08-06 07:09:20 +00002708 // If we modified a bit-field, truncate it to the right width.
2709 if (handler.AccessKind != AK_Read &&
2710 LastField && LastField->isBitField() &&
2711 !truncateBitfieldValue(Info, E, *O, LastField))
2712 return false;
2713
2714 return true;
2715 }
2716
Craig Topper36250ad2014-05-12 05:36:57 +00002717 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002718 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002719 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002720 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002721 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002722 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002723 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002724 // Note, it should not be possible to form a pointer with a valid
2725 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002726 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002727 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002728 << handler.AccessKind;
2729 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002730 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002731 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002732 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002733
2734 ObjType = CAT->getElementType();
2735
Richard Smith14a94132012-02-17 03:35:37 +00002736 // An array object is represented as either an Array APValue or as an
2737 // LValue which refers to a string literal.
2738 if (O->isLValue()) {
2739 assert(I == N - 1 && "extracting subobject of character?");
2740 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002741 if (handler.AccessKind != AK_Read)
2742 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2743 *O);
2744 else
2745 return handler.foundString(*O, ObjType, Index);
2746 }
2747
2748 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002749 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002750 else if (handler.AccessKind != AK_Read) {
2751 expandArray(*O, Index);
2752 O = &O->getArrayInitializedElt(Index);
2753 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002754 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002755 } else if (ObjType->isAnyComplexType()) {
2756 // Next subobject is a complex number.
2757 uint64_t Index = Sub.Entries[I].ArrayIndex;
2758 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002759 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002760 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002761 << handler.AccessKind;
2762 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002763 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002765 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002766
2767 bool WasConstQualified = ObjType.isConstQualified();
2768 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2769 if (WasConstQualified)
2770 ObjType.addConst();
2771
Richard Smith66c96992012-02-18 22:04:06 +00002772 assert(I == N - 1 && "extracting subobject of scalar?");
2773 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002774 return handler.found(Index ? O->getComplexIntImag()
2775 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002776 } else {
2777 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return handler.found(Index ? O->getComplexFloatImag()
2779 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002780 }
Richard Smithd62306a2011-11-10 06:34:14 +00002781 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002782 // In C++14 onwards, it is permitted to read a mutable member whose
2783 // lifetime began within the evaluation.
2784 // FIXME: Should we also allow this in C++11?
2785 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2786 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002787 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002788 << Field;
2789 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002791 }
2792
Richard Smithd62306a2011-11-10 06:34:14 +00002793 // Next subobject is a class, struct or union field.
2794 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2795 if (RD->isUnion()) {
2796 const FieldDecl *UnionField = O->getUnionField();
2797 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002798 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002800 << handler.AccessKind << Field << !UnionField << UnionField;
2801 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002802 }
Richard Smithd62306a2011-11-10 06:34:14 +00002803 O = &O->getUnionValue();
2804 } else
2805 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002806
2807 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002808 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002809 if (WasConstQualified && !Field->isMutable())
2810 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002811
2812 if (ObjType.isVolatileQualified()) {
2813 if (Info.getLangOpts().CPlusPlus) {
2814 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002815 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002816 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002817 Info.Note(Field->getLocation(), diag::note_declared_at);
2818 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002819 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002820 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002821 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002822 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002823
2824 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002825 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002826 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002827 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2828 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2829 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002830
2831 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002832 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 if (WasConstQualified)
2834 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002835 }
2836 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002837}
2838
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002839namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002840struct ExtractSubobjectHandler {
2841 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002842 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002843
2844 static const AccessKinds AccessKind = AK_Read;
2845
2846 typedef bool result_type;
2847 bool failed() { return false; }
2848 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002849 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002850 return true;
2851 }
2852 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002853 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002854 return true;
2855 }
2856 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002857 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002858 return true;
2859 }
2860 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2863 return true;
2864 }
2865};
Richard Smith3229b742013-05-05 21:17:10 +00002866} // end anonymous namespace
2867
Richard Smith3da88fa2013-04-26 14:36:30 +00002868const AccessKinds ExtractSubobjectHandler::AccessKind;
2869
2870/// Extract the designated sub-object of an rvalue.
2871static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002872 const CompleteObject &Obj,
2873 const SubobjectDesignator &Sub,
2874 APValue &Result) {
2875 ExtractSubobjectHandler Handler = { Info, Result };
2876 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002877}
2878
Richard Smith3229b742013-05-05 21:17:10 +00002879namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002880struct ModifySubobjectHandler {
2881 EvalInfo &Info;
2882 APValue &NewVal;
2883 const Expr *E;
2884
2885 typedef bool result_type;
2886 static const AccessKinds AccessKind = AK_Assign;
2887
2888 bool checkConst(QualType QT) {
2889 // Assigning to a const object has undefined behavior.
2890 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002891 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002892 return false;
2893 }
2894 return true;
2895 }
2896
2897 bool failed() { return false; }
2898 bool found(APValue &Subobj, QualType SubobjType) {
2899 if (!checkConst(SubobjType))
2900 return false;
2901 // We've been given ownership of NewVal, so just swap it in.
2902 Subobj.swap(NewVal);
2903 return true;
2904 }
2905 bool found(APSInt &Value, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2907 return false;
2908 if (!NewVal.isInt()) {
2909 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002910 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002911 return false;
2912 }
2913 Value = NewVal.getInt();
2914 return true;
2915 }
2916 bool found(APFloat &Value, QualType SubobjType) {
2917 if (!checkConst(SubobjType))
2918 return false;
2919 Value = NewVal.getFloat();
2920 return true;
2921 }
2922 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2923 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2924 }
2925};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002926} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002927
Richard Smith3229b742013-05-05 21:17:10 +00002928const AccessKinds ModifySubobjectHandler::AccessKind;
2929
Richard Smith3da88fa2013-04-26 14:36:30 +00002930/// Update the designated sub-object of an rvalue to the given value.
2931static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002932 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002933 const SubobjectDesignator &Sub,
2934 APValue &NewVal) {
2935 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002936 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002937}
2938
Richard Smith84f6dcf2012-02-02 01:16:57 +00002939/// Find the position where two subobject designators diverge, or equivalently
2940/// the length of the common initial subsequence.
2941static unsigned FindDesignatorMismatch(QualType ObjType,
2942 const SubobjectDesignator &A,
2943 const SubobjectDesignator &B,
2944 bool &WasArrayIndex) {
2945 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2946 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002947 if (!ObjType.isNull() &&
2948 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002949 // Next subobject is an array element.
2950 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2951 WasArrayIndex = true;
2952 return I;
2953 }
Richard Smith66c96992012-02-18 22:04:06 +00002954 if (ObjType->isAnyComplexType())
2955 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2956 else
2957 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002958 } else {
2959 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2960 WasArrayIndex = false;
2961 return I;
2962 }
2963 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2964 // Next subobject is a field.
2965 ObjType = FD->getType();
2966 else
2967 // Next subobject is a base class.
2968 ObjType = QualType();
2969 }
2970 }
2971 WasArrayIndex = false;
2972 return I;
2973}
2974
2975/// Determine whether the given subobject designators refer to elements of the
2976/// same array object.
2977static bool AreElementsOfSameArray(QualType ObjType,
2978 const SubobjectDesignator &A,
2979 const SubobjectDesignator &B) {
2980 if (A.Entries.size() != B.Entries.size())
2981 return false;
2982
George Burgess IVa51c4072015-10-16 01:49:01 +00002983 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002984 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2985 // A is a subobject of the array element.
2986 return false;
2987
2988 // If A (and B) designates an array element, the last entry will be the array
2989 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2990 // of length 1' case, and the entire path must match.
2991 bool WasArrayIndex;
2992 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2993 return CommonLength >= A.Entries.size() - IsArray;
2994}
2995
Richard Smith3229b742013-05-05 21:17:10 +00002996/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002997static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2998 AccessKinds AK, const LValue &LVal,
2999 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003000 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003001 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003002 return CompleteObject();
3003 }
3004
Craig Topper36250ad2014-05-12 05:36:57 +00003005 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003006 if (LVal.CallIndex) {
3007 Frame = Info.getCallFrame(LVal.CallIndex);
3008 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003009 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003010 << AK << LVal.Base.is<const ValueDecl*>();
3011 NoteLValueLocation(Info, LVal.Base);
3012 return CompleteObject();
3013 }
Richard Smith3229b742013-05-05 21:17:10 +00003014 }
3015
3016 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3017 // is not a constant expression (even if the object is non-volatile). We also
3018 // apply this rule to C++98, in order to conform to the expected 'volatile'
3019 // semantics.
3020 if (LValType.isVolatileQualified()) {
3021 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003022 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003023 << AK << LValType;
3024 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003025 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003026 return CompleteObject();
3027 }
3028
3029 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003030 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003031 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003032 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003033
3034 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3035 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3036 // In C++11, constexpr, non-volatile variables initialized with constant
3037 // expressions are constant expressions too. Inside constexpr functions,
3038 // parameters are constant expressions even if they're non-const.
3039 // In C++1y, objects local to a constant expression (those with a Frame) are
3040 // both readable and writable inside constant expressions.
3041 // In C, such things can also be folded, although they are not ICEs.
3042 const VarDecl *VD = dyn_cast<VarDecl>(D);
3043 if (VD) {
3044 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3045 VD = VDef;
3046 }
3047 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003048 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003049 return CompleteObject();
3050 }
3051
3052 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003053 if (BaseType.isVolatileQualified()) {
3054 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003056 << AK << 1 << VD;
3057 Info.Note(VD->getLocation(), diag::note_declared_at);
3058 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003059 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003060 }
3061 return CompleteObject();
3062 }
3063
3064 // Unless we're looking at a local variable or argument in a constexpr call,
3065 // the variable we're reading must be const.
3066 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003067 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003068 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3069 // OK, we can read and modify an object if we're in the process of
3070 // evaluating its initializer, because its lifetime began in this
3071 // evaluation.
3072 } else if (AK != AK_Read) {
3073 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003074 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003075 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003076 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003077 // OK, we can read this variable.
3078 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003079 // In OpenCL if a variable is in constant address space it is a const value.
3080 if (!(BaseType.isConstQualified() ||
3081 (Info.getLangOpts().OpenCL &&
3082 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003083 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003084 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003085 Info.Note(VD->getLocation(), diag::note_declared_at);
3086 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003087 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003088 }
3089 return CompleteObject();
3090 }
3091 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3092 // We support folding of const floating-point types, in order to make
3093 // static const data members of such types (supported as an extension)
3094 // more useful.
3095 if (Info.getLangOpts().CPlusPlus11) {
3096 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3097 Info.Note(VD->getLocation(), diag::note_declared_at);
3098 } else {
3099 Info.CCEDiag(E);
3100 }
George Burgess IVb5316982016-12-27 05:33:20 +00003101 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3102 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3103 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003104 } else {
3105 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003106 if (Info.checkingPotentialConstantExpression() &&
3107 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3108 // The definition of this variable could be constexpr. We can't
3109 // access it right now, but may be able to in future.
3110 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003111 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003112 Info.Note(VD->getLocation(), diag::note_declared_at);
3113 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003114 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003115 }
3116 return CompleteObject();
3117 }
3118 }
3119
3120 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3121 return CompleteObject();
3122 } else {
3123 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3124
3125 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003126 if (const MaterializeTemporaryExpr *MTE =
3127 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3128 assert(MTE->getStorageDuration() == SD_Static &&
3129 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003130
Richard Smithe6c01442013-06-05 00:46:14 +00003131 // Per C++1y [expr.const]p2:
3132 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3133 // - a [...] glvalue of integral or enumeration type that refers to
3134 // a non-volatile const object [...]
3135 // [...]
3136 // - a [...] glvalue of literal type that refers to a non-volatile
3137 // object whose lifetime began within the evaluation of e.
3138 //
3139 // C++11 misses the 'began within the evaluation of e' check and
3140 // instead allows all temporaries, including things like:
3141 // int &&r = 1;
3142 // int x = ++r;
3143 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003144 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003145 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3146 const ValueDecl *ED = MTE->getExtendingDecl();
3147 if (!(BaseType.isConstQualified() &&
3148 BaseType->isIntegralOrEnumerationType()) &&
3149 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003151 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3152 return CompleteObject();
3153 }
3154
3155 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3156 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003157 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003158 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003159 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003160 return CompleteObject();
3161 }
3162 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003163 BaseVal = Frame->getTemporary(Base);
3164 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003165 }
Richard Smith3229b742013-05-05 21:17:10 +00003166
3167 // Volatile temporary objects cannot be accessed in constant expressions.
3168 if (BaseType.isVolatileQualified()) {
3169 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003170 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003171 << AK << 0;
3172 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3173 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003174 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003175 }
3176 return CompleteObject();
3177 }
3178 }
3179
Richard Smith7525ff62013-05-09 07:14:00 +00003180 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003181 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003182 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003183 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003184 BaseType = Info.Ctx.getCanonicalType(BaseType);
3185 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003186 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003187 }
3188
Richard Smith9defb7d2018-02-21 03:38:30 +00003189 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003190 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003191 //
3192 // FIXME: Not all local state is mutable. Allow local constant subobjects
3193 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003194 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3195 Info.EvalStatus.HasSideEffects) ||
3196 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003197 return CompleteObject();
3198
Richard Smith9defb7d2018-02-21 03:38:30 +00003199 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003200}
3201
Richard Smith243ef902013-05-05 23:31:59 +00003202/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3203/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3204/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003205///
3206/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003207/// \param Conv - The expression for which we are performing the conversion.
3208/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003209/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3210/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003211/// \param LVal - The glvalue on which we are attempting to perform this action.
3212/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003213static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003214 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003215 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003216 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003217 return false;
3218
Richard Smith3229b742013-05-05 21:17:10 +00003219 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003220 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003221 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003222 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3223 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3224 // initializer until now for such expressions. Such an expression can't be
3225 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003226 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003228 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003229 }
Richard Smith3229b742013-05-05 21:17:10 +00003230 APValue Lit;
3231 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3232 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003233 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003234 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003235 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003236 // We represent a string literal array as an lvalue pointing at the
3237 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003238 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003239 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003240 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003241 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003242 }
Richard Smith11562c52011-10-28 17:51:58 +00003243 }
3244
Richard Smith3229b742013-05-05 21:17:10 +00003245 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3246 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003247}
3248
3249/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003250static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003251 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003252 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003253 return false;
3254
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003255 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003256 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003257 return false;
3258 }
3259
Richard Smith3229b742013-05-05 21:17:10 +00003260 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003261 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3262}
3263
3264namespace {
3265struct CompoundAssignSubobjectHandler {
3266 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003267 const Expr *E;
3268 QualType PromotedLHSType;
3269 BinaryOperatorKind Opcode;
3270 const APValue &RHS;
3271
3272 static const AccessKinds AccessKind = AK_Assign;
3273
3274 typedef bool result_type;
3275
3276 bool checkConst(QualType QT) {
3277 // Assigning to a const object has undefined behavior.
3278 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003279 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003280 return false;
3281 }
3282 return true;
3283 }
3284
3285 bool failed() { return false; }
3286 bool found(APValue &Subobj, QualType SubobjType) {
3287 switch (Subobj.getKind()) {
3288 case APValue::Int:
3289 return found(Subobj.getInt(), SubobjType);
3290 case APValue::Float:
3291 return found(Subobj.getFloat(), SubobjType);
3292 case APValue::ComplexInt:
3293 case APValue::ComplexFloat:
3294 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003296 return false;
3297 case APValue::LValue:
3298 return foundPointer(Subobj, SubobjType);
3299 default:
3300 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003301 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003302 return false;
3303 }
3304 }
3305 bool found(APSInt &Value, QualType SubobjType) {
3306 if (!checkConst(SubobjType))
3307 return false;
3308
3309 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3310 // We don't support compound assignment on integer-cast-to-pointer
3311 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003312 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003313 return false;
3314 }
3315
3316 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3317 SubobjType, Value);
3318 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3319 return false;
3320 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3321 return true;
3322 }
3323 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003324 return checkConst(SubobjType) &&
3325 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3326 Value) &&
3327 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3328 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003329 }
3330 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3331 if (!checkConst(SubobjType))
3332 return false;
3333
3334 QualType PointeeType;
3335 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3336 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003337
3338 if (PointeeType.isNull() || !RHS.isInt() ||
3339 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003340 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003341 return false;
3342 }
3343
Richard Smithd6cc1982017-01-31 02:23:02 +00003344 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003345 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003346 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003347
3348 LValue LVal;
3349 LVal.setFrom(Info.Ctx, Subobj);
3350 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3351 return false;
3352 LVal.moveInto(Subobj);
3353 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003354 }
3355 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3356 llvm_unreachable("shouldn't encounter string elements here");
3357 }
3358};
3359} // end anonymous namespace
3360
3361const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3362
3363/// Perform a compound assignment of LVal <op>= RVal.
3364static bool handleCompoundAssignment(
3365 EvalInfo &Info, const Expr *E,
3366 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3367 BinaryOperatorKind Opcode, const APValue &RVal) {
3368 if (LVal.Designator.Invalid)
3369 return false;
3370
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003371 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003372 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003373 return false;
3374 }
3375
3376 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3377 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3378 RVal };
3379 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3380}
3381
Aaron Ballmana5038552018-01-09 13:07:03 +00003382namespace {
3383struct IncDecSubobjectHandler {
3384 EvalInfo &Info;
3385 const UnaryOperator *E;
3386 AccessKinds AccessKind;
3387 APValue *Old;
3388
Richard Smith243ef902013-05-05 23:31:59 +00003389 typedef bool result_type;
3390
3391 bool checkConst(QualType QT) {
3392 // Assigning to a const object has undefined behavior.
3393 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003394 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003395 return false;
3396 }
3397 return true;
3398 }
3399
3400 bool failed() { return false; }
3401 bool found(APValue &Subobj, QualType SubobjType) {
3402 // Stash the old value. Also clear Old, so we don't clobber it later
3403 // if we're post-incrementing a complex.
3404 if (Old) {
3405 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003406 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003407 }
3408
3409 switch (Subobj.getKind()) {
3410 case APValue::Int:
3411 return found(Subobj.getInt(), SubobjType);
3412 case APValue::Float:
3413 return found(Subobj.getFloat(), SubobjType);
3414 case APValue::ComplexInt:
3415 return found(Subobj.getComplexIntReal(),
3416 SubobjType->castAs<ComplexType>()->getElementType()
3417 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3418 case APValue::ComplexFloat:
3419 return found(Subobj.getComplexFloatReal(),
3420 SubobjType->castAs<ComplexType>()->getElementType()
3421 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422 case APValue::LValue:
3423 return foundPointer(Subobj, SubobjType);
3424 default:
3425 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003426 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003427 return false;
3428 }
3429 }
3430 bool found(APSInt &Value, QualType SubobjType) {
3431 if (!checkConst(SubobjType))
3432 return false;
3433
3434 if (!SubobjType->isIntegerType()) {
3435 // We don't support increment / decrement on integer-cast-to-pointer
3436 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003437 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003438 return false;
3439 }
3440
3441 if (Old) *Old = APValue(Value);
3442
3443 // bool arithmetic promotes to int, and the conversion back to bool
3444 // doesn't reduce mod 2^n, so special-case it.
3445 if (SubobjType->isBooleanType()) {
3446 if (AccessKind == AK_Increment)
3447 Value = 1;
3448 else
3449 Value = !Value;
3450 return true;
3451 }
3452
3453 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003454 if (AccessKind == AK_Increment) {
3455 ++Value;
3456
3457 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3458 APSInt ActualValue(Value, /*IsUnsigned*/true);
3459 return HandleOverflow(Info, E, ActualValue, SubobjType);
3460 }
3461 } else {
3462 --Value;
3463
3464 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3465 unsigned BitWidth = Value.getBitWidth();
3466 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3467 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003468 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003469 }
3470 }
3471 return true;
3472 }
3473 bool found(APFloat &Value, QualType SubobjType) {
3474 if (!checkConst(SubobjType))
3475 return false;
3476
3477 if (Old) *Old = APValue(Value);
3478
3479 APFloat One(Value.getSemantics(), 1);
3480 if (AccessKind == AK_Increment)
3481 Value.add(One, APFloat::rmNearestTiesToEven);
3482 else
3483 Value.subtract(One, APFloat::rmNearestTiesToEven);
3484 return true;
3485 }
3486 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3487 if (!checkConst(SubobjType))
3488 return false;
3489
3490 QualType PointeeType;
3491 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3492 PointeeType = PT->getPointeeType();
3493 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003494 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003495 return false;
3496 }
3497
3498 LValue LVal;
3499 LVal.setFrom(Info.Ctx, Subobj);
3500 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3501 AccessKind == AK_Increment ? 1 : -1))
3502 return false;
3503 LVal.moveInto(Subobj);
3504 return true;
3505 }
3506 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3507 llvm_unreachable("shouldn't encounter string elements here");
3508 }
3509};
3510} // end anonymous namespace
3511
3512/// Perform an increment or decrement on LVal.
3513static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3514 QualType LValType, bool IsIncrement, APValue *Old) {
3515 if (LVal.Designator.Invalid)
3516 return false;
3517
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003518 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003519 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003520 return false;
3521 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003522
3523 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3524 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3525 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3526 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3527}
3528
Richard Smithe97cbd72011-11-11 04:05:33 +00003529/// Build an lvalue for the object argument of a member function call.
3530static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3531 LValue &This) {
3532 if (Object->getType()->isPointerType())
3533 return EvaluatePointer(Object, This, Info);
3534
3535 if (Object->isGLValue())
3536 return EvaluateLValue(Object, This, Info);
3537
Richard Smithd9f663b2013-04-22 15:31:51 +00003538 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003539 return EvaluateTemporary(Object, This, Info);
3540
Faisal Valie690b7a2016-07-02 22:34:24 +00003541 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003542 return false;
3543}
3544
3545/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3546/// lvalue referring to the result.
3547///
3548/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003549/// \param LV - An lvalue referring to the base of the member pointer.
3550/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003551/// \param IncludeMember - Specifies whether the member itself is included in
3552/// the resulting LValue subobject designator. This is not possible when
3553/// creating a bound member function.
3554/// \return The field or method declaration to which the member pointer refers,
3555/// or 0 if evaluation fails.
3556static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003557 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003558 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003559 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003560 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003561 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003562 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003563 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003564
3565 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3566 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003567 if (!MemPtr.getDecl()) {
3568 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003569 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003570 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003571 }
Richard Smith253c2a32012-01-27 01:14:48 +00003572
Richard Smith027bf112011-11-17 22:56:20 +00003573 if (MemPtr.isDerivedMember()) {
3574 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003575 // The end of the derived-to-base path for the base object must match the
3576 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003577 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003578 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003579 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003580 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003581 }
Richard Smith027bf112011-11-17 22:56:20 +00003582 unsigned PathLengthToMember =
3583 LV.Designator.Entries.size() - MemPtr.Path.size();
3584 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3585 const CXXRecordDecl *LVDecl = getAsBaseClass(
3586 LV.Designator.Entries[PathLengthToMember + I]);
3587 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003588 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003589 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003590 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003591 }
Richard Smith027bf112011-11-17 22:56:20 +00003592 }
3593
3594 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003595 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003596 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003597 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003598 } else if (!MemPtr.Path.empty()) {
3599 // Extend the LValue path with the member pointer's path.
3600 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3601 MemPtr.Path.size() + IncludeMember);
3602
3603 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003604 if (const PointerType *PT = LVType->getAs<PointerType>())
3605 LVType = PT->getPointeeType();
3606 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3607 assert(RD && "member pointer access on non-class-type expression");
3608 // The first class in the path is that of the lvalue.
3609 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3610 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003611 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003612 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003613 RD = Base;
3614 }
3615 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003616 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3617 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003618 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003619 }
3620
3621 // Add the member. Note that we cannot build bound member functions here.
3622 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003623 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003624 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003625 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003626 } else if (const IndirectFieldDecl *IFD =
3627 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003629 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003630 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003631 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003632 }
Richard Smith027bf112011-11-17 22:56:20 +00003633 }
3634
3635 return MemPtr.getDecl();
3636}
3637
Richard Smith84401042013-06-03 05:03:02 +00003638static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3639 const BinaryOperator *BO,
3640 LValue &LV,
3641 bool IncludeMember = true) {
3642 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3643
3644 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003645 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003646 MemberPtr MemPtr;
3647 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3648 }
Craig Topper36250ad2014-05-12 05:36:57 +00003649 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003650 }
3651
3652 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3653 BO->getRHS(), IncludeMember);
3654}
3655
Richard Smith027bf112011-11-17 22:56:20 +00003656/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3657/// the provided lvalue, which currently refers to the base object.
3658static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3659 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003660 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003661 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003662 return false;
3663
Richard Smitha8105bc2012-01-06 16:39:00 +00003664 QualType TargetQT = E->getType();
3665 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3666 TargetQT = PT->getPointeeType();
3667
3668 // Check this cast lands within the final derived-to-base subobject path.
3669 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003670 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003671 << D.MostDerivedType << TargetQT;
3672 return false;
3673 }
3674
Richard Smith027bf112011-11-17 22:56:20 +00003675 // Check the type of the final cast. We don't need to check the path,
3676 // since a cast can only be formed if the path is unique.
3677 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003678 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3679 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003680 if (NewEntriesSize == D.MostDerivedPathLength)
3681 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3682 else
Richard Smith027bf112011-11-17 22:56:20 +00003683 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003684 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003685 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003686 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003687 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 }
Richard Smith027bf112011-11-17 22:56:20 +00003689
3690 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003691 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003692}
3693
Mike Stump876387b2009-10-27 22:09:17 +00003694namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003695enum EvalStmtResult {
3696 /// Evaluation failed.
3697 ESR_Failed,
3698 /// Hit a 'return' statement.
3699 ESR_Returned,
3700 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003701 ESR_Succeeded,
3702 /// Hit a 'continue' statement.
3703 ESR_Continue,
3704 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003705 ESR_Break,
3706 /// Still scanning for 'case' or 'default' statement.
3707 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003708};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003709}
Richard Smith254a73d2011-10-28 22:34:42 +00003710
Richard Smith97fcf4b2016-08-14 23:15:52 +00003711static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3712 // We don't need to evaluate the initializer for a static local.
3713 if (!VD->hasLocalStorage())
3714 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003715
Richard Smith97fcf4b2016-08-14 23:15:52 +00003716 LValue Result;
3717 Result.set(VD, Info.CurrentCall->Index);
3718 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003719
Richard Smith97fcf4b2016-08-14 23:15:52 +00003720 const Expr *InitE = VD->getInit();
3721 if (!InitE) {
3722 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3723 << false << VD->getType();
3724 Val = APValue();
3725 return false;
3726 }
Richard Smith51f03172013-06-20 03:00:05 +00003727
Richard Smith97fcf4b2016-08-14 23:15:52 +00003728 if (InitE->isValueDependent())
3729 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003730
Richard Smith97fcf4b2016-08-14 23:15:52 +00003731 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3732 // Wipe out any partially-computed value, to allow tracking that this
3733 // evaluation failed.
3734 Val = APValue();
3735 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003736 }
3737
3738 return true;
3739}
3740
Richard Smith97fcf4b2016-08-14 23:15:52 +00003741static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3742 bool OK = true;
3743
3744 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3745 OK &= EvaluateVarDecl(Info, VD);
3746
3747 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3748 for (auto *BD : DD->bindings())
3749 if (auto *VD = BD->getHoldingVar())
3750 OK &= EvaluateDecl(Info, VD);
3751
3752 return OK;
3753}
3754
3755
Richard Smith4e18ca52013-05-06 05:56:11 +00003756/// Evaluate a condition (either a variable declaration or an expression).
3757static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3758 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003759 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003760 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3761 return false;
3762 return EvaluateAsBooleanCondition(Cond, Result, Info);
3763}
3764
Richard Smith89210072016-04-04 23:29:43 +00003765namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003766/// \brief A location where the result (returned value) of evaluating a
3767/// statement should be stored.
3768struct StmtResult {
3769 /// The APValue that should be filled in with the returned value.
3770 APValue &Value;
3771 /// The location containing the result, if any (used to support RVO).
3772 const LValue *Slot;
3773};
Richard Smith89210072016-04-04 23:29:43 +00003774}
Richard Smith52a980a2015-08-28 02:43:42 +00003775
3776static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003777 const Stmt *S,
3778 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003779
3780/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003781static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003782 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003783 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003784 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003785 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003786 case ESR_Break:
3787 return ESR_Succeeded;
3788 case ESR_Succeeded:
3789 case ESR_Continue:
3790 return ESR_Continue;
3791 case ESR_Failed:
3792 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003793 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003794 return ESR;
3795 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003796 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003797}
3798
Richard Smith496ddcf2013-05-12 17:32:42 +00003799/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003800static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003801 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003802 BlockScopeRAII Scope(Info);
3803
Richard Smith496ddcf2013-05-12 17:32:42 +00003804 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 {
3807 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003808 if (const Stmt *Init = SS->getInit()) {
3809 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3810 if (ESR != ESR_Succeeded)
3811 return ESR;
3812 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003813 if (SS->getConditionVariable() &&
3814 !EvaluateDecl(Info, SS->getConditionVariable()))
3815 return ESR_Failed;
3816 if (!EvaluateInteger(SS->getCond(), Value, Info))
3817 return ESR_Failed;
3818 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003819
3820 // Find the switch case corresponding to the value of the condition.
3821 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003822 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003823 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3824 SC = SC->getNextSwitchCase()) {
3825 if (isa<DefaultStmt>(SC)) {
3826 Found = SC;
3827 continue;
3828 }
3829
3830 const CaseStmt *CS = cast<CaseStmt>(SC);
3831 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3832 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3833 : LHS;
3834 if (LHS <= Value && Value <= RHS) {
3835 Found = SC;
3836 break;
3837 }
3838 }
3839
3840 if (!Found)
3841 return ESR_Succeeded;
3842
3843 // Search the switch body for the switch case and evaluate it from there.
3844 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3845 case ESR_Break:
3846 return ESR_Succeeded;
3847 case ESR_Succeeded:
3848 case ESR_Continue:
3849 case ESR_Failed:
3850 case ESR_Returned:
3851 return ESR;
3852 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003853 // This can only happen if the switch case is nested within a statement
3854 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003855 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003856 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003857 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003858 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003859}
3860
Richard Smith254a73d2011-10-28 22:34:42 +00003861// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003862static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003863 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003864 if (!Info.nextStep(S))
3865 return ESR_Failed;
3866
Richard Smith496ddcf2013-05-12 17:32:42 +00003867 // If we're hunting down a 'case' or 'default' label, recurse through
3868 // substatements until we hit the label.
3869 if (Case) {
3870 // FIXME: We don't start the lifetime of objects whose initialization we
3871 // jump over. However, such objects must be of class type with a trivial
3872 // default constructor that initialize all subobjects, so must be empty,
3873 // so this almost never matters.
3874 switch (S->getStmtClass()) {
3875 case Stmt::CompoundStmtClass:
3876 // FIXME: Precompute which substatement of a compound statement we
3877 // would jump to, and go straight there rather than performing a
3878 // linear scan each time.
3879 case Stmt::LabelStmtClass:
3880 case Stmt::AttributedStmtClass:
3881 case Stmt::DoStmtClass:
3882 break;
3883
3884 case Stmt::CaseStmtClass:
3885 case Stmt::DefaultStmtClass:
3886 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003887 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003888 break;
3889
3890 case Stmt::IfStmtClass: {
3891 // FIXME: Precompute which side of an 'if' we would jump to, and go
3892 // straight there rather than scanning both sides.
3893 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894
3895 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3896 // preceded by our switch label.
3897 BlockScopeRAII Scope(Info);
3898
Richard Smith496ddcf2013-05-12 17:32:42 +00003899 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3900 if (ESR != ESR_CaseNotFound || !IS->getElse())
3901 return ESR;
3902 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3903 }
3904
3905 case Stmt::WhileStmtClass: {
3906 EvalStmtResult ESR =
3907 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3908 if (ESR != ESR_Continue)
3909 return ESR;
3910 break;
3911 }
3912
3913 case Stmt::ForStmtClass: {
3914 const ForStmt *FS = cast<ForStmt>(S);
3915 EvalStmtResult ESR =
3916 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3917 if (ESR != ESR_Continue)
3918 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003919 if (FS->getInc()) {
3920 FullExpressionRAII IncScope(Info);
3921 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3922 return ESR_Failed;
3923 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003924 break;
3925 }
3926
3927 case Stmt::DeclStmtClass:
3928 // FIXME: If the variable has initialization that can't be jumped over,
3929 // bail out of any immediately-surrounding compound-statement too.
3930 default:
3931 return ESR_CaseNotFound;
3932 }
3933 }
3934
Richard Smith254a73d2011-10-28 22:34:42 +00003935 switch (S->getStmtClass()) {
3936 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003937 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003938 // Don't bother evaluating beyond an expression-statement which couldn't
3939 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003940 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003941 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003942 return ESR_Failed;
3943 return ESR_Succeeded;
3944 }
3945
Faisal Valie690b7a2016-07-02 22:34:24 +00003946 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003947 return ESR_Failed;
3948
3949 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003950 return ESR_Succeeded;
3951
Richard Smithd9f663b2013-04-22 15:31:51 +00003952 case Stmt::DeclStmtClass: {
3953 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003954 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003955 // Each declaration initialization is its own full-expression.
3956 // FIXME: This isn't quite right; if we're performing aggregate
3957 // initialization, each braced subexpression is its own full-expression.
3958 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003959 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003960 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003961 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003962 return ESR_Succeeded;
3963 }
3964
Richard Smith357362d2011-12-13 06:39:58 +00003965 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003966 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003968 if (RetExpr &&
3969 !(Result.Slot
3970 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3971 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003972 return ESR_Failed;
3973 return ESR_Returned;
3974 }
Richard Smith254a73d2011-10-28 22:34:42 +00003975
3976 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003977 BlockScopeRAII Scope(Info);
3978
Richard Smith254a73d2011-10-28 22:34:42 +00003979 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003980 for (const auto *BI : CS->body()) {
3981 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003982 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003983 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003984 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003985 return ESR;
3986 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003987 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003988 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003989
3990 case Stmt::IfStmtClass: {
3991 const IfStmt *IS = cast<IfStmt>(S);
3992
3993 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003994 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003995 if (const Stmt *Init = IS->getInit()) {
3996 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3997 if (ESR != ESR_Succeeded)
3998 return ESR;
3999 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004000 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004001 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004002 return ESR_Failed;
4003
4004 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4005 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4006 if (ESR != ESR_Succeeded)
4007 return ESR;
4008 }
4009 return ESR_Succeeded;
4010 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004011
4012 case Stmt::WhileStmtClass: {
4013 const WhileStmt *WS = cast<WhileStmt>(S);
4014 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004015 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004016 bool Continue;
4017 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4018 Continue))
4019 return ESR_Failed;
4020 if (!Continue)
4021 break;
4022
4023 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4024 if (ESR != ESR_Continue)
4025 return ESR;
4026 }
4027 return ESR_Succeeded;
4028 }
4029
4030 case Stmt::DoStmtClass: {
4031 const DoStmt *DS = cast<DoStmt>(S);
4032 bool Continue;
4033 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004034 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004035 if (ESR != ESR_Continue)
4036 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004037 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004038
Richard Smith08d6a2c2013-07-24 07:11:57 +00004039 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004040 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4041 return ESR_Failed;
4042 } while (Continue);
4043 return ESR_Succeeded;
4044 }
4045
4046 case Stmt::ForStmtClass: {
4047 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004048 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004049 if (FS->getInit()) {
4050 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4051 if (ESR != ESR_Succeeded)
4052 return ESR;
4053 }
4054 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004055 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004056 bool Continue = true;
4057 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4058 FS->getCond(), Continue))
4059 return ESR_Failed;
4060 if (!Continue)
4061 break;
4062
4063 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064 if (ESR != ESR_Continue)
4065 return ESR;
4066
Richard Smith08d6a2c2013-07-24 07:11:57 +00004067 if (FS->getInc()) {
4068 FullExpressionRAII IncScope(Info);
4069 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4070 return ESR_Failed;
4071 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004072 }
4073 return ESR_Succeeded;
4074 }
4075
Richard Smith896e0d72013-05-06 06:51:17 +00004076 case Stmt::CXXForRangeStmtClass: {
4077 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004078 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004079
4080 // Initialize the __range variable.
4081 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4082 if (ESR != ESR_Succeeded)
4083 return ESR;
4084
4085 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004086 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4087 if (ESR != ESR_Succeeded)
4088 return ESR;
4089 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004090 if (ESR != ESR_Succeeded)
4091 return ESR;
4092
4093 while (true) {
4094 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004095 {
4096 bool Continue = true;
4097 FullExpressionRAII CondExpr(Info);
4098 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4099 return ESR_Failed;
4100 if (!Continue)
4101 break;
4102 }
Richard Smith896e0d72013-05-06 06:51:17 +00004103
4104 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004105 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004106 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4107 if (ESR != ESR_Succeeded)
4108 return ESR;
4109
4110 // Loop body.
4111 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4112 if (ESR != ESR_Continue)
4113 return ESR;
4114
4115 // Increment: ++__begin
4116 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4117 return ESR_Failed;
4118 }
4119
4120 return ESR_Succeeded;
4121 }
4122
Richard Smith496ddcf2013-05-12 17:32:42 +00004123 case Stmt::SwitchStmtClass:
4124 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4125
Richard Smith4e18ca52013-05-06 05:56:11 +00004126 case Stmt::ContinueStmtClass:
4127 return ESR_Continue;
4128
4129 case Stmt::BreakStmtClass:
4130 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004131
4132 case Stmt::LabelStmtClass:
4133 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4134
4135 case Stmt::AttributedStmtClass:
4136 // As a general principle, C++11 attributes can be ignored without
4137 // any semantic impact.
4138 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4139 Case);
4140
4141 case Stmt::CaseStmtClass:
4142 case Stmt::DefaultStmtClass:
4143 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004144 }
4145}
4146
Richard Smithcc36f692011-12-22 02:22:31 +00004147/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4148/// default constructor. If so, we'll fold it whether or not it's marked as
4149/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4150/// so we need special handling.
4151static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004152 const CXXConstructorDecl *CD,
4153 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004154 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4155 return false;
4156
Richard Smith66e05fe2012-01-18 05:21:49 +00004157 // Value-initialization does not call a trivial default constructor, so such a
4158 // call is a core constant expression whether or not the constructor is
4159 // constexpr.
4160 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004161 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004162 // FIXME: If DiagDecl is an implicitly-declared special member function,
4163 // we should be much more explicit about why it's not constexpr.
4164 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4165 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4166 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004167 } else {
4168 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4169 }
4170 }
4171 return true;
4172}
4173
Richard Smith357362d2011-12-13 06:39:58 +00004174/// CheckConstexprFunction - Check that a function can be called in a constant
4175/// expression.
4176static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4177 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004178 const FunctionDecl *Definition,
4179 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004180 // Potential constant expressions can contain calls to declared, but not yet
4181 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004182 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004183 Declaration->isConstexpr())
4184 return false;
4185
Richard Smith0838f3a2013-05-14 05:18:44 +00004186 // Bail out with no diagnostic if the function declaration itself is invalid.
4187 // We will have produced a relevant diagnostic while parsing it.
4188 if (Declaration->isInvalidDecl())
4189 return false;
4190
Richard Smith357362d2011-12-13 06:39:58 +00004191 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004192 if (Definition && Definition->isConstexpr() &&
4193 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004194 return true;
4195
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004196 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004197 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004198
Richard Smith5179eb72016-06-28 19:03:57 +00004199 // If this function is not constexpr because it is an inherited
4200 // non-constexpr constructor, diagnose that directly.
4201 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4202 if (CD && CD->isInheritingConstructor()) {
4203 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004204 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004205 DiagDecl = CD = Inherited;
4206 }
4207
4208 // FIXME: If DiagDecl is an implicitly-declared special member function
4209 // or an inheriting constructor, we should be much more explicit about why
4210 // it's not constexpr.
4211 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004212 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004213 << CD->getInheritedConstructor().getConstructor()->getParent();
4214 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004215 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004216 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004217 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4218 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004219 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004220 }
4221 return false;
4222}
4223
Richard Smithbe6dd812014-11-19 21:27:17 +00004224/// Determine if a class has any fields that might need to be copied by a
4225/// trivial copy or move operation.
4226static bool hasFields(const CXXRecordDecl *RD) {
4227 if (!RD || RD->isEmpty())
4228 return false;
4229 for (auto *FD : RD->fields()) {
4230 if (FD->isUnnamedBitfield())
4231 continue;
4232 return true;
4233 }
4234 for (auto &Base : RD->bases())
4235 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4236 return true;
4237 return false;
4238}
4239
Richard Smithd62306a2011-11-10 06:34:14 +00004240namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004241typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004242}
4243
4244/// EvaluateArgs - Evaluate the arguments to a function call.
4245static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4246 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004247 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004248 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004249 I != E; ++I) {
4250 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4251 // If we're checking for a potential constant expression, evaluate all
4252 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004253 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004254 return false;
4255 Success = false;
4256 }
4257 }
4258 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004259}
4260
Richard Smith254a73d2011-10-28 22:34:42 +00004261/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004262static bool HandleFunctionCall(SourceLocation CallLoc,
4263 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004264 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004265 EvalInfo &Info, APValue &Result,
4266 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004267 ArgVector ArgValues(Args.size());
4268 if (!EvaluateArgs(Args, ArgValues, Info))
4269 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004270
Richard Smith253c2a32012-01-27 01:14:48 +00004271 if (!Info.CheckCallLimit(CallLoc))
4272 return false;
4273
4274 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004275
4276 // For a trivial copy or move assignment, perform an APValue copy. This is
4277 // essential for unions, where the operations performed by the assignment
4278 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004279 //
4280 // Skip this for non-union classes with no fields; in that case, the defaulted
4281 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004282 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004283 if (MD && MD->isDefaulted() &&
4284 (MD->getParent()->isUnion() ||
4285 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004286 assert(This &&
4287 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4288 LValue RHS;
4289 RHS.setFrom(Info.Ctx, ArgValues[0]);
4290 APValue RHSValue;
4291 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4292 RHS, RHSValue))
4293 return false;
4294 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4295 RHSValue))
4296 return false;
4297 This->moveInto(Result);
4298 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004299 } else if (MD && isLambdaCallOperator(MD)) {
4300 // We're in a lambda; determine the lambda capture field maps.
4301 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4302 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004303 }
4304
Richard Smith52a980a2015-08-28 02:43:42 +00004305 StmtResult Ret = {Result, ResultSlot};
4306 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004307 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004308 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004309 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004310 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004311 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004312 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004313}
4314
Richard Smithd62306a2011-11-10 06:34:14 +00004315/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004316static bool HandleConstructorCall(const Expr *E, const LValue &This,
4317 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004318 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004319 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004320 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004321 if (!Info.CheckCallLimit(CallLoc))
4322 return false;
4323
Richard Smith3607ffe2012-02-13 03:54:03 +00004324 const CXXRecordDecl *RD = Definition->getParent();
4325 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004326 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004327 return false;
4328 }
4329
Erik Pilkington42925492017-10-04 00:18:55 +00004330 EvalInfo::EvaluatingConstructorRAII EvalObj(
4331 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004332 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004333
Richard Smith52a980a2015-08-28 02:43:42 +00004334 // FIXME: Creating an APValue just to hold a nonexistent return value is
4335 // wasteful.
4336 APValue RetVal;
4337 StmtResult Ret = {RetVal, nullptr};
4338
Richard Smith5179eb72016-06-28 19:03:57 +00004339 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004340 if (Definition->isDelegatingConstructor()) {
4341 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004342 {
4343 FullExpressionRAII InitScope(Info);
4344 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4345 return false;
4346 }
Richard Smith52a980a2015-08-28 02:43:42 +00004347 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004348 }
4349
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004350 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004351 // essential for unions (or classes with anonymous union members), where the
4352 // operations performed by the constructor cannot be represented by
4353 // ctor-initializers.
4354 //
4355 // Skip this for empty non-union classes; we should not perform an
4356 // lvalue-to-rvalue conversion on them because their copy constructor does not
4357 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004358 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004359 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004360 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004361 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004362 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004363 return handleLValueToRValueConversion(
4364 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4365 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004366 }
4367
4368 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004369 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004370 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004371 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004372
John McCalld7bca762012-05-01 00:38:49 +00004373 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004374 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4375
Richard Smith08d6a2c2013-07-24 07:11:57 +00004376 // A scope for temporaries lifetime-extended by reference members.
4377 BlockScopeRAII LifetimeExtendedScope(Info);
4378
Richard Smith253c2a32012-01-27 01:14:48 +00004379 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004380 unsigned BasesSeen = 0;
4381#ifndef NDEBUG
4382 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4383#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004384 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004385 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004386 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004387 APValue *Value = &Result;
4388
4389 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004390 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004391 if (I->isBaseInitializer()) {
4392 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004393#ifndef NDEBUG
4394 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004395 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004396 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4397 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4398 "base class initializers not in expected order");
4399 ++BaseIt;
4400#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004401 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004402 BaseType->getAsCXXRecordDecl(), &Layout))
4403 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004404 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004405 } else if ((FD = I->getMember())) {
4406 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004407 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004408 if (RD->isUnion()) {
4409 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004410 Value = &Result.getUnionValue();
4411 } else {
4412 Value = &Result.getStructField(FD->getFieldIndex());
4413 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004414 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004415 // Walk the indirect field decl's chain to find the object to initialize,
4416 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004417 auto IndirectFieldChain = IFD->chain();
4418 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004419 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004420 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4421 // Switch the union field if it differs. This happens if we had
4422 // preceding zero-initialization, and we're now initializing a union
4423 // subobject other than the first.
4424 // FIXME: In this case, the values of the other subobjects are
4425 // specified, since zero-initialization sets all padding bits to zero.
4426 if (Value->isUninit() ||
4427 (Value->isUnion() && Value->getUnionField() != FD)) {
4428 if (CD->isUnion())
4429 *Value = APValue(FD);
4430 else
4431 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004432 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004433 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004434 // Store Subobject as its parent before updating it for the last element
4435 // in the chain.
4436 if (C == IndirectFieldChain.back())
4437 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004438 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004439 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004440 if (CD->isUnion())
4441 Value = &Value->getUnionValue();
4442 else
4443 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004444 }
Richard Smithd62306a2011-11-10 06:34:14 +00004445 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004446 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004447 }
Richard Smith253c2a32012-01-27 01:14:48 +00004448
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004449 // Need to override This for implicit field initializers as in this case
4450 // This refers to innermost anonymous struct/union containing initializer,
4451 // not to currently constructed class.
4452 const Expr *Init = I->getInit();
4453 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4454 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004455 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004456 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4457 (FD && FD->isBitField() &&
4458 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004459 // If we're checking for a potential constant expression, evaluate all
4460 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004461 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004462 return false;
4463 Success = false;
4464 }
Richard Smithd62306a2011-11-10 06:34:14 +00004465 }
4466
Richard Smithd9f663b2013-04-22 15:31:51 +00004467 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004468 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004469}
4470
Richard Smith5179eb72016-06-28 19:03:57 +00004471static bool HandleConstructorCall(const Expr *E, const LValue &This,
4472 ArrayRef<const Expr*> Args,
4473 const CXXConstructorDecl *Definition,
4474 EvalInfo &Info, APValue &Result) {
4475 ArgVector ArgValues(Args.size());
4476 if (!EvaluateArgs(Args, ArgValues, Info))
4477 return false;
4478
4479 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4480 Info, Result);
4481}
4482
Eli Friedman9a156e52008-11-12 09:44:48 +00004483//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004484// Generic Evaluation
4485//===----------------------------------------------------------------------===//
4486namespace {
4487
Aaron Ballman68af21c2014-01-03 19:26:43 +00004488template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004489class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004491private:
Richard Smith52a980a2015-08-28 02:43:42 +00004492 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004493 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004494 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004495 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004497 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004498 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004499
Richard Smith17100ba2012-02-16 02:46:34 +00004500 // Check whether a conditional operator with a non-constant condition is a
4501 // potential constant expression. If neither arm is a potential constant
4502 // expression, then the conditional operator is not either.
4503 template<typename ConditionalOperator>
4504 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004505 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004506
4507 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004508 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004509 {
Richard Smith17100ba2012-02-16 02:46:34 +00004510 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004511 StmtVisitorTy::Visit(E->getFalseExpr());
4512 if (Diag.empty())
4513 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004514 }
Richard Smith17100ba2012-02-16 02:46:34 +00004515
George Burgess IV8c892b52016-05-25 22:31:54 +00004516 {
4517 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004518 Diag.clear();
4519 StmtVisitorTy::Visit(E->getTrueExpr());
4520 if (Diag.empty())
4521 return;
4522 }
4523
4524 Error(E, diag::note_constexpr_conditional_never_const);
4525 }
4526
4527
4528 template<typename ConditionalOperator>
4529 bool HandleConditionalOperator(const ConditionalOperator *E) {
4530 bool BoolResult;
4531 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004532 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004533 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004534 return false;
4535 }
4536 if (Info.noteFailure()) {
4537 StmtVisitorTy::Visit(E->getTrueExpr());
4538 StmtVisitorTy::Visit(E->getFalseExpr());
4539 }
Richard Smith17100ba2012-02-16 02:46:34 +00004540 return false;
4541 }
4542
4543 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4544 return StmtVisitorTy::Visit(EvalExpr);
4545 }
4546
Peter Collingbournee9200682011-05-13 03:29:01 +00004547protected:
4548 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004549 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004550 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4551
Richard Smith92b1ce02011-12-12 09:28:41 +00004552 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004553 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004554 }
4555
Aaron Ballman68af21c2014-01-03 19:26:43 +00004556 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004557
4558public:
4559 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4560
4561 EvalInfo &getEvalInfo() { return Info; }
4562
Richard Smithf57d8cb2011-12-09 22:58:01 +00004563 /// Report an evaluation error. This should only be called when an error is
4564 /// first discovered. When propagating an error, just return false.
4565 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004566 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004567 return false;
4568 }
4569 bool Error(const Expr *E) {
4570 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4571 }
4572
Aaron Ballman68af21c2014-01-03 19:26:43 +00004573 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004574 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004575 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004576 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004577 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004578 }
4579
Aaron Ballman68af21c2014-01-03 19:26:43 +00004580 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004581 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004582 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004583 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004584 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004585 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004587 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004589 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004591 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004592 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004593 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004595 // The initializer may not have been parsed yet, or might be erroneous.
4596 if (!E->getExpr())
4597 return Error(E);
4598 return StmtVisitorTy::Visit(E->getExpr());
4599 }
Richard Smith5894a912011-12-19 22:12:41 +00004600 // We cannot create any objects for which cleanups are required, so there is
4601 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004602 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004603 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004604
Aaron Ballman68af21c2014-01-03 19:26:43 +00004605 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004606 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4607 return static_cast<Derived*>(this)->VisitCastExpr(E);
4608 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004610 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4611 return static_cast<Derived*>(this)->VisitCastExpr(E);
4612 }
4613
Aaron Ballman68af21c2014-01-03 19:26:43 +00004614 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004615 switch (E->getOpcode()) {
4616 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004617 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004618
4619 case BO_Comma:
4620 VisitIgnoredValue(E->getLHS());
4621 return StmtVisitorTy::Visit(E->getRHS());
4622
4623 case BO_PtrMemD:
4624 case BO_PtrMemI: {
4625 LValue Obj;
4626 if (!HandleMemberPointerAccess(Info, E, Obj))
4627 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004628 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004629 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004630 return false;
4631 return DerivedSuccess(Result, E);
4632 }
4633 }
4634 }
4635
Aaron Ballman68af21c2014-01-03 19:26:43 +00004636 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004637 // Evaluate and cache the common expression. We treat it as a temporary,
4638 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004639 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004640 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004641 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004642
Richard Smith17100ba2012-02-16 02:46:34 +00004643 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004644 }
4645
Aaron Ballman68af21c2014-01-03 19:26:43 +00004646 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004647 bool IsBcpCall = false;
4648 // If the condition (ignoring parens) is a __builtin_constant_p call,
4649 // the result is a constant expression if it can be folded without
4650 // side-effects. This is an important GNU extension. See GCC PR38377
4651 // for discussion.
4652 if (const CallExpr *CallCE =
4653 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004654 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004655 IsBcpCall = true;
4656
4657 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4658 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004659 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004660 return false;
4661
Richard Smith6d4c6582013-11-05 22:18:15 +00004662 FoldConstant Fold(Info, IsBcpCall);
4663 if (!HandleConditionalOperator(E)) {
4664 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004665 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004666 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004667
4668 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004669 }
4670
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004672 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4673 return DerivedSuccess(*Value, E);
4674
4675 const Expr *Source = E->getSourceExpr();
4676 if (!Source)
4677 return Error(E);
4678 if (Source == E) { // sanity checking.
4679 assert(0 && "OpaqueValueExpr recursively refers to itself");
4680 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004681 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004682 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004683 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004684
Aaron Ballman68af21c2014-01-03 19:26:43 +00004685 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004686 APValue Result;
4687 if (!handleCallExpr(E, Result, nullptr))
4688 return false;
4689 return DerivedSuccess(Result, E);
4690 }
4691
4692 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004693 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004694 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004695 QualType CalleeType = Callee->getType();
4696
Craig Topper36250ad2014-05-12 05:36:57 +00004697 const FunctionDecl *FD = nullptr;
4698 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004699 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004700 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004701
Richard Smithe97cbd72011-11-11 04:05:33 +00004702 // Extract function decl and 'this' pointer from the callee.
4703 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004704 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004705 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4706 // Explicit bound member calls, such as x.f() or p->g();
4707 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004708 return false;
4709 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004710 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004711 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004712 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4713 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004714 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4715 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004716 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004717 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004718 return Error(Callee);
4719
4720 FD = dyn_cast<FunctionDecl>(Member);
4721 if (!FD)
4722 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004723 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004724 LValue Call;
4725 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004727
Richard Smitha8105bc2012-01-06 16:39:00 +00004728 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004729 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004730 FD = dyn_cast_or_null<FunctionDecl>(
4731 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004732 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004733 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004734 // Don't call function pointers which have been cast to some other type.
4735 // Per DR (no number yet), the caller and callee can differ in noexcept.
4736 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4737 CalleeType->getPointeeType(), FD->getType())) {
4738 return Error(E);
4739 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004740
4741 // Overloaded operator calls to member functions are represented as normal
4742 // calls with '*this' as the first argument.
4743 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4744 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 // FIXME: When selecting an implicit conversion for an overloaded
4746 // operator delete, we sometimes try to evaluate calls to conversion
4747 // operators without a 'this' parameter!
4748 if (Args.empty())
4749 return Error(E);
4750
Nick Lewycky13073a62017-06-12 21:15:44 +00004751 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004752 return false;
4753 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004754 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004755 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004756 // Map the static invoker for the lambda back to the call operator.
4757 // Conveniently, we don't have to slice out the 'this' argument (as is
4758 // being done for the non-static case), since a static member function
4759 // doesn't have an implicit argument passed in.
4760 const CXXRecordDecl *ClosureClass = MD->getParent();
4761 assert(
4762 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4763 "Number of captures must be zero for conversion to function-ptr");
4764
4765 const CXXMethodDecl *LambdaCallOp =
4766 ClosureClass->getLambdaCallOperator();
4767
4768 // Set 'FD', the function that will be called below, to the call
4769 // operator. If the closure object represents a generic lambda, find
4770 // the corresponding specialization of the call operator.
4771
4772 if (ClosureClass->isGenericLambda()) {
4773 assert(MD->isFunctionTemplateSpecialization() &&
4774 "A generic lambda's static-invoker function must be a "
4775 "template specialization");
4776 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4777 FunctionTemplateDecl *CallOpTemplate =
4778 LambdaCallOp->getDescribedFunctionTemplate();
4779 void *InsertPos = nullptr;
4780 FunctionDecl *CorrespondingCallOpSpecialization =
4781 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4782 assert(CorrespondingCallOpSpecialization &&
4783 "We must always have a function call operator specialization "
4784 "that corresponds to our static invoker specialization");
4785 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4786 } else
4787 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004788 }
4789
Daniel Jasperffdee092017-05-02 19:21:42 +00004790
Richard Smithe97cbd72011-11-11 04:05:33 +00004791 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004792 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004793
Richard Smith47b34932012-02-01 02:39:43 +00004794 if (This && !This->checkSubobject(Info, E, CSK_This))
4795 return false;
4796
Richard Smith3607ffe2012-02-13 03:54:03 +00004797 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4798 // calls to such functions in constant expressions.
4799 if (This && !HasQualifier &&
4800 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4801 return Error(E, diag::note_constexpr_virtual_call);
4802
Craig Topper36250ad2014-05-12 05:36:57 +00004803 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004804 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004805
Nick Lewycky13073a62017-06-12 21:15:44 +00004806 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4807 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004808 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004809 return false;
4810
Richard Smith52a980a2015-08-28 02:43:42 +00004811 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004812 }
4813
Aaron Ballman68af21c2014-01-03 19:26:43 +00004814 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004815 return StmtVisitorTy::Visit(E->getInitializer());
4816 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004817 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004818 if (E->getNumInits() == 0)
4819 return DerivedZeroInitialization(E);
4820 if (E->getNumInits() == 1)
4821 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004822 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004823 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004824 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004825 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004826 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004827 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004828 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004829 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004830 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004831 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004832 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004833
Richard Smithd62306a2011-11-10 06:34:14 +00004834 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004836 assert(!E->isArrow() && "missing call to bound member function?");
4837
Richard Smith2e312c82012-03-03 22:46:17 +00004838 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004839 if (!Evaluate(Val, Info, E->getBase()))
4840 return false;
4841
4842 QualType BaseTy = E->getBase()->getType();
4843
4844 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004845 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004846 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004847 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004848 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4849
Richard Smith9defb7d2018-02-21 03:38:30 +00004850 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004851 SubobjectDesignator Designator(BaseTy);
4852 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004853
Richard Smith3229b742013-05-05 21:17:10 +00004854 APValue Result;
4855 return extractSubobject(Info, E, Obj, Designator, Result) &&
4856 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004857 }
4858
Aaron Ballman68af21c2014-01-03 19:26:43 +00004859 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004860 switch (E->getCastKind()) {
4861 default:
4862 break;
4863
Richard Smitha23ab512013-05-23 00:30:41 +00004864 case CK_AtomicToNonAtomic: {
4865 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004866 // This does not need to be done in place even for class/array types:
4867 // atomic-to-non-atomic conversion implies copying the object
4868 // representation.
4869 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004870 return false;
4871 return DerivedSuccess(AtomicVal, E);
4872 }
4873
Richard Smith11562c52011-10-28 17:51:58 +00004874 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004875 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004876 return StmtVisitorTy::Visit(E->getSubExpr());
4877
4878 case CK_LValueToRValue: {
4879 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004880 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4881 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004882 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004883 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004884 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004885 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004886 return false;
4887 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004888 }
4889 }
4890
Richard Smithf57d8cb2011-12-09 22:58:01 +00004891 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004892 }
4893
Aaron Ballman68af21c2014-01-03 19:26:43 +00004894 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004895 return VisitUnaryPostIncDec(UO);
4896 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004897 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004898 return VisitUnaryPostIncDec(UO);
4899 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004900 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004901 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004902 return Error(UO);
4903
4904 LValue LVal;
4905 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4906 return false;
4907 APValue RVal;
4908 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4909 UO->isIncrementOp(), &RVal))
4910 return false;
4911 return DerivedSuccess(RVal, UO);
4912 }
4913
Aaron Ballman68af21c2014-01-03 19:26:43 +00004914 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004915 // We will have checked the full-expressions inside the statement expression
4916 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004917 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004918 return Error(E);
4919
Richard Smith08d6a2c2013-07-24 07:11:57 +00004920 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004921 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004922 if (CS->body_empty())
4923 return true;
4924
Richard Smith51f03172013-06-20 03:00:05 +00004925 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4926 BE = CS->body_end();
4927 /**/; ++BI) {
4928 if (BI + 1 == BE) {
4929 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4930 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004931 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004932 diag::note_constexpr_stmt_expr_unsupported);
4933 return false;
4934 }
4935 return this->Visit(FinalExpr);
4936 }
4937
4938 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004939 StmtResult Result = { ReturnValue, nullptr };
4940 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004941 if (ESR != ESR_Succeeded) {
4942 // FIXME: If the statement-expression terminated due to 'return',
4943 // 'break', or 'continue', it would be nice to propagate that to
4944 // the outer statement evaluation rather than bailing out.
4945 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004946 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004947 diag::note_constexpr_stmt_expr_unsupported);
4948 return false;
4949 }
4950 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004951
4952 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004953 }
4954
Richard Smith4a678122011-10-24 18:44:57 +00004955 /// Visit a value which is evaluated, but whose value is ignored.
4956 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004957 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004958 }
David Majnemere9807b22016-02-26 04:23:19 +00004959
4960 /// Potentially visit a MemberExpr's base expression.
4961 void VisitIgnoredBaseExpression(const Expr *E) {
4962 // While MSVC doesn't evaluate the base expression, it does diagnose the
4963 // presence of side-effecting behavior.
4964 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4965 return;
4966 VisitIgnoredValue(E);
4967 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004968};
4969
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004970}
Peter Collingbournee9200682011-05-13 03:29:01 +00004971
4972//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004973// Common base class for lvalue and temporary evaluation.
4974//===----------------------------------------------------------------------===//
4975namespace {
4976template<class Derived>
4977class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004978 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004979protected:
4980 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004981 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004982 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004983 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004984
4985 bool Success(APValue::LValueBase B) {
4986 Result.set(B);
4987 return true;
4988 }
4989
George Burgess IVf9013bf2017-02-10 22:52:29 +00004990 bool evaluatePointer(const Expr *E, LValue &Result) {
4991 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4992 }
4993
Richard Smith027bf112011-11-17 22:56:20 +00004994public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004995 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4996 : ExprEvaluatorBaseTy(Info), Result(Result),
4997 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004998
Richard Smith2e312c82012-03-03 22:46:17 +00004999 bool Success(const APValue &V, const Expr *E) {
5000 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005001 return true;
5002 }
Richard Smith027bf112011-11-17 22:56:20 +00005003
Richard Smith027bf112011-11-17 22:56:20 +00005004 bool VisitMemberExpr(const MemberExpr *E) {
5005 // Handle non-static data members.
5006 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005007 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005008 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005009 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005010 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005011 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005012 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005013 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005014 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005015 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005016 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005017 BaseTy = E->getBase()->getType();
5018 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005019 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005020 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005021 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005022 Result.setInvalid(E);
5023 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005024 }
Richard Smith027bf112011-11-17 22:56:20 +00005025
Richard Smith1b78b3d2012-01-25 22:15:11 +00005026 const ValueDecl *MD = E->getMemberDecl();
5027 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5028 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5029 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5030 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005031 if (!HandleLValueMember(this->Info, E, Result, FD))
5032 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005033 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005034 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5035 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005036 } else
5037 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005038
Richard Smith1b78b3d2012-01-25 22:15:11 +00005039 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005040 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005041 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005042 RefValue))
5043 return false;
5044 return Success(RefValue, E);
5045 }
5046 return true;
5047 }
5048
5049 bool VisitBinaryOperator(const BinaryOperator *E) {
5050 switch (E->getOpcode()) {
5051 default:
5052 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5053
5054 case BO_PtrMemD:
5055 case BO_PtrMemI:
5056 return HandleMemberPointerAccess(this->Info, E, Result);
5057 }
5058 }
5059
5060 bool VisitCastExpr(const CastExpr *E) {
5061 switch (E->getCastKind()) {
5062 default:
5063 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5064
5065 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005066 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005067 if (!this->Visit(E->getSubExpr()))
5068 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005069
5070 // Now figure out the necessary offset to add to the base LV to get from
5071 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005072 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5073 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005074 }
5075 }
5076};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005077}
Richard Smith027bf112011-11-17 22:56:20 +00005078
5079//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005080// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005081//
5082// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5083// function designators (in C), decl references to void objects (in C), and
5084// temporaries (if building with -Wno-address-of-temporary).
5085//
5086// LValue evaluation produces values comprising a base expression of one of the
5087// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005088// - Declarations
5089// * VarDecl
5090// * FunctionDecl
5091// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005092// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005093// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005094// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005095// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005096// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005097// * ObjCEncodeExpr
5098// * AddrLabelExpr
5099// * BlockExpr
5100// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005101// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005102// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005103// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005104// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5105// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005106// * A MaterializeTemporaryExpr that has static storage duration, with no
5107// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005108// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005109//===----------------------------------------------------------------------===//
5110namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005111class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005112 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005113public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005114 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5115 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005116
Richard Smith11562c52011-10-28 17:51:58 +00005117 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005118 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005119
Peter Collingbournee9200682011-05-13 03:29:01 +00005120 bool VisitDeclRefExpr(const DeclRefExpr *E);
5121 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005122 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005123 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5124 bool VisitMemberExpr(const MemberExpr *E);
5125 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5126 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005127 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005128 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005129 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5130 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005131 bool VisitUnaryReal(const UnaryOperator *E);
5132 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005133 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5134 return VisitUnaryPreIncDec(UO);
5135 }
5136 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5137 return VisitUnaryPreIncDec(UO);
5138 }
Richard Smith3229b742013-05-05 21:17:10 +00005139 bool VisitBinAssign(const BinaryOperator *BO);
5140 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005141
Peter Collingbournee9200682011-05-13 03:29:01 +00005142 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005143 switch (E->getCastKind()) {
5144 default:
Richard Smith027bf112011-11-17 22:56:20 +00005145 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005146
Eli Friedmance3e02a2011-10-11 00:13:24 +00005147 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005148 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005149 if (!Visit(E->getSubExpr()))
5150 return false;
5151 Result.Designator.setInvalid();
5152 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005153
Richard Smith027bf112011-11-17 22:56:20 +00005154 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005155 if (!Visit(E->getSubExpr()))
5156 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005157 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005158 }
5159 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005160};
5161} // end anonymous namespace
5162
Richard Smith11562c52011-10-28 17:51:58 +00005163/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005164/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005165/// * function designators in C, and
5166/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005167/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005168static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5169 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005170 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005171 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005172 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005173}
5174
Peter Collingbournee9200682011-05-13 03:29:01 +00005175bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005176 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005177 return Success(FD);
5178 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005179 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005180 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005181 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005182 return Error(E);
5183}
Richard Smith733237d2011-10-24 23:14:33 +00005184
Faisal Vali0528a312016-11-13 06:09:16 +00005185
Richard Smith11562c52011-10-28 17:51:58 +00005186bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005187
5188 // If we are within a lambda's call operator, check whether the 'VD' referred
5189 // to within 'E' actually represents a lambda-capture that maps to a
5190 // data-member/field within the closure object, and if so, evaluate to the
5191 // field or what the field refers to.
5192 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5193 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5194 if (Info.checkingPotentialConstantExpression())
5195 return false;
5196 // Start with 'Result' referring to the complete closure object...
5197 Result = *Info.CurrentCall->This;
5198 // ... then update it to refer to the field of the closure object
5199 // that represents the capture.
5200 if (!HandleLValueMember(Info, E, Result, FD))
5201 return false;
5202 // And if the field is of reference type, update 'Result' to refer to what
5203 // the field refers to.
5204 if (FD->getType()->isReferenceType()) {
5205 APValue RVal;
5206 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5207 RVal))
5208 return false;
5209 Result.setFrom(Info.Ctx, RVal);
5210 }
5211 return true;
5212 }
5213 }
Craig Topper36250ad2014-05-12 05:36:57 +00005214 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005215 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5216 // Only if a local variable was declared in the function currently being
5217 // evaluated, do we expect to be able to find its value in the current
5218 // frame. (Otherwise it was likely declared in an enclosing context and
5219 // could either have a valid evaluatable value (for e.g. a constexpr
5220 // variable) or be ill-formed (and trigger an appropriate evaluation
5221 // diagnostic)).
5222 if (Info.CurrentCall->Callee &&
5223 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5224 Frame = Info.CurrentCall;
5225 }
5226 }
Richard Smith3229b742013-05-05 21:17:10 +00005227
Richard Smithfec09922011-11-01 16:57:24 +00005228 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005229 if (Frame) {
5230 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005231 return true;
5232 }
Richard Smithce40ad62011-11-12 22:28:03 +00005233 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005234 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005235
Richard Smith3229b742013-05-05 21:17:10 +00005236 APValue *V;
5237 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005238 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005239 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005240 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005241 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005242 return false;
5243 }
Richard Smith3229b742013-05-05 21:17:10 +00005244 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005245}
5246
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005247bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5248 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005249 // Walk through the expression to find the materialized temporary itself.
5250 SmallVector<const Expr *, 2> CommaLHSs;
5251 SmallVector<SubobjectAdjustment, 2> Adjustments;
5252 const Expr *Inner = E->GetTemporaryExpr()->
5253 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005254
Richard Smith84401042013-06-03 05:03:02 +00005255 // If we passed any comma operators, evaluate their LHSs.
5256 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5257 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5258 return false;
5259
Richard Smithe6c01442013-06-05 00:46:14 +00005260 // A materialized temporary with static storage duration can appear within the
5261 // result of a constant expression evaluation, so we need to preserve its
5262 // value for use outside this evaluation.
5263 APValue *Value;
5264 if (E->getStorageDuration() == SD_Static) {
5265 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005266 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005267 Result.set(E);
5268 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005269 Value = &Info.CurrentCall->
5270 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005271 Result.set(E, Info.CurrentCall->Index);
5272 }
5273
Richard Smithea4ad5d2013-06-06 08:19:16 +00005274 QualType Type = Inner->getType();
5275
Richard Smith84401042013-06-03 05:03:02 +00005276 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005277 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5278 (E->getStorageDuration() == SD_Static &&
5279 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5280 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005281 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005282 }
Richard Smith84401042013-06-03 05:03:02 +00005283
5284 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005285 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5286 --I;
5287 switch (Adjustments[I].Kind) {
5288 case SubobjectAdjustment::DerivedToBaseAdjustment:
5289 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5290 Type, Result))
5291 return false;
5292 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5293 break;
5294
5295 case SubobjectAdjustment::FieldAdjustment:
5296 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5297 return false;
5298 Type = Adjustments[I].Field->getType();
5299 break;
5300
5301 case SubobjectAdjustment::MemberPointerAdjustment:
5302 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5303 Adjustments[I].Ptr.RHS))
5304 return false;
5305 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5306 break;
5307 }
5308 }
5309
5310 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005311}
5312
Peter Collingbournee9200682011-05-13 03:29:01 +00005313bool
5314LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005315 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5316 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005317 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5318 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005319 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005320}
5321
Richard Smith6e525142011-12-27 12:18:28 +00005322bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005323 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005324 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005325
Faisal Valie690b7a2016-07-02 22:34:24 +00005326 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005327 << E->getExprOperand()->getType()
5328 << E->getExprOperand()->getSourceRange();
5329 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005330}
5331
Francois Pichet0066db92012-04-16 04:08:35 +00005332bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5333 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005334}
Francois Pichet0066db92012-04-16 04:08:35 +00005335
Peter Collingbournee9200682011-05-13 03:29:01 +00005336bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005337 // Handle static data members.
5338 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005339 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005340 return VisitVarDecl(E, VD);
5341 }
5342
Richard Smith254a73d2011-10-28 22:34:42 +00005343 // Handle static member functions.
5344 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5345 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005346 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005347 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005348 }
5349 }
5350
Richard Smithd62306a2011-11-10 06:34:14 +00005351 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005352 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005353}
5354
Peter Collingbournee9200682011-05-13 03:29:01 +00005355bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005356 // FIXME: Deal with vectors as array subscript bases.
5357 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005358 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005359
Nick Lewyckyad888682017-04-27 07:27:36 +00005360 bool Success = true;
5361 if (!evaluatePointer(E->getBase(), Result)) {
5362 if (!Info.noteFailure())
5363 return false;
5364 Success = false;
5365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005367 APSInt Index;
5368 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005369 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005370
Nick Lewyckyad888682017-04-27 07:27:36 +00005371 return Success &&
5372 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005373}
Eli Friedman9a156e52008-11-12 09:44:48 +00005374
Peter Collingbournee9200682011-05-13 03:29:01 +00005375bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005376 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005377}
5378
Richard Smith66c96992012-02-18 22:04:06 +00005379bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5380 if (!Visit(E->getSubExpr()))
5381 return false;
5382 // __real is a no-op on scalar lvalues.
5383 if (E->getSubExpr()->getType()->isAnyComplexType())
5384 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5385 return true;
5386}
5387
5388bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5389 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5390 "lvalue __imag__ on scalar?");
5391 if (!Visit(E->getSubExpr()))
5392 return false;
5393 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5394 return true;
5395}
5396
Richard Smith243ef902013-05-05 23:31:59 +00005397bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005398 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005399 return Error(UO);
5400
5401 if (!this->Visit(UO->getSubExpr()))
5402 return false;
5403
Richard Smith243ef902013-05-05 23:31:59 +00005404 return handleIncDec(
5405 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005406 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005407}
5408
5409bool LValueExprEvaluator::VisitCompoundAssignOperator(
5410 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005411 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005412 return Error(CAO);
5413
Richard Smith3229b742013-05-05 21:17:10 +00005414 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005415
5416 // The overall lvalue result is the result of evaluating the LHS.
5417 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005418 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005419 Evaluate(RHS, this->Info, CAO->getRHS());
5420 return false;
5421 }
5422
Richard Smith3229b742013-05-05 21:17:10 +00005423 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5424 return false;
5425
Richard Smith43e77732013-05-07 04:50:00 +00005426 return handleCompoundAssignment(
5427 this->Info, CAO,
5428 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5429 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005430}
5431
5432bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005433 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005434 return Error(E);
5435
Richard Smith3229b742013-05-05 21:17:10 +00005436 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005437
5438 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005439 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005440 Evaluate(NewVal, this->Info, E->getRHS());
5441 return false;
5442 }
5443
Richard Smith3229b742013-05-05 21:17:10 +00005444 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5445 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005446
5447 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005448 NewVal);
5449}
5450
Eli Friedman9a156e52008-11-12 09:44:48 +00005451//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005452// Pointer Evaluation
5453//===----------------------------------------------------------------------===//
5454
George Burgess IVe3763372016-12-22 02:50:20 +00005455/// \brief Attempts to compute the number of bytes available at the pointer
5456/// returned by a function with the alloc_size attribute. Returns true if we
5457/// were successful. Places an unsigned number into `Result`.
5458///
5459/// This expects the given CallExpr to be a call to a function with an
5460/// alloc_size attribute.
5461static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5462 const CallExpr *Call,
5463 llvm::APInt &Result) {
5464 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5465
Joel E. Denny49254452018-03-02 19:03:22 +00005466 assert(AllocSize && AllocSize->elemSizeParam().isValid());
5467 unsigned SizeArgNo = AllocSize->elemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005468 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5469 if (Call->getNumArgs() <= SizeArgNo)
5470 return false;
5471
5472 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5473 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5474 return false;
5475 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5476 return false;
5477 Into = Into.zextOrSelf(BitsInSizeT);
5478 return true;
5479 };
5480
5481 APSInt SizeOfElem;
5482 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5483 return false;
5484
Joel E. Denny49254452018-03-02 19:03:22 +00005485 if (!AllocSize->numElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005486 Result = std::move(SizeOfElem);
5487 return true;
5488 }
5489
5490 APSInt NumberOfElems;
Joel E. Denny49254452018-03-02 19:03:22 +00005491 unsigned NumArgNo = AllocSize->numElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005492 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5493 return false;
5494
5495 bool Overflow;
5496 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5497 if (Overflow)
5498 return false;
5499
5500 Result = std::move(BytesAvailable);
5501 return true;
5502}
5503
5504/// \brief Convenience function. LVal's base must be a call to an alloc_size
5505/// function.
5506static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5507 const LValue &LVal,
5508 llvm::APInt &Result) {
5509 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5510 "Can't get the size of a non alloc_size function");
5511 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5512 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5513 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5514}
5515
5516/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5517/// a function with the alloc_size attribute. If it was possible to do so, this
5518/// function will return true, make Result's Base point to said function call,
5519/// and mark Result's Base as invalid.
5520static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5521 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005522 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005523 return false;
5524
5525 // Because we do no form of static analysis, we only support const variables.
5526 //
5527 // Additionally, we can't support parameters, nor can we support static
5528 // variables (in the latter case, use-before-assign isn't UB; in the former,
5529 // we have no clue what they'll be assigned to).
5530 const auto *VD =
5531 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5532 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5533 return false;
5534
5535 const Expr *Init = VD->getAnyInitializer();
5536 if (!Init)
5537 return false;
5538
5539 const Expr *E = Init->IgnoreParens();
5540 if (!tryUnwrapAllocSizeCall(E))
5541 return false;
5542
5543 // Store E instead of E unwrapped so that the type of the LValue's base is
5544 // what the user wanted.
5545 Result.setInvalid(E);
5546
5547 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005548 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005549 return true;
5550}
5551
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005552namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005553class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005554 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005555 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005556 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005557
Peter Collingbournee9200682011-05-13 03:29:01 +00005558 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005559 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005560 return true;
5561 }
George Burgess IVe3763372016-12-22 02:50:20 +00005562
George Burgess IVf9013bf2017-02-10 22:52:29 +00005563 bool evaluateLValue(const Expr *E, LValue &Result) {
5564 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5565 }
5566
5567 bool evaluatePointer(const Expr *E, LValue &Result) {
5568 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5569 }
5570
George Burgess IVe3763372016-12-22 02:50:20 +00005571 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005572public:
Mike Stump11289f42009-09-09 15:08:12 +00005573
George Burgess IVf9013bf2017-02-10 22:52:29 +00005574 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5575 : ExprEvaluatorBaseTy(info), Result(Result),
5576 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005577
Richard Smith2e312c82012-03-03 22:46:17 +00005578 bool Success(const APValue &V, const Expr *E) {
5579 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005580 return true;
5581 }
Richard Smithfddd3842011-12-30 21:15:51 +00005582 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005583 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5584 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005585 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005586 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005587
John McCall45d55e42010-05-07 21:00:08 +00005588 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005589 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005590 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005591 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005592 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005593 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5594 if (Info.noteFailure())
5595 EvaluateIgnoredValue(Info, E->getSubExpr());
5596 return Error(E);
5597 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005598 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005599 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005600 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005601 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005602 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005603 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005604 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005605 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005606 }
Richard Smithd62306a2011-11-10 06:34:14 +00005607 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005608 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005609 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005610 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005611 if (!Info.CurrentCall->This) {
5612 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005613 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005614 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005615 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005616 return false;
5617 }
Richard Smithd62306a2011-11-10 06:34:14 +00005618 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005619 // If we are inside a lambda's call operator, the 'this' expression refers
5620 // to the enclosing '*this' object (either by value or reference) which is
5621 // either copied into the closure object's field that represents the '*this'
5622 // or refers to '*this'.
5623 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5624 // Update 'Result' to refer to the data member/field of the closure object
5625 // that represents the '*this' capture.
5626 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005627 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005628 return false;
5629 // If we captured '*this' by reference, replace the field with its referent.
5630 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5631 ->isPointerType()) {
5632 APValue RVal;
5633 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5634 RVal))
5635 return false;
5636
5637 Result.setFrom(Info.Ctx, RVal);
5638 }
5639 }
Richard Smithd62306a2011-11-10 06:34:14 +00005640 return true;
5641 }
John McCallc07a0c72011-02-17 10:25:35 +00005642
Eli Friedman449fe542009-03-23 04:56:01 +00005643 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005644};
Chris Lattner05706e882008-07-11 18:11:29 +00005645} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005646
George Burgess IVf9013bf2017-02-10 22:52:29 +00005647static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5648 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005649 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005650 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005651}
5652
John McCall45d55e42010-05-07 21:00:08 +00005653bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005654 if (E->getOpcode() != BO_Add &&
5655 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005656 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005657
Chris Lattner05706e882008-07-11 18:11:29 +00005658 const Expr *PExp = E->getLHS();
5659 const Expr *IExp = E->getRHS();
5660 if (IExp->getType()->isPointerType())
5661 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005662
George Burgess IVf9013bf2017-02-10 22:52:29 +00005663 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005664 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005665 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005666
John McCall45d55e42010-05-07 21:00:08 +00005667 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005668 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005669 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005670
Richard Smith96e0c102011-11-04 02:25:55 +00005671 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005672 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005673
Ted Kremenek28831752012-08-23 20:46:57 +00005674 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005675 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005676}
Eli Friedman9a156e52008-11-12 09:44:48 +00005677
John McCall45d55e42010-05-07 21:00:08 +00005678bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005679 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005680}
Mike Stump11289f42009-09-09 15:08:12 +00005681
Peter Collingbournee9200682011-05-13 03:29:01 +00005682bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5683 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005684
Eli Friedman847a2bc2009-12-27 05:43:15 +00005685 switch (E->getCastKind()) {
5686 default:
5687 break;
5688
John McCalle3027922010-08-25 11:45:40 +00005689 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005690 case CK_CPointerToObjCPointerCast:
5691 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005692 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005693 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005694 if (!Visit(SubExpr))
5695 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005696 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5697 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5698 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005699 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005700 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005701 if (SubExpr->getType()->isVoidPointerType())
5702 CCEDiag(E, diag::note_constexpr_invalid_cast)
5703 << 3 << SubExpr->getType();
5704 else
5705 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5706 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005707 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5708 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005709 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005710
Anders Carlsson18275092010-10-31 20:41:46 +00005711 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005712 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005713 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005714 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005715 if (!Result.Base && Result.Offset.isZero())
5716 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005717
Richard Smithd62306a2011-11-10 06:34:14 +00005718 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005719 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005720 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5721 castAs<PointerType>()->getPointeeType(),
5722 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005723
Richard Smith027bf112011-11-17 22:56:20 +00005724 case CK_BaseToDerived:
5725 if (!Visit(E->getSubExpr()))
5726 return false;
5727 if (!Result.Base && Result.Offset.isZero())
5728 return true;
5729 return HandleBaseToDerivedCast(Info, E, Result);
5730
Richard Smith0b0a0b62011-10-29 20:57:55 +00005731 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005732 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005733 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005734
John McCalle3027922010-08-25 11:45:40 +00005735 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005736 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5737
Richard Smith2e312c82012-03-03 22:46:17 +00005738 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005739 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005740 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005741
John McCall45d55e42010-05-07 21:00:08 +00005742 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005743 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5744 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005745 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005746 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005747 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005748 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005749 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005750 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005751 return true;
5752 } else {
5753 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005754 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005755 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005756 }
5757 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005758
5759 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005760 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005761 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005762 return false;
5763 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005764 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005765 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005766 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005767 return false;
5768 }
Richard Smith96e0c102011-11-04 02:25:55 +00005769 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005770 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5771 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005772 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005773 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005774 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005775 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005776 }
Richard Smithdd785442011-10-31 20:57:44 +00005777
John McCalle3027922010-08-25 11:45:40 +00005778 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005779 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005780
5781 case CK_LValueToRValue: {
5782 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005783 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005784 return false;
5785
5786 APValue RVal;
5787 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5788 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5789 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005790 return InvalidBaseOK &&
5791 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005792 return Success(RVal, E);
5793 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005794 }
5795
Richard Smith11562c52011-10-28 17:51:58 +00005796 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005797}
Chris Lattner05706e882008-07-11 18:11:29 +00005798
Hal Finkel0dd05d42014-10-03 17:18:37 +00005799static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5800 // C++ [expr.alignof]p3:
5801 // When alignof is applied to a reference type, the result is the
5802 // alignment of the referenced type.
5803 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5804 T = Ref->getPointeeType();
5805
5806 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005807 if (T.getQualifiers().hasUnaligned())
5808 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005809 return Info.Ctx.toCharUnitsFromBits(
5810 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5811}
5812
5813static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5814 E = E->IgnoreParens();
5815
5816 // The kinds of expressions that we have special-case logic here for
5817 // should be kept up to date with the special checks for those
5818 // expressions in Sema.
5819
5820 // alignof decl is always accepted, even if it doesn't make sense: we default
5821 // to 1 in those cases.
5822 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5823 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5824 /*RefAsPointee*/true);
5825
5826 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5827 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5828 /*RefAsPointee*/true);
5829
5830 return GetAlignOfType(Info, E->getType());
5831}
5832
George Burgess IVe3763372016-12-22 02:50:20 +00005833// To be clear: this happily visits unsupported builtins. Better name welcomed.
5834bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5835 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5836 return true;
5837
George Burgess IVf9013bf2017-02-10 22:52:29 +00005838 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005839 return false;
5840
5841 Result.setInvalid(E);
5842 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005843 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005844 return true;
5845}
5846
Peter Collingbournee9200682011-05-13 03:29:01 +00005847bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005848 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005849 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005850
Richard Smith6328cbd2016-11-16 00:57:23 +00005851 if (unsigned BuiltinOp = E->getBuiltinCallee())
5852 return VisitBuiltinCallExpr(E, BuiltinOp);
5853
George Burgess IVe3763372016-12-22 02:50:20 +00005854 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005855}
5856
5857bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5858 unsigned BuiltinOp) {
5859 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005860 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005861 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005862 case Builtin::BI__builtin_assume_aligned: {
5863 // We need to be very careful here because: if the pointer does not have the
5864 // asserted alignment, then the behavior is undefined, and undefined
5865 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005866 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005867 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005868
Hal Finkel0dd05d42014-10-03 17:18:37 +00005869 LValue OffsetResult(Result);
5870 APSInt Alignment;
5871 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5872 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005873 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005874
5875 if (E->getNumArgs() > 2) {
5876 APSInt Offset;
5877 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5878 return false;
5879
Richard Smith642a2362017-01-30 23:30:26 +00005880 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005881 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5882 }
5883
5884 // If there is a base object, then it must have the correct alignment.
5885 if (OffsetResult.Base) {
5886 CharUnits BaseAlignment;
5887 if (const ValueDecl *VD =
5888 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5889 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5890 } else {
5891 BaseAlignment =
5892 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5893 }
5894
5895 if (BaseAlignment < Align) {
5896 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005897 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005898 CCEDiag(E->getArg(0),
5899 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005900 << (unsigned)BaseAlignment.getQuantity()
5901 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005902 return false;
5903 }
5904 }
5905
5906 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005907 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005908 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005909
Richard Smith642a2362017-01-30 23:30:26 +00005910 (OffsetResult.Base
5911 ? CCEDiag(E->getArg(0),
5912 diag::note_constexpr_baa_insufficient_alignment) << 1
5913 : CCEDiag(E->getArg(0),
5914 diag::note_constexpr_baa_value_insufficient_alignment))
5915 << (int)OffsetResult.Offset.getQuantity()
5916 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005917 return false;
5918 }
5919
5920 return true;
5921 }
Richard Smithe9507952016-11-12 01:39:56 +00005922
5923 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005924 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005925 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005926 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005927 if (Info.getLangOpts().CPlusPlus11)
5928 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5929 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005930 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005931 else
5932 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005933 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005934 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005935 case Builtin::BI__builtin_wcschr:
5936 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005937 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005938 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005939 if (!Visit(E->getArg(0)))
5940 return false;
5941 APSInt Desired;
5942 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5943 return false;
5944 uint64_t MaxLength = uint64_t(-1);
5945 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005946 BuiltinOp != Builtin::BIwcschr &&
5947 BuiltinOp != Builtin::BI__builtin_strchr &&
5948 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005949 APSInt N;
5950 if (!EvaluateInteger(E->getArg(2), N, Info))
5951 return false;
5952 MaxLength = N.getExtValue();
5953 }
5954
Richard Smith8110c9d2016-11-29 19:45:17 +00005955 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005956
Richard Smith8110c9d2016-11-29 19:45:17 +00005957 // Figure out what value we're actually looking for (after converting to
5958 // the corresponding unsigned type if necessary).
5959 uint64_t DesiredVal;
5960 bool StopAtNull = false;
5961 switch (BuiltinOp) {
5962 case Builtin::BIstrchr:
5963 case Builtin::BI__builtin_strchr:
5964 // strchr compares directly to the passed integer, and therefore
5965 // always fails if given an int that is not a char.
5966 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5967 E->getArg(1)->getType(),
5968 Desired),
5969 Desired))
5970 return ZeroInitialization(E);
5971 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005972 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005973 case Builtin::BImemchr:
5974 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005975 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005976 // memchr compares by converting both sides to unsigned char. That's also
5977 // correct for strchr if we get this far (to cope with plain char being
5978 // unsigned in the strchr case).
5979 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5980 break;
Richard Smithe9507952016-11-12 01:39:56 +00005981
Richard Smith8110c9d2016-11-29 19:45:17 +00005982 case Builtin::BIwcschr:
5983 case Builtin::BI__builtin_wcschr:
5984 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005985 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005986 case Builtin::BIwmemchr:
5987 case Builtin::BI__builtin_wmemchr:
5988 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5989 DesiredVal = Desired.getZExtValue();
5990 break;
5991 }
Richard Smithe9507952016-11-12 01:39:56 +00005992
5993 for (; MaxLength; --MaxLength) {
5994 APValue Char;
5995 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5996 !Char.isInt())
5997 return false;
5998 if (Char.getInt().getZExtValue() == DesiredVal)
5999 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006000 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006001 break;
6002 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6003 return false;
6004 }
6005 // Not found: return nullptr.
6006 return ZeroInitialization(E);
6007 }
6008
Richard Smith6cbd65d2013-07-11 02:27:57 +00006009 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006010 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006011 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006012}
Chris Lattner05706e882008-07-11 18:11:29 +00006013
6014//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006015// Member Pointer Evaluation
6016//===----------------------------------------------------------------------===//
6017
6018namespace {
6019class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006020 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006021 MemberPtr &Result;
6022
6023 bool Success(const ValueDecl *D) {
6024 Result = MemberPtr(D);
6025 return true;
6026 }
6027public:
6028
6029 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6030 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6031
Richard Smith2e312c82012-03-03 22:46:17 +00006032 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006033 Result.setFrom(V);
6034 return true;
6035 }
Richard Smithfddd3842011-12-30 21:15:51 +00006036 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006037 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006038 }
6039
6040 bool VisitCastExpr(const CastExpr *E);
6041 bool VisitUnaryAddrOf(const UnaryOperator *E);
6042};
6043} // end anonymous namespace
6044
6045static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6046 EvalInfo &Info) {
6047 assert(E->isRValue() && E->getType()->isMemberPointerType());
6048 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6049}
6050
6051bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6052 switch (E->getCastKind()) {
6053 default:
6054 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6055
6056 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006057 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006058 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006059
6060 case CK_BaseToDerivedMemberPointer: {
6061 if (!Visit(E->getSubExpr()))
6062 return false;
6063 if (E->path_empty())
6064 return true;
6065 // Base-to-derived member pointer casts store the path in derived-to-base
6066 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6067 // the wrong end of the derived->base arc, so stagger the path by one class.
6068 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6069 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6070 PathI != PathE; ++PathI) {
6071 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6072 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6073 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006074 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006075 }
6076 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6077 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006078 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006079 return true;
6080 }
6081
6082 case CK_DerivedToBaseMemberPointer:
6083 if (!Visit(E->getSubExpr()))
6084 return false;
6085 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6086 PathE = E->path_end(); PathI != PathE; ++PathI) {
6087 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6088 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6089 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006090 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006091 }
6092 return true;
6093 }
6094}
6095
6096bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6097 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6098 // member can be formed.
6099 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6100}
6101
6102//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006103// Record Evaluation
6104//===----------------------------------------------------------------------===//
6105
6106namespace {
6107 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006108 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006109 const LValue &This;
6110 APValue &Result;
6111 public:
6112
6113 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6114 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6115
Richard Smith2e312c82012-03-03 22:46:17 +00006116 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006117 Result = V;
6118 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006119 }
Richard Smithb8348f52016-05-12 22:16:28 +00006120 bool ZeroInitialization(const Expr *E) {
6121 return ZeroInitialization(E, E->getType());
6122 }
6123 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006124
Richard Smith52a980a2015-08-28 02:43:42 +00006125 bool VisitCallExpr(const CallExpr *E) {
6126 return handleCallExpr(E, Result, &This);
6127 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006128 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006129 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006130 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6131 return VisitCXXConstructExpr(E, E->getType());
6132 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006133 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006134 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006135 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006136 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006137 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006138}
Richard Smithd62306a2011-11-10 06:34:14 +00006139
Richard Smithfddd3842011-12-30 21:15:51 +00006140/// Perform zero-initialization on an object of non-union class type.
6141/// C++11 [dcl.init]p5:
6142/// To zero-initialize an object or reference of type T means:
6143/// [...]
6144/// -- if T is a (possibly cv-qualified) non-union class type,
6145/// each non-static data member and each base-class subobject is
6146/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006147static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6148 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006149 const LValue &This, APValue &Result) {
6150 assert(!RD->isUnion() && "Expected non-union class type");
6151 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6152 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006153 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006154
John McCalld7bca762012-05-01 00:38:49 +00006155 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006156 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6157
6158 if (CD) {
6159 unsigned Index = 0;
6160 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006161 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006162 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6163 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006164 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6165 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006166 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006167 Result.getStructBase(Index)))
6168 return false;
6169 }
6170 }
6171
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006172 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006173 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006174 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006175 continue;
6176
6177 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006178 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006179 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006180
David Blaikie2d7c57e2012-04-30 02:36:29 +00006181 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006182 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006183 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006184 return false;
6185 }
6186
6187 return true;
6188}
6189
Richard Smithb8348f52016-05-12 22:16:28 +00006190bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6191 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006192 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006193 if (RD->isUnion()) {
6194 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6195 // object's first non-static named data member is zero-initialized
6196 RecordDecl::field_iterator I = RD->field_begin();
6197 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006198 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006199 return true;
6200 }
6201
6202 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006203 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006204 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006205 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006206 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006207 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006208 }
6209
Richard Smith5d108602012-02-17 00:44:16 +00006210 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006211 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006212 return false;
6213 }
6214
Richard Smitha8105bc2012-01-06 16:39:00 +00006215 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006216}
6217
Richard Smithe97cbd72011-11-11 04:05:33 +00006218bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6219 switch (E->getCastKind()) {
6220 default:
6221 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6222
6223 case CK_ConstructorConversion:
6224 return Visit(E->getSubExpr());
6225
6226 case CK_DerivedToBase:
6227 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006228 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006229 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006230 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006231 if (!DerivedObject.isStruct())
6232 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006233
6234 // Derived-to-base rvalue conversion: just slice off the derived part.
6235 APValue *Value = &DerivedObject;
6236 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6237 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6238 PathE = E->path_end(); PathI != PathE; ++PathI) {
6239 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6240 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6241 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6242 RD = Base;
6243 }
6244 Result = *Value;
6245 return true;
6246 }
6247 }
6248}
6249
Richard Smithd62306a2011-11-10 06:34:14 +00006250bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006251 if (E->isTransparent())
6252 return Visit(E->getInit(0));
6253
Richard Smithd62306a2011-11-10 06:34:14 +00006254 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006255 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006256 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6257
6258 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006259 const FieldDecl *Field = E->getInitializedFieldInUnion();
6260 Result = APValue(Field);
6261 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006262 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006263
6264 // If the initializer list for a union does not contain any elements, the
6265 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006266 // FIXME: The element should be initialized from an initializer list.
6267 // Is this difference ever observable for initializer lists which
6268 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006269 ImplicitValueInitExpr VIE(Field->getType());
6270 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6271
Richard Smithd62306a2011-11-10 06:34:14 +00006272 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006273 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6274 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006275
6276 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6277 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6278 isa<CXXDefaultInitExpr>(InitExpr));
6279
Richard Smithb228a862012-02-15 02:18:13 +00006280 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006281 }
6282
Richard Smith872307e2016-03-08 22:17:41 +00006283 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006284 if (Result.isUninit())
6285 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6286 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006287 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006288 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006289
6290 // Initialize base classes.
6291 if (CXXRD) {
6292 for (const auto &Base : CXXRD->bases()) {
6293 assert(ElementNo < E->getNumInits() && "missing init for base class");
6294 const Expr *Init = E->getInit(ElementNo);
6295
6296 LValue Subobject = This;
6297 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6298 return false;
6299
6300 APValue &FieldVal = Result.getStructBase(ElementNo);
6301 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006302 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006303 return false;
6304 Success = false;
6305 }
6306 ++ElementNo;
6307 }
6308 }
6309
6310 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006311 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006312 // Anonymous bit-fields are not considered members of the class for
6313 // purposes of aggregate initialization.
6314 if (Field->isUnnamedBitfield())
6315 continue;
6316
6317 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006318
Richard Smith253c2a32012-01-27 01:14:48 +00006319 bool HaveInit = ElementNo < E->getNumInits();
6320
6321 // FIXME: Diagnostics here should point to the end of the initializer
6322 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006323 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006324 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006325 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006326
6327 // Perform an implicit value-initialization for members beyond the end of
6328 // the initializer list.
6329 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006330 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006331
Richard Smith852c9db2013-04-20 22:23:05 +00006332 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6333 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6334 isa<CXXDefaultInitExpr>(Init));
6335
Richard Smith49ca8aa2013-08-06 07:09:20 +00006336 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6337 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6338 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006339 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006340 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006341 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006342 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006343 }
6344 }
6345
Richard Smith253c2a32012-01-27 01:14:48 +00006346 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006347}
6348
Richard Smithb8348f52016-05-12 22:16:28 +00006349bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6350 QualType T) {
6351 // Note that E's type is not necessarily the type of our class here; we might
6352 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006353 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006354 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6355
Richard Smithfddd3842011-12-30 21:15:51 +00006356 bool ZeroInit = E->requiresZeroInitialization();
6357 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006358 // If we've already performed zero-initialization, we're already done.
6359 if (!Result.isUninit())
6360 return true;
6361
Richard Smithda3f4fd2014-03-05 23:32:50 +00006362 // We can get here in two different ways:
6363 // 1) We're performing value-initialization, and should zero-initialize
6364 // the object, or
6365 // 2) We're performing default-initialization of an object with a trivial
6366 // constexpr default constructor, in which case we should start the
6367 // lifetimes of all the base subobjects (there can be no data member
6368 // subobjects in this case) per [basic.life]p1.
6369 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006370 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006371 }
6372
Craig Topper36250ad2014-05-12 05:36:57 +00006373 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006374 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006375
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006376 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006377 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006378
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006379 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006380 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006381 if (const MaterializeTemporaryExpr *ME
6382 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6383 return Visit(ME->GetTemporaryExpr());
6384
Richard Smithb8348f52016-05-12 22:16:28 +00006385 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006386 return false;
6387
Craig Topper5fc8fc22014-08-27 06:28:36 +00006388 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006389 return HandleConstructorCall(E, This, Args,
6390 cast<CXXConstructorDecl>(Definition), Info,
6391 Result);
6392}
6393
6394bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6395 const CXXInheritedCtorInitExpr *E) {
6396 if (!Info.CurrentCall) {
6397 assert(Info.checkingPotentialConstantExpression());
6398 return false;
6399 }
6400
6401 const CXXConstructorDecl *FD = E->getConstructor();
6402 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6403 return false;
6404
6405 const FunctionDecl *Definition = nullptr;
6406 auto Body = FD->getBody(Definition);
6407
6408 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6409 return false;
6410
6411 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006412 cast<CXXConstructorDecl>(Definition), Info,
6413 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006414}
6415
Richard Smithcc1b96d2013-06-12 22:31:48 +00006416bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6417 const CXXStdInitializerListExpr *E) {
6418 const ConstantArrayType *ArrayType =
6419 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6420
6421 LValue Array;
6422 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6423 return false;
6424
6425 // Get a pointer to the first element of the array.
6426 Array.addArray(Info, E, ArrayType);
6427
6428 // FIXME: Perform the checks on the field types in SemaInit.
6429 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6430 RecordDecl::field_iterator Field = Record->field_begin();
6431 if (Field == Record->field_end())
6432 return Error(E);
6433
6434 // Start pointer.
6435 if (!Field->getType()->isPointerType() ||
6436 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6437 ArrayType->getElementType()))
6438 return Error(E);
6439
6440 // FIXME: What if the initializer_list type has base classes, etc?
6441 Result = APValue(APValue::UninitStruct(), 0, 2);
6442 Array.moveInto(Result.getStructField(0));
6443
6444 if (++Field == Record->field_end())
6445 return Error(E);
6446
6447 if (Field->getType()->isPointerType() &&
6448 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6449 ArrayType->getElementType())) {
6450 // End pointer.
6451 if (!HandleLValueArrayAdjustment(Info, E, Array,
6452 ArrayType->getElementType(),
6453 ArrayType->getSize().getZExtValue()))
6454 return false;
6455 Array.moveInto(Result.getStructField(1));
6456 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6457 // Length.
6458 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6459 else
6460 return Error(E);
6461
6462 if (++Field != Record->field_end())
6463 return Error(E);
6464
6465 return true;
6466}
6467
Faisal Valic72a08c2017-01-09 03:02:53 +00006468bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6469 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6470 if (ClosureClass->isInvalidDecl()) return false;
6471
6472 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006473
Faisal Vali051e3a22017-02-16 04:12:21 +00006474 const size_t NumFields =
6475 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006476
6477 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6478 E->capture_init_end()) &&
6479 "The number of lambda capture initializers should equal the number of "
6480 "fields within the closure type");
6481
Faisal Vali051e3a22017-02-16 04:12:21 +00006482 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6483 // Iterate through all the lambda's closure object's fields and initialize
6484 // them.
6485 auto *CaptureInitIt = E->capture_init_begin();
6486 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6487 bool Success = true;
6488 for (const auto *Field : ClosureClass->fields()) {
6489 assert(CaptureInitIt != E->capture_init_end());
6490 // Get the initializer for this field
6491 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006492
Faisal Vali051e3a22017-02-16 04:12:21 +00006493 // If there is no initializer, either this is a VLA or an error has
6494 // occurred.
6495 if (!CurFieldInit)
6496 return Error(E);
6497
6498 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6499 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6500 if (!Info.keepEvaluatingAfterFailure())
6501 return false;
6502 Success = false;
6503 }
6504 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006505 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006506 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006507}
6508
Richard Smithd62306a2011-11-10 06:34:14 +00006509static bool EvaluateRecord(const Expr *E, const LValue &This,
6510 APValue &Result, EvalInfo &Info) {
6511 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006512 "can't evaluate expression as a record rvalue");
6513 return RecordExprEvaluator(Info, This, Result).Visit(E);
6514}
6515
6516//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006517// Temporary Evaluation
6518//
6519// Temporaries are represented in the AST as rvalues, but generally behave like
6520// lvalues. The full-object of which the temporary is a subobject is implicitly
6521// materialized so that a reference can bind to it.
6522//===----------------------------------------------------------------------===//
6523namespace {
6524class TemporaryExprEvaluator
6525 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6526public:
6527 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006528 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006529
6530 /// Visit an expression which constructs the value of this temporary.
6531 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006532 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006533 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6534 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006535 }
6536
6537 bool VisitCastExpr(const CastExpr *E) {
6538 switch (E->getCastKind()) {
6539 default:
6540 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6541
6542 case CK_ConstructorConversion:
6543 return VisitConstructExpr(E->getSubExpr());
6544 }
6545 }
6546 bool VisitInitListExpr(const InitListExpr *E) {
6547 return VisitConstructExpr(E);
6548 }
6549 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6550 return VisitConstructExpr(E);
6551 }
6552 bool VisitCallExpr(const CallExpr *E) {
6553 return VisitConstructExpr(E);
6554 }
Richard Smith513955c2014-12-17 19:24:30 +00006555 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6556 return VisitConstructExpr(E);
6557 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006558 bool VisitLambdaExpr(const LambdaExpr *E) {
6559 return VisitConstructExpr(E);
6560 }
Richard Smith027bf112011-11-17 22:56:20 +00006561};
6562} // end anonymous namespace
6563
6564/// Evaluate an expression of record type as a temporary.
6565static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006566 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006567 return TemporaryExprEvaluator(Info, Result).Visit(E);
6568}
6569
6570//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006571// Vector Evaluation
6572//===----------------------------------------------------------------------===//
6573
6574namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006575 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006576 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006577 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006578 public:
Mike Stump11289f42009-09-09 15:08:12 +00006579
Richard Smith2d406342011-10-22 21:10:00 +00006580 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6581 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006582
Craig Topper9798b932015-09-29 04:30:05 +00006583 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006584 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6585 // FIXME: remove this APValue copy.
6586 Result = APValue(V.data(), V.size());
6587 return true;
6588 }
Richard Smith2e312c82012-03-03 22:46:17 +00006589 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006590 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006591 Result = V;
6592 return true;
6593 }
Richard Smithfddd3842011-12-30 21:15:51 +00006594 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006595
Richard Smith2d406342011-10-22 21:10:00 +00006596 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006597 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006598 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006599 bool VisitInitListExpr(const InitListExpr *E);
6600 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006601 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006602 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006603 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006604 };
6605} // end anonymous namespace
6606
6607static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006608 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006609 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006610}
6611
George Burgess IV533ff002015-12-11 00:23:35 +00006612bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006613 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006614 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006615
Richard Smith161f09a2011-12-06 22:44:34 +00006616 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006617 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006618
Eli Friedmanc757de22011-03-25 00:43:55 +00006619 switch (E->getCastKind()) {
6620 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006621 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006622 if (SETy->isIntegerType()) {
6623 APSInt IntResult;
6624 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006625 return false;
6626 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006627 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006628 APFloat FloatResult(0.0);
6629 if (!EvaluateFloat(SE, FloatResult, Info))
6630 return false;
6631 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006632 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006633 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006634 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006635
6636 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006637 SmallVector<APValue, 4> Elts(NElts, Val);
6638 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006639 }
Eli Friedman803acb32011-12-22 03:51:45 +00006640 case CK_BitCast: {
6641 // Evaluate the operand into an APInt we can extract from.
6642 llvm::APInt SValInt;
6643 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6644 return false;
6645 // Extract the elements
6646 QualType EltTy = VTy->getElementType();
6647 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6648 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6649 SmallVector<APValue, 4> Elts;
6650 if (EltTy->isRealFloatingType()) {
6651 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006652 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006653 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006654 FloatEltSize = 80;
6655 for (unsigned i = 0; i < NElts; i++) {
6656 llvm::APInt Elt;
6657 if (BigEndian)
6658 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6659 else
6660 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006661 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006662 }
6663 } else if (EltTy->isIntegerType()) {
6664 for (unsigned i = 0; i < NElts; i++) {
6665 llvm::APInt Elt;
6666 if (BigEndian)
6667 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6668 else
6669 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6670 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6671 }
6672 } else {
6673 return Error(E);
6674 }
6675 return Success(Elts, E);
6676 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006677 default:
Richard Smith11562c52011-10-28 17:51:58 +00006678 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006679 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006680}
6681
Richard Smith2d406342011-10-22 21:10:00 +00006682bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006683VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006684 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006685 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006686 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006687
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006688 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006689 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006690
Eli Friedmanb9c71292012-01-03 23:24:20 +00006691 // The number of initializers can be less than the number of
6692 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006693 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006694 // should be initialized with zeroes.
6695 unsigned CountInits = 0, CountElts = 0;
6696 while (CountElts < NumElements) {
6697 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006698 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006699 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006700 APValue v;
6701 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6702 return Error(E);
6703 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006704 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006705 Elements.push_back(v.getVectorElt(j));
6706 CountElts += vlen;
6707 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006708 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006709 if (CountInits < NumInits) {
6710 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006711 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006712 } else // trailing integer zero.
6713 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6714 Elements.push_back(APValue(sInt));
6715 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006716 } else {
6717 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006718 if (CountInits < NumInits) {
6719 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006720 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006721 } else // trailing float zero.
6722 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6723 Elements.push_back(APValue(f));
6724 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006725 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006726 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006727 }
Richard Smith2d406342011-10-22 21:10:00 +00006728 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006729}
6730
Richard Smith2d406342011-10-22 21:10:00 +00006731bool
Richard Smithfddd3842011-12-30 21:15:51 +00006732VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006733 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006734 QualType EltTy = VT->getElementType();
6735 APValue ZeroElement;
6736 if (EltTy->isIntegerType())
6737 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6738 else
6739 ZeroElement =
6740 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6741
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006742 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006743 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006744}
6745
Richard Smith2d406342011-10-22 21:10:00 +00006746bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006747 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006748 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006749}
6750
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006751//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006752// Array Evaluation
6753//===----------------------------------------------------------------------===//
6754
6755namespace {
6756 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006757 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006758 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006759 APValue &Result;
6760 public:
6761
Richard Smithd62306a2011-11-10 06:34:14 +00006762 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6763 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006764
6765 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006766 assert((V.isArray() || V.isLValue()) &&
6767 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006768 Result = V;
6769 return true;
6770 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006771
Richard Smithfddd3842011-12-30 21:15:51 +00006772 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006773 const ConstantArrayType *CAT =
6774 Info.Ctx.getAsConstantArrayType(E->getType());
6775 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006776 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006777
6778 Result = APValue(APValue::UninitArray(), 0,
6779 CAT->getSize().getZExtValue());
6780 if (!Result.hasArrayFiller()) return true;
6781
Richard Smithfddd3842011-12-30 21:15:51 +00006782 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006783 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006784 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006785 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006786 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006787 }
6788
Richard Smith52a980a2015-08-28 02:43:42 +00006789 bool VisitCallExpr(const CallExpr *E) {
6790 return handleCallExpr(E, Result, &This);
6791 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006792 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006793 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006794 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006795 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6796 const LValue &Subobject,
6797 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006798 };
6799} // end anonymous namespace
6800
Richard Smithd62306a2011-11-10 06:34:14 +00006801static bool EvaluateArray(const Expr *E, const LValue &This,
6802 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006803 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006804 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006805}
6806
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006807// Return true iff the given array filler may depend on the element index.
6808static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6809 // For now, just whitelist non-class value-initialization and initialization
6810 // lists comprised of them.
6811 if (isa<ImplicitValueInitExpr>(FillerExpr))
6812 return false;
6813 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6814 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6815 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6816 return true;
6817 }
6818 return false;
6819 }
6820 return true;
6821}
6822
Richard Smithf3e9e432011-11-07 09:22:26 +00006823bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6824 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6825 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006826 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006827
Richard Smithca2cfbf2011-12-22 01:07:19 +00006828 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6829 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006830 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006831 LValue LV;
6832 if (!EvaluateLValue(E->getInit(0), LV, Info))
6833 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006834 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006835 LV.moveInto(Val);
6836 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006837 }
6838
Richard Smith253c2a32012-01-27 01:14:48 +00006839 bool Success = true;
6840
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006841 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6842 "zero-initialized array shouldn't have any initialized elts");
6843 APValue Filler;
6844 if (Result.isArray() && Result.hasArrayFiller())
6845 Filler = Result.getArrayFiller();
6846
Richard Smith9543c5e2013-04-22 14:44:29 +00006847 unsigned NumEltsToInit = E->getNumInits();
6848 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006849 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006850
6851 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006852 // array element.
6853 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006854 NumEltsToInit = NumElts;
6855
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006856 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6857 NumEltsToInit << ".\n");
6858
Richard Smith9543c5e2013-04-22 14:44:29 +00006859 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006860
6861 // If the array was previously zero-initialized, preserve the
6862 // zero-initialized values.
6863 if (!Filler.isUninit()) {
6864 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6865 Result.getArrayInitializedElt(I) = Filler;
6866 if (Result.hasArrayFiller())
6867 Result.getArrayFiller() = Filler;
6868 }
6869
Richard Smithd62306a2011-11-10 06:34:14 +00006870 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006871 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006872 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6873 const Expr *Init =
6874 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006875 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006876 Info, Subobject, Init) ||
6877 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006878 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006879 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006880 return false;
6881 Success = false;
6882 }
Richard Smithd62306a2011-11-10 06:34:14 +00006883 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006884
Richard Smith9543c5e2013-04-22 14:44:29 +00006885 if (!Result.hasArrayFiller())
6886 return Success;
6887
6888 // If we get here, we have a trivial filler, which we can just evaluate
6889 // once and splat over the rest of the array elements.
6890 assert(FillerExpr && "no array filler for incomplete init list");
6891 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6892 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006893}
6894
Richard Smith410306b2016-12-12 02:53:20 +00006895bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6896 if (E->getCommonExpr() &&
6897 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6898 Info, E->getCommonExpr()->getSourceExpr()))
6899 return false;
6900
6901 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6902
6903 uint64_t Elements = CAT->getSize().getZExtValue();
6904 Result = APValue(APValue::UninitArray(), Elements, Elements);
6905
6906 LValue Subobject = This;
6907 Subobject.addArray(Info, E, CAT);
6908
6909 bool Success = true;
6910 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6911 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6912 Info, Subobject, E->getSubExpr()) ||
6913 !HandleLValueArrayAdjustment(Info, E, Subobject,
6914 CAT->getElementType(), 1)) {
6915 if (!Info.noteFailure())
6916 return false;
6917 Success = false;
6918 }
6919 }
6920
6921 return Success;
6922}
6923
Richard Smith027bf112011-11-17 22:56:20 +00006924bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006925 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6926}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006927
Richard Smith9543c5e2013-04-22 14:44:29 +00006928bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6929 const LValue &Subobject,
6930 APValue *Value,
6931 QualType Type) {
6932 bool HadZeroInit = !Value->isUninit();
6933
6934 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6935 unsigned N = CAT->getSize().getZExtValue();
6936
6937 // Preserve the array filler if we had prior zero-initialization.
6938 APValue Filler =
6939 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6940 : APValue();
6941
6942 *Value = APValue(APValue::UninitArray(), N, N);
6943
6944 if (HadZeroInit)
6945 for (unsigned I = 0; I != N; ++I)
6946 Value->getArrayInitializedElt(I) = Filler;
6947
6948 // Initialize the elements.
6949 LValue ArrayElt = Subobject;
6950 ArrayElt.addArray(Info, E, CAT);
6951 for (unsigned I = 0; I != N; ++I)
6952 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6953 CAT->getElementType()) ||
6954 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6955 CAT->getElementType(), 1))
6956 return false;
6957
6958 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006959 }
Richard Smith027bf112011-11-17 22:56:20 +00006960
Richard Smith9543c5e2013-04-22 14:44:29 +00006961 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006962 return Error(E);
6963
Richard Smithb8348f52016-05-12 22:16:28 +00006964 return RecordExprEvaluator(Info, Subobject, *Value)
6965 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006966}
6967
Richard Smithf3e9e432011-11-07 09:22:26 +00006968//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006969// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006970//
6971// As a GNU extension, we support casting pointers to sufficiently-wide integer
6972// types and back in constant folding. Integer values are thus represented
6973// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006974//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006975
6976namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006977class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006978 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006979 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006980public:
Richard Smith2e312c82012-03-03 22:46:17 +00006981 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006982 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006983
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006984 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006985 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006986 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006987 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006988 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006989 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006990 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006991 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006992 return true;
6993 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006994 bool Success(const llvm::APSInt &SI, const Expr *E) {
6995 return Success(SI, E, Result);
6996 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006997
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006998 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006999 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007000 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007001 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007002 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007003 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007004 Result.getInt().setIsUnsigned(
7005 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007006 return true;
7007 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007008 bool Success(const llvm::APInt &I, const Expr *E) {
7009 return Success(I, E, Result);
7010 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007011
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007012 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007013 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007014 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007015 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007016 return true;
7017 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007018 bool Success(uint64_t Value, const Expr *E) {
7019 return Success(Value, E, Result);
7020 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007021
Ken Dyckdbc01912011-03-11 02:13:43 +00007022 bool Success(CharUnits Size, const Expr *E) {
7023 return Success(Size.getQuantity(), E);
7024 }
7025
Richard Smith2e312c82012-03-03 22:46:17 +00007026 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007027 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007028 Result = V;
7029 return true;
7030 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007031 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007032 }
Mike Stump11289f42009-09-09 15:08:12 +00007033
Richard Smithfddd3842011-12-30 21:15:51 +00007034 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007035
Peter Collingbournee9200682011-05-13 03:29:01 +00007036 //===--------------------------------------------------------------------===//
7037 // Visitor Methods
7038 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007039
Chris Lattner7174bf32008-07-12 00:38:25 +00007040 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007041 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007042 }
7043 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007044 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007045 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007046
7047 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7048 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007049 if (CheckReferencedDecl(E, E->getDecl()))
7050 return true;
7051
7052 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007053 }
7054 bool VisitMemberExpr(const MemberExpr *E) {
7055 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007056 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007057 return true;
7058 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007059
7060 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007061 }
7062
Peter Collingbournee9200682011-05-13 03:29:01 +00007063 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007064 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007065 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007066 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007067 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007068
Peter Collingbournee9200682011-05-13 03:29:01 +00007069 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007070 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007071
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007072 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007073 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007074 }
Mike Stump11289f42009-09-09 15:08:12 +00007075
Ted Kremeneke65b0862012-03-06 20:05:56 +00007076 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7077 return Success(E->getValue(), E);
7078 }
Richard Smith410306b2016-12-12 02:53:20 +00007079
7080 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7081 if (Info.ArrayInitIndex == uint64_t(-1)) {
7082 // We were asked to evaluate this subexpression independent of the
7083 // enclosing ArrayInitLoopExpr. We can't do that.
7084 Info.FFDiag(E);
7085 return false;
7086 }
7087 return Success(Info.ArrayInitIndex, E);
7088 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007089
Richard Smith4ce706a2011-10-11 21:43:33 +00007090 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007091 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007092 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007093 }
7094
Douglas Gregor29c42f22012-02-24 07:38:34 +00007095 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7096 return Success(E->getValue(), E);
7097 }
7098
John Wiegley6242b6a2011-04-28 00:16:57 +00007099 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7100 return Success(E->getValue(), E);
7101 }
7102
John Wiegleyf9f65842011-04-25 06:54:41 +00007103 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7104 return Success(E->getValue(), E);
7105 }
7106
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007107 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007108 bool VisitUnaryImag(const UnaryOperator *E);
7109
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007110 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007111 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007112
Eli Friedman4e7a2412009-02-27 04:45:43 +00007113 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007114};
Chris Lattner05706e882008-07-11 18:11:29 +00007115} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007116
Richard Smith11562c52011-10-28 17:51:58 +00007117/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7118/// produce either the integer value or a pointer.
7119///
7120/// GCC has a heinous extension which folds casts between pointer types and
7121/// pointer-sized integral types. We support this by allowing the evaluation of
7122/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7123/// Some simple arithmetic on such values is supported (they are treated much
7124/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007125static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007126 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007127 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007128 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007129}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007130
Richard Smithf57d8cb2011-12-09 22:58:01 +00007131static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007132 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007133 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007134 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007135 if (!Val.isInt()) {
7136 // FIXME: It would be better to produce the diagnostic for casting
7137 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007138 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007139 return false;
7140 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007141 Result = Val.getInt();
7142 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007143}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007144
Richard Smithf57d8cb2011-12-09 22:58:01 +00007145/// Check whether the given declaration can be directly converted to an integral
7146/// rvalue. If not, no diagnostic is produced; there are other things we can
7147/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007148bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007149 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007150 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007151 // Check for signedness/width mismatches between E type and ECD value.
7152 bool SameSign = (ECD->getInitVal().isSigned()
7153 == E->getType()->isSignedIntegerOrEnumerationType());
7154 bool SameWidth = (ECD->getInitVal().getBitWidth()
7155 == Info.Ctx.getIntWidth(E->getType()));
7156 if (SameSign && SameWidth)
7157 return Success(ECD->getInitVal(), E);
7158 else {
7159 // Get rid of mismatch (otherwise Success assertions will fail)
7160 // by computing a new value matching the type of E.
7161 llvm::APSInt Val = ECD->getInitVal();
7162 if (!SameSign)
7163 Val.setIsSigned(!ECD->getInitVal().isSigned());
7164 if (!SameWidth)
7165 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7166 return Success(Val, E);
7167 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007168 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007169 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007170}
7171
Chris Lattner86ee2862008-10-06 06:40:35 +00007172/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7173/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007174static int EvaluateBuiltinClassifyType(const CallExpr *E,
7175 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007176 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007177 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007178 enum gcc_type_class {
7179 no_type_class = -1,
7180 void_type_class, integer_type_class, char_type_class,
7181 enumeral_type_class, boolean_type_class,
7182 pointer_type_class, reference_type_class, offset_type_class,
7183 real_type_class, complex_type_class,
7184 function_type_class, method_type_class,
7185 record_type_class, union_type_class,
7186 array_type_class, string_type_class,
7187 lang_type_class
7188 };
Mike Stump11289f42009-09-09 15:08:12 +00007189
7190 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007191 // ideal, however it is what gcc does.
7192 if (E->getNumArgs() == 0)
7193 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007194
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007195 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7196 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7197
7198 switch (CanTy->getTypeClass()) {
7199#define TYPE(ID, BASE)
7200#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7201#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7202#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7203#include "clang/AST/TypeNodes.def"
7204 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7205
7206 case Type::Builtin:
7207 switch (BT->getKind()) {
7208#define BUILTIN_TYPE(ID, SINGLETON_ID)
7209#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7210#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7211#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7212#include "clang/AST/BuiltinTypes.def"
7213 case BuiltinType::Void:
7214 return void_type_class;
7215
7216 case BuiltinType::Bool:
7217 return boolean_type_class;
7218
7219 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7220 case BuiltinType::UChar:
7221 case BuiltinType::UShort:
7222 case BuiltinType::UInt:
7223 case BuiltinType::ULong:
7224 case BuiltinType::ULongLong:
7225 case BuiltinType::UInt128:
7226 return integer_type_class;
7227
7228 case BuiltinType::NullPtr:
7229 return pointer_type_class;
7230
7231 case BuiltinType::WChar_U:
7232 case BuiltinType::Char16:
7233 case BuiltinType::Char32:
7234 case BuiltinType::ObjCId:
7235 case BuiltinType::ObjCClass:
7236 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007237#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7238 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007239#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007240 case BuiltinType::OCLSampler:
7241 case BuiltinType::OCLEvent:
7242 case BuiltinType::OCLClkEvent:
7243 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007244 case BuiltinType::OCLReserveID:
7245 case BuiltinType::Dependent:
7246 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7247 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007248 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007249
7250 case Type::Enum:
7251 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7252 break;
7253
7254 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007255 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007256 break;
7257
7258 case Type::MemberPointer:
7259 if (CanTy->isMemberDataPointerType())
7260 return offset_type_class;
7261 else {
7262 // We expect member pointers to be either data or function pointers,
7263 // nothing else.
7264 assert(CanTy->isMemberFunctionPointerType());
7265 return method_type_class;
7266 }
7267
7268 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007269 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007270
7271 case Type::FunctionNoProto:
7272 case Type::FunctionProto:
7273 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7274
7275 case Type::Record:
7276 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7277 switch (RT->getDecl()->getTagKind()) {
7278 case TagTypeKind::TTK_Struct:
7279 case TagTypeKind::TTK_Class:
7280 case TagTypeKind::TTK_Interface:
7281 return record_type_class;
7282
7283 case TagTypeKind::TTK_Enum:
7284 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7285
7286 case TagTypeKind::TTK_Union:
7287 return union_type_class;
7288 }
7289 }
David Blaikie83d382b2011-09-23 05:06:16 +00007290 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007291
7292 case Type::ConstantArray:
7293 case Type::VariableArray:
7294 case Type::IncompleteArray:
7295 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7296
7297 case Type::BlockPointer:
7298 case Type::LValueReference:
7299 case Type::RValueReference:
7300 case Type::Vector:
7301 case Type::ExtVector:
7302 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007303 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007304 case Type::ObjCObject:
7305 case Type::ObjCInterface:
7306 case Type::ObjCObjectPointer:
7307 case Type::Pipe:
7308 case Type::Atomic:
7309 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7310 }
7311
7312 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007313}
7314
Richard Smith5fab0c92011-12-28 19:48:30 +00007315/// EvaluateBuiltinConstantPForLValue - Determine the result of
7316/// __builtin_constant_p when applied to the given lvalue.
7317///
7318/// An lvalue is only "constant" if it is a pointer or reference to the first
7319/// character of a string literal.
7320template<typename LValue>
7321static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007322 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007323 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7324}
7325
7326/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7327/// GCC as we can manage.
7328static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7329 QualType ArgType = Arg->getType();
7330
7331 // __builtin_constant_p always has one operand. The rules which gcc follows
7332 // are not precisely documented, but are as follows:
7333 //
7334 // - If the operand is of integral, floating, complex or enumeration type,
7335 // and can be folded to a known value of that type, it returns 1.
7336 // - If the operand and can be folded to a pointer to the first character
7337 // of a string literal (or such a pointer cast to an integral type), it
7338 // returns 1.
7339 //
7340 // Otherwise, it returns 0.
7341 //
7342 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7343 // its support for this does not currently work.
7344 if (ArgType->isIntegralOrEnumerationType()) {
7345 Expr::EvalResult Result;
7346 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7347 return false;
7348
7349 APValue &V = Result.Val;
7350 if (V.getKind() == APValue::Int)
7351 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007352 if (V.getKind() == APValue::LValue)
7353 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007354 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7355 return Arg->isEvaluatable(Ctx);
7356 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7357 LValue LV;
7358 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007359 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007360 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7361 : EvaluatePointer(Arg, LV, Info)) &&
7362 !Status.HasSideEffects)
7363 return EvaluateBuiltinConstantPForLValue(LV);
7364 }
7365
7366 // Anything else isn't considered to be sufficiently constant.
7367 return false;
7368}
7369
John McCall95007602010-05-10 23:27:23 +00007370/// Retrieves the "underlying object type" of the given expression,
7371/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007372static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007373 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7374 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007375 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007376 } else if (const Expr *E = B.get<const Expr*>()) {
7377 if (isa<CompoundLiteralExpr>(E))
7378 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007379 }
7380
7381 return QualType();
7382}
7383
George Burgess IV3a03fab2015-09-04 21:28:13 +00007384/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007385/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007386/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007387/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7388///
7389/// Always returns an RValue with a pointer representation.
7390static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7391 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7392
7393 auto *NoParens = E->IgnoreParens();
7394 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007395 if (Cast == nullptr)
7396 return NoParens;
7397
7398 // We only conservatively allow a few kinds of casts, because this code is
7399 // inherently a simple solution that seeks to support the common case.
7400 auto CastKind = Cast->getCastKind();
7401 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7402 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007403 return NoParens;
7404
7405 auto *SubExpr = Cast->getSubExpr();
7406 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7407 return NoParens;
7408 return ignorePointerCastsAndParens(SubExpr);
7409}
7410
George Burgess IVa51c4072015-10-16 01:49:01 +00007411/// Checks to see if the given LValue's Designator is at the end of the LValue's
7412/// record layout. e.g.
7413/// struct { struct { int a, b; } fst, snd; } obj;
7414/// obj.fst // no
7415/// obj.snd // yes
7416/// obj.fst.a // no
7417/// obj.fst.b // no
7418/// obj.snd.a // no
7419/// obj.snd.b // yes
7420///
7421/// Please note: this function is specialized for how __builtin_object_size
7422/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007423///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007424/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7425/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007426static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7427 assert(!LVal.Designator.Invalid);
7428
George Burgess IV4168d752016-06-27 19:40:41 +00007429 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7430 const RecordDecl *Parent = FD->getParent();
7431 Invalid = Parent->isInvalidDecl();
7432 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007433 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007434 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007435 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7436 };
7437
7438 auto &Base = LVal.getLValueBase();
7439 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7440 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007441 bool Invalid;
7442 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7443 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007444 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007445 for (auto *FD : IFD->chain()) {
7446 bool Invalid;
7447 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7448 return Invalid;
7449 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007450 }
7451 }
7452
George Burgess IVe3763372016-12-22 02:50:20 +00007453 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007454 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007455 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007456 // If we don't know the array bound, conservatively assume we're looking at
7457 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007458 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007459 if (BaseType->isIncompleteArrayType())
7460 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7461 else
7462 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007463 }
7464
7465 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7466 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007467 if (BaseType->isArrayType()) {
7468 // Because __builtin_object_size treats arrays as objects, we can ignore
7469 // the index iff this is the last array in the Designator.
7470 if (I + 1 == E)
7471 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007472 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7473 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007474 if (Index + 1 != CAT->getSize())
7475 return false;
7476 BaseType = CAT->getElementType();
7477 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007478 const auto *CT = BaseType->castAs<ComplexType>();
7479 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007480 if (Index != 1)
7481 return false;
7482 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007483 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007484 bool Invalid;
7485 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7486 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007487 BaseType = FD->getType();
7488 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007489 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007490 return false;
7491 }
7492 }
7493 return true;
7494}
7495
George Burgess IVe3763372016-12-22 02:50:20 +00007496/// Tests to see if the LValue has a user-specified designator (that isn't
7497/// necessarily valid). Note that this always returns 'true' if the LValue has
7498/// an unsized array as its first designator entry, because there's currently no
7499/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007500static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007501 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007502 return false;
7503
George Burgess IVe3763372016-12-22 02:50:20 +00007504 if (!LVal.Designator.Entries.empty())
7505 return LVal.Designator.isMostDerivedAnUnsizedArray();
7506
George Burgess IVa51c4072015-10-16 01:49:01 +00007507 if (!LVal.InvalidBase)
7508 return true;
7509
George Burgess IVe3763372016-12-22 02:50:20 +00007510 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7511 // the LValueBase.
7512 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7513 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007514}
7515
George Burgess IVe3763372016-12-22 02:50:20 +00007516/// Attempts to detect a user writing into a piece of memory that's impossible
7517/// to figure out the size of by just using types.
7518static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7519 const SubobjectDesignator &Designator = LVal.Designator;
7520 // Notes:
7521 // - Users can only write off of the end when we have an invalid base. Invalid
7522 // bases imply we don't know where the memory came from.
7523 // - We used to be a bit more aggressive here; we'd only be conservative if
7524 // the array at the end was flexible, or if it had 0 or 1 elements. This
7525 // broke some common standard library extensions (PR30346), but was
7526 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7527 // with some sort of whitelist. OTOH, it seems that GCC is always
7528 // conservative with the last element in structs (if it's an array), so our
7529 // current behavior is more compatible than a whitelisting approach would
7530 // be.
7531 return LVal.InvalidBase &&
7532 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7533 Designator.MostDerivedIsArrayElement &&
7534 isDesignatorAtObjectEnd(Ctx, LVal);
7535}
7536
7537/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7538/// Fails if the conversion would cause loss of precision.
7539static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7540 CharUnits &Result) {
7541 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7542 if (Int.ugt(CharUnitsMax))
7543 return false;
7544 Result = CharUnits::fromQuantity(Int.getZExtValue());
7545 return true;
7546}
7547
7548/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7549/// determine how many bytes exist from the beginning of the object to either
7550/// the end of the current subobject, or the end of the object itself, depending
7551/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007552///
George Burgess IVe3763372016-12-22 02:50:20 +00007553/// If this returns false, the value of Result is undefined.
7554static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7555 unsigned Type, const LValue &LVal,
7556 CharUnits &EndOffset) {
7557 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007558
George Burgess IV7fb7e362017-01-03 23:35:19 +00007559 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7560 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7561 return false;
7562 return HandleSizeof(Info, ExprLoc, Ty, Result);
7563 };
7564
George Burgess IVe3763372016-12-22 02:50:20 +00007565 // We want to evaluate the size of the entire object. This is a valid fallback
7566 // for when Type=1 and the designator is invalid, because we're asked for an
7567 // upper-bound.
7568 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7569 // Type=3 wants a lower bound, so we can't fall back to this.
7570 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007571 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007572
7573 llvm::APInt APEndOffset;
7574 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7575 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7576 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7577
7578 if (LVal.InvalidBase)
7579 return false;
7580
7581 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007582 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007583 }
7584
George Burgess IVe3763372016-12-22 02:50:20 +00007585 // We want to evaluate the size of a subobject.
7586 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007587
7588 // The following is a moderately common idiom in C:
7589 //
7590 // struct Foo { int a; char c[1]; };
7591 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7592 // strcpy(&F->c[0], Bar);
7593 //
George Burgess IVe3763372016-12-22 02:50:20 +00007594 // In order to not break too much legacy code, we need to support it.
7595 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7596 // If we can resolve this to an alloc_size call, we can hand that back,
7597 // because we know for certain how many bytes there are to write to.
7598 llvm::APInt APEndOffset;
7599 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7600 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7601 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7602
7603 // If we cannot determine the size of the initial allocation, then we can't
7604 // given an accurate upper-bound. However, we are still able to give
7605 // conservative lower-bounds for Type=3.
7606 if (Type == 1)
7607 return false;
7608 }
7609
7610 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007611 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007612 return false;
7613
George Burgess IVe3763372016-12-22 02:50:20 +00007614 // According to the GCC documentation, we want the size of the subobject
7615 // denoted by the pointer. But that's not quite right -- what we actually
7616 // want is the size of the immediately-enclosing array, if there is one.
7617 int64_t ElemsRemaining;
7618 if (Designator.MostDerivedIsArrayElement &&
7619 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7620 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7621 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7622 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7623 } else {
7624 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7625 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007626
George Burgess IVe3763372016-12-22 02:50:20 +00007627 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7628 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007629}
7630
George Burgess IVe3763372016-12-22 02:50:20 +00007631/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7632/// returns true and stores the result in @p Size.
7633///
7634/// If @p WasError is non-null, this will report whether the failure to evaluate
7635/// is to be treated as an Error in IntExprEvaluator.
7636static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7637 EvalInfo &Info, uint64_t &Size) {
7638 // Determine the denoted object.
7639 LValue LVal;
7640 {
7641 // The operand of __builtin_object_size is never evaluated for side-effects.
7642 // If there are any, but we can determine the pointed-to object anyway, then
7643 // ignore the side-effects.
7644 SpeculativeEvaluationRAII SpeculativeEval(Info);
7645 FoldOffsetRAII Fold(Info);
7646
7647 if (E->isGLValue()) {
7648 // It's possible for us to be given GLValues if we're called via
7649 // Expr::tryEvaluateObjectSize.
7650 APValue RVal;
7651 if (!EvaluateAsRValue(Info, E, RVal))
7652 return false;
7653 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007654 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7655 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007656 return false;
7657 }
7658
7659 // If we point to before the start of the object, there are no accessible
7660 // bytes.
7661 if (LVal.getLValueOffset().isNegative()) {
7662 Size = 0;
7663 return true;
7664 }
7665
7666 CharUnits EndOffset;
7667 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7668 return false;
7669
7670 // If we've fallen outside of the end offset, just pretend there's nothing to
7671 // write to/read from.
7672 if (EndOffset <= LVal.getLValueOffset())
7673 Size = 0;
7674 else
7675 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7676 return true;
John McCall95007602010-05-10 23:27:23 +00007677}
7678
Peter Collingbournee9200682011-05-13 03:29:01 +00007679bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007680 if (unsigned BuiltinOp = E->getBuiltinCallee())
7681 return VisitBuiltinCallExpr(E, BuiltinOp);
7682
7683 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7684}
7685
7686bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7687 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007688 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007689 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007690 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007691
7692 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007693 // The type was checked when we built the expression.
7694 unsigned Type =
7695 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7696 assert(Type <= 3 && "unexpected type");
7697
George Burgess IVe3763372016-12-22 02:50:20 +00007698 uint64_t Size;
7699 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7700 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007701
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007702 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007703 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007704
Richard Smith01ade172012-05-23 04:13:20 +00007705 // Expression had no side effects, but we couldn't statically determine the
7706 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007707 switch (Info.EvalMode) {
7708 case EvalInfo::EM_ConstantExpression:
7709 case EvalInfo::EM_PotentialConstantExpression:
7710 case EvalInfo::EM_ConstantFold:
7711 case EvalInfo::EM_EvaluateForOverflow:
7712 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007713 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007714 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007715 return Error(E);
7716 case EvalInfo::EM_ConstantExpressionUnevaluated:
7717 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007718 // Reduce it to a constant now.
7719 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007720 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007721
7722 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007723 }
7724
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007725 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007726 case Builtin::BI__builtin_bswap32:
7727 case Builtin::BI__builtin_bswap64: {
7728 APSInt Val;
7729 if (!EvaluateInteger(E->getArg(0), Val, Info))
7730 return false;
7731
7732 return Success(Val.byteSwap(), E);
7733 }
7734
Richard Smith8889a3d2013-06-13 06:26:32 +00007735 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007736 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007737
7738 // FIXME: BI__builtin_clrsb
7739 // FIXME: BI__builtin_clrsbl
7740 // FIXME: BI__builtin_clrsbll
7741
Richard Smith80b3c8e2013-06-13 05:04:16 +00007742 case Builtin::BI__builtin_clz:
7743 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007744 case Builtin::BI__builtin_clzll:
7745 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007746 APSInt Val;
7747 if (!EvaluateInteger(E->getArg(0), Val, Info))
7748 return false;
7749 if (!Val)
7750 return Error(E);
7751
7752 return Success(Val.countLeadingZeros(), E);
7753 }
7754
Richard Smith8889a3d2013-06-13 06:26:32 +00007755 case Builtin::BI__builtin_constant_p:
7756 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7757
Richard Smith80b3c8e2013-06-13 05:04:16 +00007758 case Builtin::BI__builtin_ctz:
7759 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007760 case Builtin::BI__builtin_ctzll:
7761 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007762 APSInt Val;
7763 if (!EvaluateInteger(E->getArg(0), Val, Info))
7764 return false;
7765 if (!Val)
7766 return Error(E);
7767
7768 return Success(Val.countTrailingZeros(), E);
7769 }
7770
Richard Smith8889a3d2013-06-13 06:26:32 +00007771 case Builtin::BI__builtin_eh_return_data_regno: {
7772 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7773 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7774 return Success(Operand, E);
7775 }
7776
7777 case Builtin::BI__builtin_expect:
7778 return Visit(E->getArg(0));
7779
7780 case Builtin::BI__builtin_ffs:
7781 case Builtin::BI__builtin_ffsl:
7782 case Builtin::BI__builtin_ffsll: {
7783 APSInt Val;
7784 if (!EvaluateInteger(E->getArg(0), Val, Info))
7785 return false;
7786
7787 unsigned N = Val.countTrailingZeros();
7788 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7789 }
7790
7791 case Builtin::BI__builtin_fpclassify: {
7792 APFloat Val(0.0);
7793 if (!EvaluateFloat(E->getArg(5), Val, Info))
7794 return false;
7795 unsigned Arg;
7796 switch (Val.getCategory()) {
7797 case APFloat::fcNaN: Arg = 0; break;
7798 case APFloat::fcInfinity: Arg = 1; break;
7799 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7800 case APFloat::fcZero: Arg = 4; break;
7801 }
7802 return Visit(E->getArg(Arg));
7803 }
7804
7805 case Builtin::BI__builtin_isinf_sign: {
7806 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007807 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007808 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7809 }
7810
Richard Smithea3019d2013-10-15 19:07:14 +00007811 case Builtin::BI__builtin_isinf: {
7812 APFloat Val(0.0);
7813 return EvaluateFloat(E->getArg(0), Val, Info) &&
7814 Success(Val.isInfinity() ? 1 : 0, E);
7815 }
7816
7817 case Builtin::BI__builtin_isfinite: {
7818 APFloat Val(0.0);
7819 return EvaluateFloat(E->getArg(0), Val, Info) &&
7820 Success(Val.isFinite() ? 1 : 0, E);
7821 }
7822
7823 case Builtin::BI__builtin_isnan: {
7824 APFloat Val(0.0);
7825 return EvaluateFloat(E->getArg(0), Val, Info) &&
7826 Success(Val.isNaN() ? 1 : 0, E);
7827 }
7828
7829 case Builtin::BI__builtin_isnormal: {
7830 APFloat Val(0.0);
7831 return EvaluateFloat(E->getArg(0), Val, Info) &&
7832 Success(Val.isNormal() ? 1 : 0, E);
7833 }
7834
Richard Smith8889a3d2013-06-13 06:26:32 +00007835 case Builtin::BI__builtin_parity:
7836 case Builtin::BI__builtin_parityl:
7837 case Builtin::BI__builtin_parityll: {
7838 APSInt Val;
7839 if (!EvaluateInteger(E->getArg(0), Val, Info))
7840 return false;
7841
7842 return Success(Val.countPopulation() % 2, E);
7843 }
7844
Richard Smith80b3c8e2013-06-13 05:04:16 +00007845 case Builtin::BI__builtin_popcount:
7846 case Builtin::BI__builtin_popcountl:
7847 case Builtin::BI__builtin_popcountll: {
7848 APSInt Val;
7849 if (!EvaluateInteger(E->getArg(0), Val, Info))
7850 return false;
7851
7852 return Success(Val.countPopulation(), E);
7853 }
7854
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007855 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007856 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007857 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007858 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007859 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007860 << /*isConstexpr*/0 << /*isConstructor*/0
7861 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007862 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007863 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007864 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007865 case Builtin::BI__builtin_strlen:
7866 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007867 // As an extension, we support __builtin_strlen() as a constant expression,
7868 // and support folding strlen() to a constant.
7869 LValue String;
7870 if (!EvaluatePointer(E->getArg(0), String, Info))
7871 return false;
7872
Richard Smith8110c9d2016-11-29 19:45:17 +00007873 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7874
Richard Smithe6c19f22013-11-15 02:10:04 +00007875 // Fast path: if it's a string literal, search the string value.
7876 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7877 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007878 // The string literal may have embedded null characters. Find the first
7879 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007880 StringRef Str = S->getBytes();
7881 int64_t Off = String.Offset.getQuantity();
7882 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007883 S->getCharByteWidth() == 1 &&
7884 // FIXME: Add fast-path for wchar_t too.
7885 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007886 Str = Str.substr(Off);
7887
7888 StringRef::size_type Pos = Str.find(0);
7889 if (Pos != StringRef::npos)
7890 Str = Str.substr(0, Pos);
7891
7892 return Success(Str.size(), E);
7893 }
7894
7895 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007896 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007897
7898 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007899 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7900 APValue Char;
7901 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7902 !Char.isInt())
7903 return false;
7904 if (!Char.getInt())
7905 return Success(Strlen, E);
7906 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7907 return false;
7908 }
7909 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007910
Richard Smithe151bab2016-11-11 23:43:35 +00007911 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007912 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007913 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007914 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007915 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007916 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007917 // A call to strlen is not a constant expression.
7918 if (Info.getLangOpts().CPlusPlus11)
7919 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7920 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007921 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007922 else
7923 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007924 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007925 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007926 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007927 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007928 case Builtin::BI__builtin_wcsncmp:
7929 case Builtin::BI__builtin_memcmp:
7930 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007931 LValue String1, String2;
7932 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7933 !EvaluatePointer(E->getArg(1), String2, Info))
7934 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007935
7936 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7937
Richard Smithe151bab2016-11-11 23:43:35 +00007938 uint64_t MaxLength = uint64_t(-1);
7939 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007940 BuiltinOp != Builtin::BIwcscmp &&
7941 BuiltinOp != Builtin::BI__builtin_strcmp &&
7942 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007943 APSInt N;
7944 if (!EvaluateInteger(E->getArg(2), N, Info))
7945 return false;
7946 MaxLength = N.getExtValue();
7947 }
7948 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007949 BuiltinOp != Builtin::BIwmemcmp &&
7950 BuiltinOp != Builtin::BI__builtin_memcmp &&
7951 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007952 for (; MaxLength; --MaxLength) {
7953 APValue Char1, Char2;
7954 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7955 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7956 !Char1.isInt() || !Char2.isInt())
7957 return false;
7958 if (Char1.getInt() != Char2.getInt())
7959 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7960 if (StopAtNull && !Char1.getInt())
7961 return Success(0, E);
7962 assert(!(StopAtNull && !Char2.getInt()));
7963 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7964 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7965 return false;
7966 }
7967 // We hit the strncmp / memcmp limit.
7968 return Success(0, E);
7969 }
7970
Richard Smith01ba47d2012-04-13 00:45:38 +00007971 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007972 case Builtin::BI__atomic_is_lock_free:
7973 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007974 APSInt SizeVal;
7975 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7976 return false;
7977
7978 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7979 // of two less than the maximum inline atomic width, we know it is
7980 // lock-free. If the size isn't a power of two, or greater than the
7981 // maximum alignment where we promote atomics, we know it is not lock-free
7982 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7983 // the answer can only be determined at runtime; for example, 16-byte
7984 // atomics have lock-free implementations on some, but not all,
7985 // x86-64 processors.
7986
7987 // Check power-of-two.
7988 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007989 if (Size.isPowerOfTwo()) {
7990 // Check against inlining width.
7991 unsigned InlineWidthBits =
7992 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7993 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7994 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7995 Size == CharUnits::One() ||
7996 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7997 Expr::NPC_NeverValueDependent))
7998 // OK, we will inline appropriately-aligned operations of this size,
7999 // and _Atomic(T) is appropriately-aligned.
8000 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008001
Richard Smith01ba47d2012-04-13 00:45:38 +00008002 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8003 castAs<PointerType>()->getPointeeType();
8004 if (!PointeeType->isIncompleteType() &&
8005 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8006 // OK, we will inline operations on this object.
8007 return Success(1, E);
8008 }
8009 }
8010 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008011
Richard Smith01ba47d2012-04-13 00:45:38 +00008012 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8013 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008014 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008015 case Builtin::BIomp_is_initial_device:
8016 // We can decide statically which value the runtime would return if called.
8017 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008018 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008019}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008020
Richard Smith8b3497e2011-10-31 01:37:14 +00008021static bool HasSameBase(const LValue &A, const LValue &B) {
8022 if (!A.getLValueBase())
8023 return !B.getLValueBase();
8024 if (!B.getLValueBase())
8025 return false;
8026
Richard Smithce40ad62011-11-12 22:28:03 +00008027 if (A.getLValueBase().getOpaqueValue() !=
8028 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008029 const Decl *ADecl = GetLValueBaseDecl(A);
8030 if (!ADecl)
8031 return false;
8032 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008033 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008034 return false;
8035 }
8036
8037 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008038 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008039}
8040
Richard Smithd20f1e62014-10-21 23:01:04 +00008041/// \brief Determine whether this is a pointer past the end of the complete
8042/// object referred to by the lvalue.
8043static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8044 const LValue &LV) {
8045 // A null pointer can be viewed as being "past the end" but we don't
8046 // choose to look at it that way here.
8047 if (!LV.getLValueBase())
8048 return false;
8049
8050 // If the designator is valid and refers to a subobject, we're not pointing
8051 // past the end.
8052 if (!LV.getLValueDesignator().Invalid &&
8053 !LV.getLValueDesignator().isOnePastTheEnd())
8054 return false;
8055
David Majnemerc378ca52015-08-29 08:32:55 +00008056 // A pointer to an incomplete type might be past-the-end if the type's size is
8057 // zero. We cannot tell because the type is incomplete.
8058 QualType Ty = getType(LV.getLValueBase());
8059 if (Ty->isIncompleteType())
8060 return true;
8061
Richard Smithd20f1e62014-10-21 23:01:04 +00008062 // We're a past-the-end pointer if we point to the byte after the object,
8063 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008064 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008065 return LV.getLValueOffset() == Size;
8066}
8067
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008068namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008069
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008070/// \brief Data recursive integer evaluator of certain binary operators.
8071///
8072/// We use a data recursive algorithm for binary operators so that we are able
8073/// to handle extreme cases of chained binary operators without causing stack
8074/// overflow.
8075class DataRecursiveIntBinOpEvaluator {
8076 struct EvalResult {
8077 APValue Val;
8078 bool Failed;
8079
8080 EvalResult() : Failed(false) { }
8081
8082 void swap(EvalResult &RHS) {
8083 Val.swap(RHS.Val);
8084 Failed = RHS.Failed;
8085 RHS.Failed = false;
8086 }
8087 };
8088
8089 struct Job {
8090 const Expr *E;
8091 EvalResult LHSResult; // meaningful only for binary operator expression.
8092 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008093
David Blaikie73726062015-08-12 23:09:24 +00008094 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008095 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008096
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008097 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008098 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008099 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008100
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008101 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008102 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008103 };
8104
8105 SmallVector<Job, 16> Queue;
8106
8107 IntExprEvaluator &IntEval;
8108 EvalInfo &Info;
8109 APValue &FinalResult;
8110
8111public:
8112 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8113 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8114
8115 /// \brief True if \param E is a binary operator that we are going to handle
8116 /// data recursively.
8117 /// We handle binary operators that are comma, logical, or that have operands
8118 /// with integral or enumeration type.
8119 static bool shouldEnqueue(const BinaryOperator *E) {
8120 return E->getOpcode() == BO_Comma ||
8121 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008122 (E->isRValue() &&
8123 E->getType()->isIntegralOrEnumerationType() &&
8124 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008125 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008126 }
8127
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008128 bool Traverse(const BinaryOperator *E) {
8129 enqueue(E);
8130 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008131 while (!Queue.empty())
8132 process(PrevResult);
8133
8134 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008135
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008136 FinalResult.swap(PrevResult.Val);
8137 return true;
8138 }
8139
8140private:
8141 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8142 return IntEval.Success(Value, E, Result);
8143 }
8144 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8145 return IntEval.Success(Value, E, Result);
8146 }
8147 bool Error(const Expr *E) {
8148 return IntEval.Error(E);
8149 }
8150 bool Error(const Expr *E, diag::kind D) {
8151 return IntEval.Error(E, D);
8152 }
8153
8154 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8155 return Info.CCEDiag(E, D);
8156 }
8157
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008158 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8159 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008160 bool &SuppressRHSDiags);
8161
8162 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8163 const BinaryOperator *E, APValue &Result);
8164
8165 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8166 Result.Failed = !Evaluate(Result.Val, Info, E);
8167 if (Result.Failed)
8168 Result.Val = APValue();
8169 }
8170
Richard Trieuba4d0872012-03-21 23:30:30 +00008171 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008172
8173 void enqueue(const Expr *E) {
8174 E = E->IgnoreParens();
8175 Queue.resize(Queue.size()+1);
8176 Queue.back().E = E;
8177 Queue.back().Kind = Job::AnyExprKind;
8178 }
8179};
8180
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008181}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008182
8183bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008184 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008185 bool &SuppressRHSDiags) {
8186 if (E->getOpcode() == BO_Comma) {
8187 // Ignore LHS but note if we could not evaluate it.
8188 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008189 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008190 return true;
8191 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008192
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008193 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008194 bool LHSAsBool;
8195 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008196 // We were able to evaluate the LHS, see if we can get away with not
8197 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008198 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8199 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008200 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008201 }
8202 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008203 LHSResult.Failed = true;
8204
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008205 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008206 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008207 if (!Info.noteSideEffect())
8208 return false;
8209
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 // We can't evaluate the LHS; however, sometimes the result
8211 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8212 // Don't ignore RHS and suppress diagnostics from this arm.
8213 SuppressRHSDiags = true;
8214 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008216 return true;
8217 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008219 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8220 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008221
George Burgess IVa145e252016-05-25 22:38:36 +00008222 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008223 return false; // Ignore RHS;
8224
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008225 return true;
8226}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008227
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008228static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8229 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008230 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8231 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8232 // offsets.
8233 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8234 CharUnits &Offset = LVal.getLValueOffset();
8235 uint64_t Offset64 = Offset.getQuantity();
8236 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8237 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8238 : Offset64 + Index64);
8239}
8240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241bool DataRecursiveIntBinOpEvaluator::
8242 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8243 const BinaryOperator *E, APValue &Result) {
8244 if (E->getOpcode() == BO_Comma) {
8245 if (RHSResult.Failed)
8246 return false;
8247 Result = RHSResult.Val;
8248 return true;
8249 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008251 if (E->isLogicalOp()) {
8252 bool lhsResult, rhsResult;
8253 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8254 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008255
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 if (LHSIsOK) {
8257 if (RHSIsOK) {
8258 if (E->getOpcode() == BO_LOr)
8259 return Success(lhsResult || rhsResult, E, Result);
8260 else
8261 return Success(lhsResult && rhsResult, E, Result);
8262 }
8263 } else {
8264 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008265 // We can't evaluate the LHS; however, sometimes the result
8266 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8267 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008268 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008269 }
8270 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008271
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008272 return false;
8273 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008274
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008275 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8276 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008277
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008278 if (LHSResult.Failed || RHSResult.Failed)
8279 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008280
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281 const APValue &LHSVal = LHSResult.Val;
8282 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008283
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008284 // Handle cases like (unsigned long)&a + 4.
8285 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8286 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008287 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008288 return true;
8289 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008290
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008291 // Handle cases like 4 + (unsigned long)&a
8292 if (E->getOpcode() == BO_Add &&
8293 RHSVal.isLValue() && LHSVal.isInt()) {
8294 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008295 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008296 return true;
8297 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008298
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008299 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8300 // Handle (intptr_t)&&A - (intptr_t)&&B.
8301 if (!LHSVal.getLValueOffset().isZero() ||
8302 !RHSVal.getLValueOffset().isZero())
8303 return false;
8304 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8305 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8306 if (!LHSExpr || !RHSExpr)
8307 return false;
8308 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8309 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8310 if (!LHSAddrExpr || !RHSAddrExpr)
8311 return false;
8312 // Make sure both labels come from the same function.
8313 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8314 RHSAddrExpr->getLabel()->getDeclContext())
8315 return false;
8316 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8317 return true;
8318 }
Richard Smith43e77732013-05-07 04:50:00 +00008319
8320 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008321 if (!LHSVal.isInt() || !RHSVal.isInt())
8322 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008323
8324 // Set up the width and signedness manually, in case it can't be deduced
8325 // from the operation we're performing.
8326 // FIXME: Don't do this in the cases where we can deduce it.
8327 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8328 E->getType()->isUnsignedIntegerOrEnumerationType());
8329 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8330 RHSVal.getInt(), Value))
8331 return false;
8332 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008333}
8334
Richard Trieuba4d0872012-03-21 23:30:30 +00008335void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008336 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008337
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008338 switch (job.Kind) {
8339 case Job::AnyExprKind: {
8340 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8341 if (shouldEnqueue(Bop)) {
8342 job.Kind = Job::BinOpKind;
8343 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008344 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008345 }
8346 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008347
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008348 EvaluateExpr(job.E, Result);
8349 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008350 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008351 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008352
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008353 case Job::BinOpKind: {
8354 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008355 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008356 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008357 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008358 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008359 }
8360 if (SuppressRHSDiags)
8361 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008362 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 job.Kind = Job::BinOpVisitedLHSKind;
8364 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008365 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008366 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008368 case Job::BinOpVisitedLHSKind: {
8369 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8370 EvalResult RHS;
8371 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008372 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008373 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008374 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008375 }
8376 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008378 llvm_unreachable("Invalid Job::Kind!");
8379}
8380
George Burgess IV8c892b52016-05-25 22:31:54 +00008381namespace {
8382/// Used when we determine that we should fail, but can keep evaluating prior to
8383/// noting that we had a failure.
8384class DelayedNoteFailureRAII {
8385 EvalInfo &Info;
8386 bool NoteFailure;
8387
8388public:
8389 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8390 : Info(Info), NoteFailure(NoteFailure) {}
8391 ~DelayedNoteFailureRAII() {
8392 if (NoteFailure) {
8393 bool ContinueAfterFailure = Info.noteFailure();
8394 (void)ContinueAfterFailure;
8395 assert(ContinueAfterFailure &&
8396 "Shouldn't have kept evaluating on failure.");
8397 }
8398 }
8399};
8400}
8401
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008402bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008403 // We don't call noteFailure immediately because the assignment happens after
8404 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008405 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008406 return Error(E);
8407
George Burgess IV8c892b52016-05-25 22:31:54 +00008408 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008409 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8410 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008411
Anders Carlssonacc79812008-11-16 07:17:21 +00008412 QualType LHSTy = E->getLHS()->getType();
8413 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008414
Chandler Carruthb29a7432014-10-11 11:03:30 +00008415 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008416 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008417 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008418 if (E->isAssignmentOp()) {
8419 LValue LV;
8420 EvaluateLValue(E->getLHS(), LV, Info);
8421 LHSOK = false;
8422 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008423 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8424 if (LHSOK) {
8425 LHS.makeComplexFloat();
8426 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8427 }
8428 } else {
8429 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8430 }
George Burgess IVa145e252016-05-25 22:38:36 +00008431 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008432 return false;
8433
Chandler Carruthb29a7432014-10-11 11:03:30 +00008434 if (E->getRHS()->getType()->isRealFloatingType()) {
8435 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8436 return false;
8437 RHS.makeComplexFloat();
8438 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8439 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008440 return false;
8441
8442 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008443 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008444 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008445 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008446 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8447
John McCalle3027922010-08-25 11:45:40 +00008448 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008449 return Success((CR_r == APFloat::cmpEqual &&
8450 CR_i == APFloat::cmpEqual), E);
8451 else {
John McCalle3027922010-08-25 11:45:40 +00008452 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008453 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008454 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008455 CR_r == APFloat::cmpLessThan ||
8456 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008457 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008458 CR_i == APFloat::cmpLessThan ||
8459 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008460 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008461 } else {
John McCalle3027922010-08-25 11:45:40 +00008462 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008463 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8464 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8465 else {
John McCalle3027922010-08-25 11:45:40 +00008466 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008467 "Invalid compex comparison.");
8468 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8469 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8470 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008471 }
8472 }
Mike Stump11289f42009-09-09 15:08:12 +00008473
Anders Carlssonacc79812008-11-16 07:17:21 +00008474 if (LHSTy->isRealFloatingType() &&
8475 RHSTy->isRealFloatingType()) {
8476 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008477
Richard Smith253c2a32012-01-27 01:14:48 +00008478 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008479 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008480 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008481
Richard Smith253c2a32012-01-27 01:14:48 +00008482 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008483 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008484
Anders Carlssonacc79812008-11-16 07:17:21 +00008485 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008486
Anders Carlssonacc79812008-11-16 07:17:21 +00008487 switch (E->getOpcode()) {
8488 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008489 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008490 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008491 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008492 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008493 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008494 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008495 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008496 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008497 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008498 E);
John McCalle3027922010-08-25 11:45:40 +00008499 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008500 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008501 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008502 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008503 || CR == APFloat::cmpLessThan
8504 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008505 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008506 }
Mike Stump11289f42009-09-09 15:08:12 +00008507
Eli Friedmana38da572009-04-28 19:17:36 +00008508 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008509 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008510 LValue LHSValue, RHSValue;
8511
8512 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008513 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008514 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008515
Richard Smith253c2a32012-01-27 01:14:48 +00008516 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008517 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008518
Richard Smith8b3497e2011-10-31 01:37:14 +00008519 // Reject differing bases from the normal codepath; we special-case
8520 // comparisons to null.
8521 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008522 if (E->getOpcode() == BO_Sub) {
8523 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008524 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008525 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008526 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008527 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008528 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008529 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008530 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8531 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8532 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008533 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008534 // Make sure both labels come from the same function.
8535 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8536 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008537 return Error(E);
8538 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008539 }
Richard Smith83c68212011-10-31 05:11:32 +00008540 // Inequalities and subtractions between unrelated pointers have
8541 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008542 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008543 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008544 // A constant address may compare equal to the address of a symbol.
8545 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008546 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008547 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8548 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008549 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008550 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008551 // distinct addresses. In clang, the result of such a comparison is
8552 // unspecified, so it is not a constant expression. However, we do know
8553 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008554 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8555 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008556 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008557 // We can't tell whether weak symbols will end up pointing to the same
8558 // object.
8559 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008560 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008561 // We can't compare the address of the start of one object with the
8562 // past-the-end address of another object, per C++ DR1652.
8563 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8564 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8565 (RHSValue.Base && RHSValue.Offset.isZero() &&
8566 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8567 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008568 // We can't tell whether an object is at the same address as another
8569 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008570 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8571 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008572 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008573 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008574 // (Note that clang defaults to -fmerge-all-constants, which can
8575 // lead to inconsistent results for comparisons involving the address
8576 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008577 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008578 }
Eli Friedman64004332009-03-23 04:38:34 +00008579
Richard Smith1b470412012-02-01 08:10:20 +00008580 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8581 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8582
Richard Smith84f6dcf2012-02-02 01:16:57 +00008583 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8584 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8585
John McCalle3027922010-08-25 11:45:40 +00008586 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008587 // C++11 [expr.add]p6:
8588 // Unless both pointers point to elements of the same array object, or
8589 // one past the last element of the array object, the behavior is
8590 // undefined.
8591 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8592 !AreElementsOfSameArray(getType(LHSValue.Base),
8593 LHSDesignator, RHSDesignator))
8594 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8595
Chris Lattner882bdf22010-04-20 17:13:14 +00008596 QualType Type = E->getLHS()->getType();
8597 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008598
Richard Smithd62306a2011-11-10 06:34:14 +00008599 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008600 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008601 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008602
Richard Smith84c6b3d2013-09-10 21:34:14 +00008603 // As an extension, a type may have zero size (empty struct or union in
8604 // C, array of zero length). Pointer subtraction in such cases has
8605 // undefined behavior, so is not constant.
8606 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008607 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008608 << ElementType;
8609 return false;
8610 }
8611
Richard Smith1b470412012-02-01 08:10:20 +00008612 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8613 // and produce incorrect results when it overflows. Such behavior
8614 // appears to be non-conforming, but is common, so perhaps we should
8615 // assume the standard intended for such cases to be undefined behavior
8616 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008617
Richard Smith1b470412012-02-01 08:10:20 +00008618 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8619 // overflow in the final conversion to ptrdiff_t.
8620 APSInt LHS(
8621 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8622 APSInt RHS(
8623 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8624 APSInt ElemSize(
8625 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8626 APSInt TrueResult = (LHS - RHS) / ElemSize;
8627 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8628
Richard Smith0c6124b2015-12-03 01:36:22 +00008629 if (Result.extend(65) != TrueResult &&
8630 !HandleOverflow(Info, E, TrueResult, E->getType()))
8631 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008632 return Success(Result, E);
8633 }
Richard Smithde21b242012-01-31 06:41:30 +00008634
8635 // C++11 [expr.rel]p3:
8636 // Pointers to void (after pointer conversions) can be compared, with a
8637 // result defined as follows: If both pointers represent the same
8638 // address or are both the null pointer value, the result is true if the
8639 // operator is <= or >= and false otherwise; otherwise the result is
8640 // unspecified.
8641 // We interpret this as applying to pointers to *cv* void.
8642 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008643 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008644 CCEDiag(E, diag::note_constexpr_void_comparison);
8645
Richard Smith84f6dcf2012-02-02 01:16:57 +00008646 // C++11 [expr.rel]p2:
8647 // - If two pointers point to non-static data members of the same object,
8648 // or to subobjects or array elements fo such members, recursively, the
8649 // pointer to the later declared member compares greater provided the
8650 // two members have the same access control and provided their class is
8651 // not a union.
8652 // [...]
8653 // - Otherwise pointer comparisons are unspecified.
8654 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8655 E->isRelationalOp()) {
8656 bool WasArrayIndex;
8657 unsigned Mismatch =
8658 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8659 RHSDesignator, WasArrayIndex);
8660 // At the point where the designators diverge, the comparison has a
8661 // specified value if:
8662 // - we are comparing array indices
8663 // - we are comparing fields of a union, or fields with the same access
8664 // Otherwise, the result is unspecified and thus the comparison is not a
8665 // constant expression.
8666 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8667 Mismatch < RHSDesignator.Entries.size()) {
8668 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8669 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8670 if (!LF && !RF)
8671 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8672 else if (!LF)
8673 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8674 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8675 << RF->getParent() << RF;
8676 else if (!RF)
8677 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8678 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8679 << LF->getParent() << LF;
8680 else if (!LF->getParent()->isUnion() &&
8681 LF->getAccess() != RF->getAccess())
8682 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8683 << LF << LF->getAccess() << RF << RF->getAccess()
8684 << LF->getParent();
8685 }
8686 }
8687
Eli Friedman6c31cb42012-04-16 04:30:08 +00008688 // The comparison here must be unsigned, and performed with the same
8689 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008690 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8691 uint64_t CompareLHS = LHSOffset.getQuantity();
8692 uint64_t CompareRHS = RHSOffset.getQuantity();
8693 assert(PtrSize <= 64 && "Unexpected pointer width");
8694 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8695 CompareLHS &= Mask;
8696 CompareRHS &= Mask;
8697
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008698 // If there is a base and this is a relational operator, we can only
8699 // compare pointers within the object in question; otherwise, the result
8700 // depends on where the object is located in memory.
8701 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8702 QualType BaseTy = getType(LHSValue.Base);
8703 if (BaseTy->isIncompleteType())
8704 return Error(E);
8705 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8706 uint64_t OffsetLimit = Size.getQuantity();
8707 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8708 return Error(E);
8709 }
8710
Richard Smith8b3497e2011-10-31 01:37:14 +00008711 switch (E->getOpcode()) {
8712 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008713 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8714 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8715 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8716 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8717 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8718 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008719 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008720 }
8721 }
Richard Smith7bb00672012-02-01 01:42:44 +00008722
8723 if (LHSTy->isMemberPointerType()) {
8724 assert(E->isEqualityOp() && "unexpected member pointer operation");
8725 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8726
8727 MemberPtr LHSValue, RHSValue;
8728
8729 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008730 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008731 return false;
8732
8733 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8734 return false;
8735
8736 // C++11 [expr.eq]p2:
8737 // If both operands are null, they compare equal. Otherwise if only one is
8738 // null, they compare unequal.
8739 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8740 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8741 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8742 }
8743
8744 // Otherwise if either is a pointer to a virtual member function, the
8745 // result is unspecified.
8746 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8747 if (MD->isVirtual())
8748 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8749 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8750 if (MD->isVirtual())
8751 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8752
8753 // Otherwise they compare equal if and only if they would refer to the
8754 // same member of the same most derived object or the same subobject if
8755 // they were dereferenced with a hypothetical object of the associated
8756 // class type.
8757 bool Equal = LHSValue == RHSValue;
8758 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8759 }
8760
Richard Smithab44d9b2012-02-14 22:35:28 +00008761 if (LHSTy->isNullPtrType()) {
8762 assert(E->isComparisonOp() && "unexpected nullptr operation");
8763 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8764 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8765 // are compared, the result is true of the operator is <=, >= or ==, and
8766 // false otherwise.
8767 BinaryOperator::Opcode Opcode = E->getOpcode();
8768 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8769 }
8770
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008771 assert((!LHSTy->isIntegralOrEnumerationType() ||
8772 !RHSTy->isIntegralOrEnumerationType()) &&
8773 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8774 // We can't continue from here for non-integral types.
8775 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008776}
8777
Peter Collingbournee190dee2011-03-11 19:24:49 +00008778/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8779/// a result as the expression's type.
8780bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8781 const UnaryExprOrTypeTraitExpr *E) {
8782 switch(E->getKind()) {
8783 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008784 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008785 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008786 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008787 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008788 }
Eli Friedman64004332009-03-23 04:38:34 +00008789
Peter Collingbournee190dee2011-03-11 19:24:49 +00008790 case UETT_VecStep: {
8791 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008792
Peter Collingbournee190dee2011-03-11 19:24:49 +00008793 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008794 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008795
Peter Collingbournee190dee2011-03-11 19:24:49 +00008796 // The vec_step built-in functions that take a 3-component
8797 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8798 if (n == 3)
8799 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008800
Peter Collingbournee190dee2011-03-11 19:24:49 +00008801 return Success(n, E);
8802 } else
8803 return Success(1, E);
8804 }
8805
8806 case UETT_SizeOf: {
8807 QualType SrcTy = E->getTypeOfArgument();
8808 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8809 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008810 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8811 SrcTy = Ref->getPointeeType();
8812
Richard Smithd62306a2011-11-10 06:34:14 +00008813 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008814 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008815 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008816 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008817 }
Alexey Bataev00396512015-07-02 03:40:19 +00008818 case UETT_OpenMPRequiredSimdAlign:
8819 assert(E->isArgumentType());
8820 return Success(
8821 Info.Ctx.toCharUnitsFromBits(
8822 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8823 .getQuantity(),
8824 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008825 }
8826
8827 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008828}
8829
Peter Collingbournee9200682011-05-13 03:29:01 +00008830bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008831 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008832 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008833 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008834 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008835 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008836 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008837 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008838 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008839 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008840 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008841 APSInt IdxResult;
8842 if (!EvaluateInteger(Idx, IdxResult, Info))
8843 return false;
8844 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8845 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008846 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008847 CurrentType = AT->getElementType();
8848 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8849 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008850 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008851 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008852
James Y Knight7281c352015-12-29 22:31:18 +00008853 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008854 FieldDecl *MemberDecl = ON.getField();
8855 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008856 if (!RT)
8857 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008858 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008859 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008860 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008861 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008862 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008863 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008864 CurrentType = MemberDecl->getType().getNonReferenceType();
8865 break;
8866 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008867
James Y Knight7281c352015-12-29 22:31:18 +00008868 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008869 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008870
James Y Knight7281c352015-12-29 22:31:18 +00008871 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008872 CXXBaseSpecifier *BaseSpec = ON.getBase();
8873 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008874 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008875
8876 // Find the layout of the class whose base we are looking into.
8877 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008878 if (!RT)
8879 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008880 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008881 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008882 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8883
8884 // Find the base class itself.
8885 CurrentType = BaseSpec->getType();
8886 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8887 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008888 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008889
Douglas Gregord1702062010-04-29 00:18:15 +00008890 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008891 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008892 break;
8893 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008894 }
8895 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008896 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008897}
8898
Chris Lattnere13042c2008-07-11 19:10:17 +00008899bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008900 switch (E->getOpcode()) {
8901 default:
8902 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8903 // See C99 6.6p3.
8904 return Error(E);
8905 case UO_Extension:
8906 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8907 // If so, we could clear the diagnostic ID.
8908 return Visit(E->getSubExpr());
8909 case UO_Plus:
8910 // The result is just the value.
8911 return Visit(E->getSubExpr());
8912 case UO_Minus: {
8913 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008914 return false;
8915 if (!Result.isInt()) return Error(E);
8916 const APSInt &Value = Result.getInt();
8917 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8918 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8919 E->getType()))
8920 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008921 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008922 }
8923 case UO_Not: {
8924 if (!Visit(E->getSubExpr()))
8925 return false;
8926 if (!Result.isInt()) return Error(E);
8927 return Success(~Result.getInt(), E);
8928 }
8929 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008930 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008931 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008932 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008933 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008934 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008935 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008936}
Mike Stump11289f42009-09-09 15:08:12 +00008937
Chris Lattner477c4be2008-07-12 01:15:53 +00008938/// HandleCast - This is used to evaluate implicit or explicit casts where the
8939/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008940bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8941 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008942 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008943 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008944
Eli Friedmanc757de22011-03-25 00:43:55 +00008945 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008946 case CK_BaseToDerived:
8947 case CK_DerivedToBase:
8948 case CK_UncheckedDerivedToBase:
8949 case CK_Dynamic:
8950 case CK_ToUnion:
8951 case CK_ArrayToPointerDecay:
8952 case CK_FunctionToPointerDecay:
8953 case CK_NullToPointer:
8954 case CK_NullToMemberPointer:
8955 case CK_BaseToDerivedMemberPointer:
8956 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008957 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008958 case CK_ConstructorConversion:
8959 case CK_IntegralToPointer:
8960 case CK_ToVoid:
8961 case CK_VectorSplat:
8962 case CK_IntegralToFloating:
8963 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008964 case CK_CPointerToObjCPointerCast:
8965 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008966 case CK_AnyPointerToBlockPointerCast:
8967 case CK_ObjCObjectLValueCast:
8968 case CK_FloatingRealToComplex:
8969 case CK_FloatingComplexToReal:
8970 case CK_FloatingComplexCast:
8971 case CK_FloatingComplexToIntegralComplex:
8972 case CK_IntegralRealToComplex:
8973 case CK_IntegralComplexCast:
8974 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008975 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008976 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008977 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008978 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008979 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008980 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008981 llvm_unreachable("invalid cast kind for integral value");
8982
Eli Friedman9faf2f92011-03-25 19:07:11 +00008983 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008984 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008985 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008986 case CK_ARCProduceObject:
8987 case CK_ARCConsumeObject:
8988 case CK_ARCReclaimReturnedObject:
8989 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008990 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008991 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008992
Richard Smith4ef685b2012-01-17 21:17:26 +00008993 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008994 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008995 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008996 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008997 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008998
8999 case CK_MemberPointerToBoolean:
9000 case CK_PointerToBoolean:
9001 case CK_IntegralToBoolean:
9002 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009003 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009004 case CK_FloatingComplexToBoolean:
9005 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009006 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009007 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009008 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009009 uint64_t IntResult = BoolResult;
9010 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9011 IntResult = (uint64_t)-1;
9012 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009013 }
9014
Eli Friedmanc757de22011-03-25 00:43:55 +00009015 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009016 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009017 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009018
Eli Friedman742421e2009-02-20 01:15:07 +00009019 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009020 // Allow casts of address-of-label differences if they are no-ops
9021 // or narrowing. (The narrowing case isn't actually guaranteed to
9022 // be constant-evaluatable except in some narrow cases which are hard
9023 // to detect here. We let it through on the assumption the user knows
9024 // what they are doing.)
9025 if (Result.isAddrLabelDiff())
9026 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009027 // Only allow casts of lvalues if they are lossless.
9028 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9029 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009030
Richard Smith911e1422012-01-30 22:27:01 +00009031 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9032 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009033 }
Mike Stump11289f42009-09-09 15:08:12 +00009034
Eli Friedmanc757de22011-03-25 00:43:55 +00009035 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009036 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9037
John McCall45d55e42010-05-07 21:00:08 +00009038 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009039 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009040 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009041
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009042 if (LV.getLValueBase()) {
9043 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009044 // FIXME: Allow a larger integer size than the pointer size, and allow
9045 // narrowing back down to pointer width in subsequent integral casts.
9046 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009047 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009048 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009049
Richard Smithcf74da72011-11-16 07:18:12 +00009050 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009051 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009052 return true;
9053 }
9054
Yaxun Liu402804b2016-12-15 08:09:08 +00009055 uint64_t V;
9056 if (LV.isNullPointer())
9057 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9058 else
9059 V = LV.getLValueOffset().getQuantity();
9060
9061 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009062 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009063 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009064
Eli Friedmanc757de22011-03-25 00:43:55 +00009065 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009066 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009067 if (!EvaluateComplex(SubExpr, C, Info))
9068 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009069 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009070 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009071
Eli Friedmanc757de22011-03-25 00:43:55 +00009072 case CK_FloatingToIntegral: {
9073 APFloat F(0.0);
9074 if (!EvaluateFloat(SubExpr, F, Info))
9075 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009076
Richard Smith357362d2011-12-13 06:39:58 +00009077 APSInt Value;
9078 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9079 return false;
9080 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009081 }
9082 }
Mike Stump11289f42009-09-09 15:08:12 +00009083
Eli Friedmanc757de22011-03-25 00:43:55 +00009084 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009085}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009086
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009087bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9088 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009089 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009090 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9091 return false;
9092 if (!LV.isComplexInt())
9093 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009094 return Success(LV.getComplexIntReal(), E);
9095 }
9096
9097 return Visit(E->getSubExpr());
9098}
9099
Eli Friedman4e7a2412009-02-27 04:45:43 +00009100bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009101 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009102 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009103 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9104 return false;
9105 if (!LV.isComplexInt())
9106 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009107 return Success(LV.getComplexIntImag(), E);
9108 }
9109
Richard Smith4a678122011-10-24 18:44:57 +00009110 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009111 return Success(0, E);
9112}
9113
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009114bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9115 return Success(E->getPackLength(), E);
9116}
9117
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009118bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9119 return Success(E->getValue(), E);
9120}
9121
Chris Lattner05706e882008-07-11 18:11:29 +00009122//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009123// Float Evaluation
9124//===----------------------------------------------------------------------===//
9125
9126namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009127class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009128 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009129 APFloat &Result;
9130public:
9131 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009132 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009133
Richard Smith2e312c82012-03-03 22:46:17 +00009134 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009135 Result = V.getFloat();
9136 return true;
9137 }
Eli Friedman24c01542008-08-22 00:06:13 +00009138
Richard Smithfddd3842011-12-30 21:15:51 +00009139 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009140 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9141 return true;
9142 }
9143
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009144 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009145
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009146 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009147 bool VisitBinaryOperator(const BinaryOperator *E);
9148 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009149 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009150
John McCallb1fb0d32010-05-07 22:08:54 +00009151 bool VisitUnaryReal(const UnaryOperator *E);
9152 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009153
Richard Smithfddd3842011-12-30 21:15:51 +00009154 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009155};
9156} // end anonymous namespace
9157
9158static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009159 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009160 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009161}
9162
Jay Foad39c79802011-01-12 09:06:06 +00009163static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009164 QualType ResultTy,
9165 const Expr *Arg,
9166 bool SNaN,
9167 llvm::APFloat &Result) {
9168 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9169 if (!S) return false;
9170
9171 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9172
9173 llvm::APInt fill;
9174
9175 // Treat empty strings as if they were zero.
9176 if (S->getString().empty())
9177 fill = llvm::APInt(32, 0);
9178 else if (S->getString().getAsInteger(0, fill))
9179 return false;
9180
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009181 if (Context.getTargetInfo().isNan2008()) {
9182 if (SNaN)
9183 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9184 else
9185 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9186 } else {
9187 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9188 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9189 // a different encoding to what became a standard in 2008, and for pre-
9190 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9191 // sNaN. This is now known as "legacy NaN" encoding.
9192 if (SNaN)
9193 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9194 else
9195 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9196 }
9197
John McCall16291492010-02-28 13:00:19 +00009198 return true;
9199}
9200
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009201bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009202 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009203 default:
9204 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9205
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009206 case Builtin::BI__builtin_huge_val:
9207 case Builtin::BI__builtin_huge_valf:
9208 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009209 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009210 case Builtin::BI__builtin_inf:
9211 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009212 case Builtin::BI__builtin_infl:
9213 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009214 const llvm::fltSemantics &Sem =
9215 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009216 Result = llvm::APFloat::getInf(Sem);
9217 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009218 }
Mike Stump11289f42009-09-09 15:08:12 +00009219
John McCall16291492010-02-28 13:00:19 +00009220 case Builtin::BI__builtin_nans:
9221 case Builtin::BI__builtin_nansf:
9222 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009223 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009224 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9225 true, Result))
9226 return Error(E);
9227 return true;
John McCall16291492010-02-28 13:00:19 +00009228
Chris Lattner0b7282e2008-10-06 06:31:58 +00009229 case Builtin::BI__builtin_nan:
9230 case Builtin::BI__builtin_nanf:
9231 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009232 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009233 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009234 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009235 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9236 false, Result))
9237 return Error(E);
9238 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009239
9240 case Builtin::BI__builtin_fabs:
9241 case Builtin::BI__builtin_fabsf:
9242 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009243 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009244 if (!EvaluateFloat(E->getArg(0), Result, Info))
9245 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009246
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009247 if (Result.isNegative())
9248 Result.changeSign();
9249 return true;
9250
Richard Smith8889a3d2013-06-13 06:26:32 +00009251 // FIXME: Builtin::BI__builtin_powi
9252 // FIXME: Builtin::BI__builtin_powif
9253 // FIXME: Builtin::BI__builtin_powil
9254
Mike Stump11289f42009-09-09 15:08:12 +00009255 case Builtin::BI__builtin_copysign:
9256 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009257 case Builtin::BI__builtin_copysignl:
9258 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009259 APFloat RHS(0.);
9260 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9261 !EvaluateFloat(E->getArg(1), RHS, Info))
9262 return false;
9263 Result.copySign(RHS);
9264 return true;
9265 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009266 }
9267}
9268
John McCallb1fb0d32010-05-07 22:08:54 +00009269bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009270 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9271 ComplexValue CV;
9272 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9273 return false;
9274 Result = CV.FloatReal;
9275 return true;
9276 }
9277
9278 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009279}
9280
9281bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009282 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9283 ComplexValue CV;
9284 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9285 return false;
9286 Result = CV.FloatImag;
9287 return true;
9288 }
9289
Richard Smith4a678122011-10-24 18:44:57 +00009290 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009291 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9292 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009293 return true;
9294}
9295
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009296bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009297 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009298 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009299 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009300 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009301 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009302 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9303 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009304 Result.changeSign();
9305 return true;
9306 }
9307}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009308
Eli Friedman24c01542008-08-22 00:06:13 +00009309bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009310 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9311 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009312
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009313 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009314 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009315 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009316 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009317 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9318 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009319}
9320
9321bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9322 Result = E->getValue();
9323 return true;
9324}
9325
Peter Collingbournee9200682011-05-13 03:29:01 +00009326bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9327 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009328
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009329 switch (E->getCastKind()) {
9330 default:
Richard Smith11562c52011-10-28 17:51:58 +00009331 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009332
9333 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009334 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009335 return EvaluateInteger(SubExpr, IntResult, Info) &&
9336 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9337 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009338 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009339
9340 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009341 if (!Visit(SubExpr))
9342 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009343 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9344 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009345 }
John McCalld7646252010-11-14 08:17:51 +00009346
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009347 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009348 ComplexValue V;
9349 if (!EvaluateComplex(SubExpr, V, Info))
9350 return false;
9351 Result = V.getComplexFloatReal();
9352 return true;
9353 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009354 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009355}
9356
Eli Friedman24c01542008-08-22 00:06:13 +00009357//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009358// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009359//===----------------------------------------------------------------------===//
9360
9361namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009362class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009363 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009364 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009365
Anders Carlsson537969c2008-11-16 20:27:53 +00009366public:
John McCall93d91dc2010-05-07 17:22:02 +00009367 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009368 : ExprEvaluatorBaseTy(info), Result(Result) {}
9369
Richard Smith2e312c82012-03-03 22:46:17 +00009370 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009371 Result.setFrom(V);
9372 return true;
9373 }
Mike Stump11289f42009-09-09 15:08:12 +00009374
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009375 bool ZeroInitialization(const Expr *E);
9376
Anders Carlsson537969c2008-11-16 20:27:53 +00009377 //===--------------------------------------------------------------------===//
9378 // Visitor Methods
9379 //===--------------------------------------------------------------------===//
9380
Peter Collingbournee9200682011-05-13 03:29:01 +00009381 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009382 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009383 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009384 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009385 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009386};
9387} // end anonymous namespace
9388
John McCall93d91dc2010-05-07 17:22:02 +00009389static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9390 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009391 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009392 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009393}
9394
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009395bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009396 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009397 if (ElemTy->isRealFloatingType()) {
9398 Result.makeComplexFloat();
9399 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9400 Result.FloatReal = Zero;
9401 Result.FloatImag = Zero;
9402 } else {
9403 Result.makeComplexInt();
9404 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9405 Result.IntReal = Zero;
9406 Result.IntImag = Zero;
9407 }
9408 return true;
9409}
9410
Peter Collingbournee9200682011-05-13 03:29:01 +00009411bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9412 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009413
9414 if (SubExpr->getType()->isRealFloatingType()) {
9415 Result.makeComplexFloat();
9416 APFloat &Imag = Result.FloatImag;
9417 if (!EvaluateFloat(SubExpr, Imag, Info))
9418 return false;
9419
9420 Result.FloatReal = APFloat(Imag.getSemantics());
9421 return true;
9422 } else {
9423 assert(SubExpr->getType()->isIntegerType() &&
9424 "Unexpected imaginary literal.");
9425
9426 Result.makeComplexInt();
9427 APSInt &Imag = Result.IntImag;
9428 if (!EvaluateInteger(SubExpr, Imag, Info))
9429 return false;
9430
9431 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9432 return true;
9433 }
9434}
9435
Peter Collingbournee9200682011-05-13 03:29:01 +00009436bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009437
John McCallfcef3cf2010-12-14 17:51:41 +00009438 switch (E->getCastKind()) {
9439 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009440 case CK_BaseToDerived:
9441 case CK_DerivedToBase:
9442 case CK_UncheckedDerivedToBase:
9443 case CK_Dynamic:
9444 case CK_ToUnion:
9445 case CK_ArrayToPointerDecay:
9446 case CK_FunctionToPointerDecay:
9447 case CK_NullToPointer:
9448 case CK_NullToMemberPointer:
9449 case CK_BaseToDerivedMemberPointer:
9450 case CK_DerivedToBaseMemberPointer:
9451 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009452 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009453 case CK_ConstructorConversion:
9454 case CK_IntegralToPointer:
9455 case CK_PointerToIntegral:
9456 case CK_PointerToBoolean:
9457 case CK_ToVoid:
9458 case CK_VectorSplat:
9459 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009460 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009461 case CK_IntegralToBoolean:
9462 case CK_IntegralToFloating:
9463 case CK_FloatingToIntegral:
9464 case CK_FloatingToBoolean:
9465 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009466 case CK_CPointerToObjCPointerCast:
9467 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009468 case CK_AnyPointerToBlockPointerCast:
9469 case CK_ObjCObjectLValueCast:
9470 case CK_FloatingComplexToReal:
9471 case CK_FloatingComplexToBoolean:
9472 case CK_IntegralComplexToReal:
9473 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009474 case CK_ARCProduceObject:
9475 case CK_ARCConsumeObject:
9476 case CK_ARCReclaimReturnedObject:
9477 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009478 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009479 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009480 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009481 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009482 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009483 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009484 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009485 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009486
John McCallfcef3cf2010-12-14 17:51:41 +00009487 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009488 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009489 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009490 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009491
9492 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009493 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009494 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009495 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009496
9497 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009498 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009499 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009500 return false;
9501
John McCallfcef3cf2010-12-14 17:51:41 +00009502 Result.makeComplexFloat();
9503 Result.FloatImag = APFloat(Real.getSemantics());
9504 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009505 }
9506
John McCallfcef3cf2010-12-14 17:51:41 +00009507 case CK_FloatingComplexCast: {
9508 if (!Visit(E->getSubExpr()))
9509 return false;
9510
9511 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9512 QualType From
9513 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9514
Richard Smith357362d2011-12-13 06:39:58 +00009515 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9516 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009517 }
9518
9519 case CK_FloatingComplexToIntegralComplex: {
9520 if (!Visit(E->getSubExpr()))
9521 return false;
9522
9523 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9524 QualType From
9525 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9526 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009527 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9528 To, Result.IntReal) &&
9529 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9530 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009531 }
9532
9533 case CK_IntegralRealToComplex: {
9534 APSInt &Real = Result.IntReal;
9535 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9536 return false;
9537
9538 Result.makeComplexInt();
9539 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9540 return true;
9541 }
9542
9543 case CK_IntegralComplexCast: {
9544 if (!Visit(E->getSubExpr()))
9545 return false;
9546
9547 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9548 QualType From
9549 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9550
Richard Smith911e1422012-01-30 22:27:01 +00009551 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9552 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009553 return true;
9554 }
9555
9556 case CK_IntegralComplexToFloatingComplex: {
9557 if (!Visit(E->getSubExpr()))
9558 return false;
9559
Ted Kremenek28831752012-08-23 20:46:57 +00009560 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009561 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009562 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009563 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009564 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9565 To, Result.FloatReal) &&
9566 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9567 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009568 }
9569 }
9570
9571 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009572}
9573
John McCall93d91dc2010-05-07 17:22:02 +00009574bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009575 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009576 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9577
Chandler Carrutha216cad2014-10-11 00:57:18 +00009578 // Track whether the LHS or RHS is real at the type system level. When this is
9579 // the case we can simplify our evaluation strategy.
9580 bool LHSReal = false, RHSReal = false;
9581
9582 bool LHSOK;
9583 if (E->getLHS()->getType()->isRealFloatingType()) {
9584 LHSReal = true;
9585 APFloat &Real = Result.FloatReal;
9586 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9587 if (LHSOK) {
9588 Result.makeComplexFloat();
9589 Result.FloatImag = APFloat(Real.getSemantics());
9590 }
9591 } else {
9592 LHSOK = Visit(E->getLHS());
9593 }
George Burgess IVa145e252016-05-25 22:38:36 +00009594 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009595 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009596
John McCall93d91dc2010-05-07 17:22:02 +00009597 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009598 if (E->getRHS()->getType()->isRealFloatingType()) {
9599 RHSReal = true;
9600 APFloat &Real = RHS.FloatReal;
9601 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9602 return false;
9603 RHS.makeComplexFloat();
9604 RHS.FloatImag = APFloat(Real.getSemantics());
9605 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009606 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009607
Chandler Carrutha216cad2014-10-11 00:57:18 +00009608 assert(!(LHSReal && RHSReal) &&
9609 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009610 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009611 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009612 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009613 if (Result.isComplexFloat()) {
9614 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9615 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009616 if (LHSReal)
9617 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9618 else if (!RHSReal)
9619 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9620 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009621 } else {
9622 Result.getComplexIntReal() += RHS.getComplexIntReal();
9623 Result.getComplexIntImag() += RHS.getComplexIntImag();
9624 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009625 break;
John McCalle3027922010-08-25 11:45:40 +00009626 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009627 if (Result.isComplexFloat()) {
9628 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9629 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009630 if (LHSReal) {
9631 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9632 Result.getComplexFloatImag().changeSign();
9633 } else if (!RHSReal) {
9634 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9635 APFloat::rmNearestTiesToEven);
9636 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009637 } else {
9638 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9639 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9640 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009641 break;
John McCalle3027922010-08-25 11:45:40 +00009642 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009643 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009644 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009645 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009646 // following naming scheme:
9647 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009648 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009649 APFloat &A = LHS.getComplexFloatReal();
9650 APFloat &B = LHS.getComplexFloatImag();
9651 APFloat &C = RHS.getComplexFloatReal();
9652 APFloat &D = RHS.getComplexFloatImag();
9653 APFloat &ResR = Result.getComplexFloatReal();
9654 APFloat &ResI = Result.getComplexFloatImag();
9655 if (LHSReal) {
9656 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9657 ResR = A * C;
9658 ResI = A * D;
9659 } else if (RHSReal) {
9660 ResR = C * A;
9661 ResI = C * B;
9662 } else {
9663 // In the fully general case, we need to handle NaNs and infinities
9664 // robustly.
9665 APFloat AC = A * C;
9666 APFloat BD = B * D;
9667 APFloat AD = A * D;
9668 APFloat BC = B * C;
9669 ResR = AC - BD;
9670 ResI = AD + BC;
9671 if (ResR.isNaN() && ResI.isNaN()) {
9672 bool Recalc = false;
9673 if (A.isInfinity() || B.isInfinity()) {
9674 A = APFloat::copySign(
9675 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9676 B = APFloat::copySign(
9677 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9678 if (C.isNaN())
9679 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9680 if (D.isNaN())
9681 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9682 Recalc = true;
9683 }
9684 if (C.isInfinity() || D.isInfinity()) {
9685 C = APFloat::copySign(
9686 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9687 D = APFloat::copySign(
9688 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9689 if (A.isNaN())
9690 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9691 if (B.isNaN())
9692 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9693 Recalc = true;
9694 }
9695 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9696 AD.isInfinity() || BC.isInfinity())) {
9697 if (A.isNaN())
9698 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9699 if (B.isNaN())
9700 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9701 if (C.isNaN())
9702 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9703 if (D.isNaN())
9704 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9705 Recalc = true;
9706 }
9707 if (Recalc) {
9708 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9709 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9710 }
9711 }
9712 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009713 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009714 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009715 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009716 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9717 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009718 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009719 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9720 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9721 }
9722 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009723 case BO_Div:
9724 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009725 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009726 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009727 // following naming scheme:
9728 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009729 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009730 APFloat &A = LHS.getComplexFloatReal();
9731 APFloat &B = LHS.getComplexFloatImag();
9732 APFloat &C = RHS.getComplexFloatReal();
9733 APFloat &D = RHS.getComplexFloatImag();
9734 APFloat &ResR = Result.getComplexFloatReal();
9735 APFloat &ResI = Result.getComplexFloatImag();
9736 if (RHSReal) {
9737 ResR = A / C;
9738 ResI = B / C;
9739 } else {
9740 if (LHSReal) {
9741 // No real optimizations we can do here, stub out with zero.
9742 B = APFloat::getZero(A.getSemantics());
9743 }
9744 int DenomLogB = 0;
9745 APFloat MaxCD = maxnum(abs(C), abs(D));
9746 if (MaxCD.isFinite()) {
9747 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009748 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9749 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009750 }
9751 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009752 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9753 APFloat::rmNearestTiesToEven);
9754 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9755 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009756 if (ResR.isNaN() && ResI.isNaN()) {
9757 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9758 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9759 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9760 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9761 D.isFinite()) {
9762 A = APFloat::copySign(
9763 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9764 B = APFloat::copySign(
9765 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9766 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9767 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9768 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9769 C = APFloat::copySign(
9770 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9771 D = APFloat::copySign(
9772 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9773 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9774 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9775 }
9776 }
9777 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009778 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009779 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9780 return Error(E, diag::note_expr_divide_by_zero);
9781
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009782 ComplexValue LHS = Result;
9783 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9784 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9785 Result.getComplexIntReal() =
9786 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9787 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9788 Result.getComplexIntImag() =
9789 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9790 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9791 }
9792 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009793 }
9794
John McCall93d91dc2010-05-07 17:22:02 +00009795 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009796}
9797
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009798bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9799 // Get the operand value into 'Result'.
9800 if (!Visit(E->getSubExpr()))
9801 return false;
9802
9803 switch (E->getOpcode()) {
9804 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009805 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009806 case UO_Extension:
9807 return true;
9808 case UO_Plus:
9809 // The result is always just the subexpr.
9810 return true;
9811 case UO_Minus:
9812 if (Result.isComplexFloat()) {
9813 Result.getComplexFloatReal().changeSign();
9814 Result.getComplexFloatImag().changeSign();
9815 }
9816 else {
9817 Result.getComplexIntReal() = -Result.getComplexIntReal();
9818 Result.getComplexIntImag() = -Result.getComplexIntImag();
9819 }
9820 return true;
9821 case UO_Not:
9822 if (Result.isComplexFloat())
9823 Result.getComplexFloatImag().changeSign();
9824 else
9825 Result.getComplexIntImag() = -Result.getComplexIntImag();
9826 return true;
9827 }
9828}
9829
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009830bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9831 if (E->getNumInits() == 2) {
9832 if (E->getType()->isComplexType()) {
9833 Result.makeComplexFloat();
9834 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9835 return false;
9836 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9837 return false;
9838 } else {
9839 Result.makeComplexInt();
9840 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9841 return false;
9842 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9843 return false;
9844 }
9845 return true;
9846 }
9847 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9848}
9849
Anders Carlsson537969c2008-11-16 20:27:53 +00009850//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009851// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9852// implicit conversion.
9853//===----------------------------------------------------------------------===//
9854
9855namespace {
9856class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009857 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009858 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009859 APValue &Result;
9860public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009861 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9862 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009863
9864 bool Success(const APValue &V, const Expr *E) {
9865 Result = V;
9866 return true;
9867 }
9868
9869 bool ZeroInitialization(const Expr *E) {
9870 ImplicitValueInitExpr VIE(
9871 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009872 // For atomic-qualified class (and array) types in C++, initialize the
9873 // _Atomic-wrapped subobject directly, in-place.
9874 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9875 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009876 }
9877
9878 bool VisitCastExpr(const CastExpr *E) {
9879 switch (E->getCastKind()) {
9880 default:
9881 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9882 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009883 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9884 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009885 }
9886 }
9887};
9888} // end anonymous namespace
9889
Richard Smith64cb9ca2017-02-22 22:09:50 +00009890static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9891 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009892 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009893 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009894}
9895
9896//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009897// Void expression evaluation, primarily for a cast to void on the LHS of a
9898// comma operator
9899//===----------------------------------------------------------------------===//
9900
9901namespace {
9902class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009903 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009904public:
9905 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9906
Richard Smith2e312c82012-03-03 22:46:17 +00009907 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009908
Richard Smith7cd577b2017-08-17 19:35:50 +00009909 bool ZeroInitialization(const Expr *E) { return true; }
9910
Richard Smith42d3af92011-12-07 00:43:50 +00009911 bool VisitCastExpr(const CastExpr *E) {
9912 switch (E->getCastKind()) {
9913 default:
9914 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9915 case CK_ToVoid:
9916 VisitIgnoredValue(E->getSubExpr());
9917 return true;
9918 }
9919 }
Hal Finkela8443c32014-07-17 14:49:58 +00009920
9921 bool VisitCallExpr(const CallExpr *E) {
9922 switch (E->getBuiltinCallee()) {
9923 default:
9924 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9925 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009926 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009927 // The argument is not evaluated!
9928 return true;
9929 }
9930 }
Richard Smith42d3af92011-12-07 00:43:50 +00009931};
9932} // end anonymous namespace
9933
9934static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9935 assert(E->isRValue() && E->getType()->isVoidType());
9936 return VoidExprEvaluator(Info).Visit(E);
9937}
9938
9939//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009940// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009941//===----------------------------------------------------------------------===//
9942
Richard Smith2e312c82012-03-03 22:46:17 +00009943static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009944 // In C, function designators are not lvalues, but we evaluate them as if they
9945 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009946 QualType T = E->getType();
9947 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009948 LValue LV;
9949 if (!EvaluateLValue(E, LV, Info))
9950 return false;
9951 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009952 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009953 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009954 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009955 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009956 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009957 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009958 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009959 LValue LV;
9960 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009961 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009962 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009963 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009964 llvm::APFloat F(0.0);
9965 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009966 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009967 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009968 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009969 ComplexValue C;
9970 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009971 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009972 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009973 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009974 MemberPtr P;
9975 if (!EvaluateMemberPointer(E, P, Info))
9976 return false;
9977 P.moveInto(Result);
9978 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009979 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009980 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009981 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009982 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9983 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009984 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009985 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009986 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009987 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009988 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009989 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9990 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009991 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009992 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009993 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009994 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009995 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009996 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009997 if (!EvaluateVoid(E, Info))
9998 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009999 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010000 QualType Unqual = T.getAtomicUnqualifiedType();
10001 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10002 LValue LV;
10003 LV.set(E, Info.CurrentCall->Index);
10004 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10005 if (!EvaluateAtomic(E, &LV, Value, Info))
10006 return false;
10007 } else {
10008 if (!EvaluateAtomic(E, nullptr, Result, Info))
10009 return false;
10010 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010011 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010012 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010013 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010014 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010015 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010016 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010017 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010018
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010019 return true;
10020}
10021
Richard Smithb228a862012-02-15 02:18:13 +000010022/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10023/// cases, the in-place evaluation is essential, since later initializers for
10024/// an object can indirectly refer to subobjects which were initialized earlier.
10025static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010026 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010027 assert(!E->isValueDependent());
10028
Richard Smith7525ff62013-05-09 07:14:00 +000010029 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010030 return false;
10031
10032 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010033 // Evaluate arrays and record types in-place, so that later initializers can
10034 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010035 QualType T = E->getType();
10036 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010037 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010038 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010039 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010040 else if (T->isAtomicType()) {
10041 QualType Unqual = T.getAtomicUnqualifiedType();
10042 if (Unqual->isArrayType() || Unqual->isRecordType())
10043 return EvaluateAtomic(E, &This, Result, Info);
10044 }
Richard Smithed5165f2011-11-04 05:33:44 +000010045 }
10046
10047 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010048 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010049}
10050
Richard Smithf57d8cb2011-12-09 22:58:01 +000010051/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10052/// lvalue-to-rvalue cast if it is an lvalue.
10053static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010054 if (E->getType().isNull())
10055 return false;
10056
Nick Lewyckyc190f962017-05-02 01:06:16 +000010057 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010058 return false;
10059
Richard Smith2e312c82012-03-03 22:46:17 +000010060 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010061 return false;
10062
10063 if (E->isGLValue()) {
10064 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010065 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010066 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010067 return false;
10068 }
10069
Richard Smith2e312c82012-03-03 22:46:17 +000010070 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010071 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010072}
Richard Smith11562c52011-10-28 17:51:58 +000010073
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010074static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010075 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010076 // Fast-path evaluations of integer literals, since we sometimes see files
10077 // containing vast quantities of these.
10078 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10079 Result.Val = APValue(APSInt(L->getValue(),
10080 L->getType()->isUnsignedIntegerType()));
10081 IsConst = true;
10082 return true;
10083 }
James Dennett0492ef02014-03-14 17:44:10 +000010084
10085 // This case should be rare, but we need to check it before we check on
10086 // the type below.
10087 if (Exp->getType().isNull()) {
10088 IsConst = false;
10089 return true;
10090 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010091
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010092 // FIXME: Evaluating values of large array and record types can cause
10093 // performance problems. Only do so in C++11 for now.
10094 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10095 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010096 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010097 IsConst = false;
10098 return true;
10099 }
10100 return false;
10101}
10102
10103
Richard Smith7b553f12011-10-29 00:50:52 +000010104/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010105/// any crazy technique (that has nothing to do with language standards) that
10106/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010107/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10108/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010109bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010110 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010111 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010112 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010113
Richard Smith6d4c6582013-11-05 22:18:15 +000010114 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010115 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010116}
10117
Jay Foad39c79802011-01-12 09:06:06 +000010118bool Expr::EvaluateAsBooleanCondition(bool &Result,
10119 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010120 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010121 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010122 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010123}
10124
Richard Smithce8eca52015-12-08 03:21:47 +000010125static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10126 Expr::SideEffectsKind SEK) {
10127 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10128 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10129}
10130
Richard Smith5fab0c92011-12-28 19:48:30 +000010131bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10132 SideEffectsKind AllowSideEffects) const {
10133 if (!getType()->isIntegralOrEnumerationType())
10134 return false;
10135
Richard Smith11562c52011-10-28 17:51:58 +000010136 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010137 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010138 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010139 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010140
Richard Smith11562c52011-10-28 17:51:58 +000010141 Result = ExprResult.Val.getInt();
10142 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010143}
10144
Richard Trieube234c32016-04-21 21:04:55 +000010145bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10146 SideEffectsKind AllowSideEffects) const {
10147 if (!getType()->isRealFloatingType())
10148 return false;
10149
10150 EvalResult ExprResult;
10151 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10152 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10153 return false;
10154
10155 Result = ExprResult.Val.getFloat();
10156 return true;
10157}
10158
Jay Foad39c79802011-01-12 09:06:06 +000010159bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010160 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010161
John McCall45d55e42010-05-07 21:00:08 +000010162 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010163 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10164 !CheckLValueConstantExpression(Info, getExprLoc(),
10165 Ctx.getLValueReferenceType(getType()), LV))
10166 return false;
10167
Richard Smith2e312c82012-03-03 22:46:17 +000010168 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010169 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010170}
10171
Richard Smithd0b4dd62011-12-19 06:19:21 +000010172bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10173 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010174 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010175 // FIXME: Evaluating initializers for large array and record types can cause
10176 // performance problems. Only do so in C++11 for now.
10177 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010178 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010179 return false;
10180
Richard Smithd0b4dd62011-12-19 06:19:21 +000010181 Expr::EvalStatus EStatus;
10182 EStatus.Diag = &Notes;
10183
Richard Smith0c6124b2015-12-03 01:36:22 +000010184 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10185 ? EvalInfo::EM_ConstantExpression
10186 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010187 InitInfo.setEvaluatingDecl(VD, Value);
10188
10189 LValue LVal;
10190 LVal.set(VD);
10191
Richard Smithfddd3842011-12-30 21:15:51 +000010192 // C++11 [basic.start.init]p2:
10193 // Variables with static storage duration or thread storage duration shall be
10194 // zero-initialized before any other initialization takes place.
10195 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010196 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010197 !VD->getType()->isReferenceType()) {
10198 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010199 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010200 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010201 return false;
10202 }
10203
Richard Smith7525ff62013-05-09 07:14:00 +000010204 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10205 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010206 EStatus.HasSideEffects)
10207 return false;
10208
10209 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10210 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010211}
10212
Richard Smith7b553f12011-10-29 00:50:52 +000010213/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10214/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010215bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010216 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010217 return EvaluateAsRValue(Result, Ctx) &&
10218 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010219}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010220
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010221APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010222 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010223 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010224 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010225 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010226 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010227 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010228 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010229
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010230 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010231}
John McCall864e3962010-05-07 05:32:02 +000010232
Richard Smithe9ff7702013-11-05 22:23:30 +000010233void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010234 bool IsConst;
10235 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010236 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010237 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010238 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10239 }
10240}
10241
Richard Smithe6c01442013-06-05 00:46:14 +000010242bool Expr::EvalResult::isGlobalLValue() const {
10243 assert(Val.isLValue());
10244 return IsGlobalLValue(Val.getLValueBase());
10245}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010246
10247
John McCall864e3962010-05-07 05:32:02 +000010248/// isIntegerConstantExpr - this recursive routine will test if an expression is
10249/// an integer constant expression.
10250
10251/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10252/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010253
10254// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010255// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10256// and a (possibly null) SourceLocation indicating the location of the problem.
10257//
John McCall864e3962010-05-07 05:32:02 +000010258// Note that to reduce code duplication, this helper does no evaluation
10259// itself; the caller checks whether the expression is evaluatable, and
10260// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010261// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010262
Dan Gohman28ade552010-07-26 21:25:24 +000010263namespace {
10264
Richard Smith9e575da2012-12-28 13:25:52 +000010265enum ICEKind {
10266 /// This expression is an ICE.
10267 IK_ICE,
10268 /// This expression is not an ICE, but if it isn't evaluated, it's
10269 /// a legal subexpression for an ICE. This return value is used to handle
10270 /// the comma operator in C99 mode, and non-constant subexpressions.
10271 IK_ICEIfUnevaluated,
10272 /// This expression is not an ICE, and is not a legal subexpression for one.
10273 IK_NotICE
10274};
10275
John McCall864e3962010-05-07 05:32:02 +000010276struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010277 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010278 SourceLocation Loc;
10279
Richard Smith9e575da2012-12-28 13:25:52 +000010280 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010281};
10282
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010283}
Dan Gohman28ade552010-07-26 21:25:24 +000010284
Richard Smith9e575da2012-12-28 13:25:52 +000010285static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10286
10287static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010288
Craig Toppera31a8822013-08-22 07:09:37 +000010289static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010290 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010291 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010292 !EVResult.Val.isInt())
10293 return ICEDiag(IK_NotICE, E->getLocStart());
10294
John McCall864e3962010-05-07 05:32:02 +000010295 return NoDiag();
10296}
10297
Craig Toppera31a8822013-08-22 07:09:37 +000010298static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010299 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010300 if (!E->getType()->isIntegralOrEnumerationType())
10301 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010302
10303 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010304#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010305#define STMT(Node, Base) case Expr::Node##Class:
10306#define EXPR(Node, Base)
10307#include "clang/AST/StmtNodes.inc"
10308 case Expr::PredefinedExprClass:
10309 case Expr::FloatingLiteralClass:
10310 case Expr::ImaginaryLiteralClass:
10311 case Expr::StringLiteralClass:
10312 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010313 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010314 case Expr::MemberExprClass:
10315 case Expr::CompoundAssignOperatorClass:
10316 case Expr::CompoundLiteralExprClass:
10317 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010318 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010319 case Expr::ArrayInitLoopExprClass:
10320 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010321 case Expr::NoInitExprClass:
10322 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010323 case Expr::ImplicitValueInitExprClass:
10324 case Expr::ParenListExprClass:
10325 case Expr::VAArgExprClass:
10326 case Expr::AddrLabelExprClass:
10327 case Expr::StmtExprClass:
10328 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010329 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010330 case Expr::CXXDynamicCastExprClass:
10331 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010332 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010333 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010334 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010335 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010336 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010337 case Expr::CXXThisExprClass:
10338 case Expr::CXXThrowExprClass:
10339 case Expr::CXXNewExprClass:
10340 case Expr::CXXDeleteExprClass:
10341 case Expr::CXXPseudoDestructorExprClass:
10342 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010343 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010344 case Expr::DependentScopeDeclRefExprClass:
10345 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010346 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010347 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010348 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010349 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010350 case Expr::CXXTemporaryObjectExprClass:
10351 case Expr::CXXUnresolvedConstructExprClass:
10352 case Expr::CXXDependentScopeMemberExprClass:
10353 case Expr::UnresolvedMemberExprClass:
10354 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010355 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010356 case Expr::ObjCArrayLiteralClass:
10357 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010358 case Expr::ObjCEncodeExprClass:
10359 case Expr::ObjCMessageExprClass:
10360 case Expr::ObjCSelectorExprClass:
10361 case Expr::ObjCProtocolExprClass:
10362 case Expr::ObjCIvarRefExprClass:
10363 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010364 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010365 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010366 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010367 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010368 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010369 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010370 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010371 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010372 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010373 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010374 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010375 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010376 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010377 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010378 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010379 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010380 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010381 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010382 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010383 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010384 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010385 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010386
Richard Smithf137f932014-01-25 20:50:08 +000010387 case Expr::InitListExprClass: {
10388 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10389 // form "T x = { a };" is equivalent to "T x = a;".
10390 // Unless we're initializing a reference, T is a scalar as it is known to be
10391 // of integral or enumeration type.
10392 if (E->isRValue())
10393 if (cast<InitListExpr>(E)->getNumInits() == 1)
10394 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10395 return ICEDiag(IK_NotICE, E->getLocStart());
10396 }
10397
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010398 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010399 case Expr::GNUNullExprClass:
10400 // GCC considers the GNU __null value to be an integral constant expression.
10401 return NoDiag();
10402
John McCall7c454bb2011-07-15 05:09:51 +000010403 case Expr::SubstNonTypeTemplateParmExprClass:
10404 return
10405 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10406
John McCall864e3962010-05-07 05:32:02 +000010407 case Expr::ParenExprClass:
10408 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010409 case Expr::GenericSelectionExprClass:
10410 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010411 case Expr::IntegerLiteralClass:
10412 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010413 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010414 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010415 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010416 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010417 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010418 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010419 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010420 return NoDiag();
10421 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010422 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010423 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10424 // constant expressions, but they can never be ICEs because an ICE cannot
10425 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010426 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010427 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010428 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010429 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010430 }
Richard Smith6365c912012-02-24 22:12:32 +000010431 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010432 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10433 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010434 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010435 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010436 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010437 // Parameter variables are never constants. Without this check,
10438 // getAnyInitializer() can find a default argument, which leads
10439 // to chaos.
10440 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010441 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010442
10443 // C++ 7.1.5.1p2
10444 // A variable of non-volatile const-qualified integral or enumeration
10445 // type initialized by an ICE can be used in ICEs.
10446 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010447 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010448 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010449
Richard Smithd0b4dd62011-12-19 06:19:21 +000010450 const VarDecl *VD;
10451 // Look for a declaration of this variable that has an initializer, and
10452 // check whether it is an ICE.
10453 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10454 return NoDiag();
10455 else
Richard Smith9e575da2012-12-28 13:25:52 +000010456 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010457 }
10458 }
Richard Smith9e575da2012-12-28 13:25:52 +000010459 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010460 }
John McCall864e3962010-05-07 05:32:02 +000010461 case Expr::UnaryOperatorClass: {
10462 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10463 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010464 case UO_PostInc:
10465 case UO_PostDec:
10466 case UO_PreInc:
10467 case UO_PreDec:
10468 case UO_AddrOf:
10469 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010470 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010471 // C99 6.6/3 allows increment and decrement within unevaluated
10472 // subexpressions of constant expressions, but they can never be ICEs
10473 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010474 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010475 case UO_Extension:
10476 case UO_LNot:
10477 case UO_Plus:
10478 case UO_Minus:
10479 case UO_Not:
10480 case UO_Real:
10481 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010482 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010483 }
Richard Smith9e575da2012-12-28 13:25:52 +000010484
John McCall864e3962010-05-07 05:32:02 +000010485 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010486 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010487 }
10488 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010489 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10490 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10491 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10492 // compliance: we should warn earlier for offsetof expressions with
10493 // array subscripts that aren't ICEs, and if the array subscripts
10494 // are ICEs, the value of the offsetof must be an integer constant.
10495 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010496 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010497 case Expr::UnaryExprOrTypeTraitExprClass: {
10498 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10499 if ((Exp->getKind() == UETT_SizeOf) &&
10500 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010501 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010502 return NoDiag();
10503 }
10504 case Expr::BinaryOperatorClass: {
10505 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10506 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010507 case BO_PtrMemD:
10508 case BO_PtrMemI:
10509 case BO_Assign:
10510 case BO_MulAssign:
10511 case BO_DivAssign:
10512 case BO_RemAssign:
10513 case BO_AddAssign:
10514 case BO_SubAssign:
10515 case BO_ShlAssign:
10516 case BO_ShrAssign:
10517 case BO_AndAssign:
10518 case BO_XorAssign:
10519 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010520 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010521 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10522 // constant expressions, but they can never be ICEs because an ICE cannot
10523 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010524 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010525
John McCalle3027922010-08-25 11:45:40 +000010526 case BO_Mul:
10527 case BO_Div:
10528 case BO_Rem:
10529 case BO_Add:
10530 case BO_Sub:
10531 case BO_Shl:
10532 case BO_Shr:
10533 case BO_LT:
10534 case BO_GT:
10535 case BO_LE:
10536 case BO_GE:
10537 case BO_EQ:
10538 case BO_NE:
10539 case BO_And:
10540 case BO_Xor:
10541 case BO_Or:
10542 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010543 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10544 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010545 if (Exp->getOpcode() == BO_Div ||
10546 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010547 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010548 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010549 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010550 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010551 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010552 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010553 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010554 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010555 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010556 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010557 }
10558 }
10559 }
John McCalle3027922010-08-25 11:45:40 +000010560 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010561 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010562 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10563 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010564 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10565 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010566 } else {
10567 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010568 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010569 }
10570 }
Richard Smith9e575da2012-12-28 13:25:52 +000010571 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010572 }
John McCalle3027922010-08-25 11:45:40 +000010573 case BO_LAnd:
10574 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010575 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10576 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010577 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010578 // Rare case where the RHS has a comma "side-effect"; we need
10579 // to actually check the condition to see whether the side
10580 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010581 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010582 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010583 return RHSResult;
10584 return NoDiag();
10585 }
10586
Richard Smith9e575da2012-12-28 13:25:52 +000010587 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010588 }
10589 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010590 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010591 }
10592 case Expr::ImplicitCastExprClass:
10593 case Expr::CStyleCastExprClass:
10594 case Expr::CXXFunctionalCastExprClass:
10595 case Expr::CXXStaticCastExprClass:
10596 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010597 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010598 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010599 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010600 if (isa<ExplicitCastExpr>(E)) {
10601 if (const FloatingLiteral *FL
10602 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10603 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10604 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10605 APSInt IgnoredVal(DestWidth, !DestSigned);
10606 bool Ignored;
10607 // If the value does not fit in the destination type, the behavior is
10608 // undefined, so we are not required to treat it as a constant
10609 // expression.
10610 if (FL->getValue().convertToInteger(IgnoredVal,
10611 llvm::APFloat::rmTowardZero,
10612 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010613 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010614 return NoDiag();
10615 }
10616 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010617 switch (cast<CastExpr>(E)->getCastKind()) {
10618 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010619 case CK_AtomicToNonAtomic:
10620 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010621 case CK_NoOp:
10622 case CK_IntegralToBoolean:
10623 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010624 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010625 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010626 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010627 }
John McCall864e3962010-05-07 05:32:02 +000010628 }
John McCallc07a0c72011-02-17 10:25:35 +000010629 case Expr::BinaryConditionalOperatorClass: {
10630 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10631 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010632 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010633 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010634 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10635 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10636 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010637 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010638 return FalseResult;
10639 }
John McCall864e3962010-05-07 05:32:02 +000010640 case Expr::ConditionalOperatorClass: {
10641 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10642 // If the condition (ignoring parens) is a __builtin_constant_p call,
10643 // then only the true side is actually considered in an integer constant
10644 // expression, and it is fully evaluated. This is an important GNU
10645 // extension. See GCC PR38377 for discussion.
10646 if (const CallExpr *CallCE
10647 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010648 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010649 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010650 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010651 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010652 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010653
Richard Smithf57d8cb2011-12-09 22:58:01 +000010654 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10655 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010656
Richard Smith9e575da2012-12-28 13:25:52 +000010657 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010658 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010659 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010660 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010661 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010662 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010663 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010664 return NoDiag();
10665 // Rare case where the diagnostics depend on which side is evaluated
10666 // Note that if we get here, CondResult is 0, and at least one of
10667 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010668 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010669 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010670 return TrueResult;
10671 }
10672 case Expr::CXXDefaultArgExprClass:
10673 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010674 case Expr::CXXDefaultInitExprClass:
10675 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010676 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010677 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010678 }
10679 }
10680
David Blaikiee4d798f2012-01-20 21:50:17 +000010681 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010682}
10683
Richard Smithf57d8cb2011-12-09 22:58:01 +000010684/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010685static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010686 const Expr *E,
10687 llvm::APSInt *Value,
10688 SourceLocation *Loc) {
10689 if (!E->getType()->isIntegralOrEnumerationType()) {
10690 if (Loc) *Loc = E->getExprLoc();
10691 return false;
10692 }
10693
Richard Smith66e05fe2012-01-18 05:21:49 +000010694 APValue Result;
10695 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010696 return false;
10697
Richard Smith98710fc2014-11-13 23:03:19 +000010698 if (!Result.isInt()) {
10699 if (Loc) *Loc = E->getExprLoc();
10700 return false;
10701 }
10702
Richard Smith66e05fe2012-01-18 05:21:49 +000010703 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010704 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010705}
10706
Craig Toppera31a8822013-08-22 07:09:37 +000010707bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10708 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010709 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010710 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010711
Richard Smith9e575da2012-12-28 13:25:52 +000010712 ICEDiag D = CheckICE(this, Ctx);
10713 if (D.Kind != IK_ICE) {
10714 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010715 return false;
10716 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010717 return true;
10718}
10719
Craig Toppera31a8822013-08-22 07:09:37 +000010720bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010721 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010722 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010723 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10724
10725 if (!isIntegerConstantExpr(Ctx, Loc))
10726 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010727 // The only possible side-effects here are due to UB discovered in the
10728 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10729 // required to treat the expression as an ICE, so we produce the folded
10730 // value.
10731 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010732 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010733 return true;
10734}
Richard Smith66e05fe2012-01-18 05:21:49 +000010735
Craig Toppera31a8822013-08-22 07:09:37 +000010736bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010737 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010738}
10739
Craig Toppera31a8822013-08-22 07:09:37 +000010740bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010741 SourceLocation *Loc) const {
10742 // We support this checking in C++98 mode in order to diagnose compatibility
10743 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010744 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010745
Richard Smith98a0a492012-02-14 21:38:30 +000010746 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010747 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010748 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010749 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010750 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010751
10752 APValue Scratch;
10753 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10754
10755 if (!Diags.empty()) {
10756 IsConstExpr = false;
10757 if (Loc) *Loc = Diags[0].first;
10758 } else if (!IsConstExpr) {
10759 // FIXME: This shouldn't happen.
10760 if (Loc) *Loc = getExprLoc();
10761 }
10762
10763 return IsConstExpr;
10764}
Richard Smith253c2a32012-01-27 01:14:48 +000010765
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010766bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10767 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010768 ArrayRef<const Expr*> Args,
10769 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010770 Expr::EvalStatus Status;
10771 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10772
George Burgess IV177399e2017-01-09 04:12:14 +000010773 LValue ThisVal;
10774 const LValue *ThisPtr = nullptr;
10775 if (This) {
10776#ifndef NDEBUG
10777 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10778 assert(MD && "Don't provide `this` for non-methods.");
10779 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10780#endif
10781 if (EvaluateObjectArgument(Info, This, ThisVal))
10782 ThisPtr = &ThisVal;
10783 if (Info.EvalStatus.HasSideEffects)
10784 return false;
10785 }
10786
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010787 ArgVector ArgValues(Args.size());
10788 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10789 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010790 if ((*I)->isValueDependent() ||
10791 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010792 // If evaluation fails, throw away the argument entirely.
10793 ArgValues[I - Args.begin()] = APValue();
10794 if (Info.EvalStatus.HasSideEffects)
10795 return false;
10796 }
10797
10798 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010799 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010800 ArgValues.data());
10801 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10802}
10803
Richard Smith253c2a32012-01-27 01:14:48 +000010804bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010805 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010806 PartialDiagnosticAt> &Diags) {
10807 // FIXME: It would be useful to check constexpr function templates, but at the
10808 // moment the constant expression evaluator cannot cope with the non-rigorous
10809 // ASTs which we build for dependent expressions.
10810 if (FD->isDependentContext())
10811 return true;
10812
10813 Expr::EvalStatus Status;
10814 Status.Diag = &Diags;
10815
Richard Smith6d4c6582013-11-05 22:18:15 +000010816 EvalInfo Info(FD->getASTContext(), Status,
10817 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010818
10819 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010820 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010821
Richard Smith7525ff62013-05-09 07:14:00 +000010822 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010823 // is a temporary being used as the 'this' pointer.
10824 LValue This;
10825 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010826 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010827
Richard Smith253c2a32012-01-27 01:14:48 +000010828 ArrayRef<const Expr*> Args;
10829
Richard Smith2e312c82012-03-03 22:46:17 +000010830 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010831 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10832 // Evaluate the call as a constant initializer, to allow the construction
10833 // of objects of non-literal types.
10834 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010835 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10836 } else {
10837 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010838 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010839 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010840 }
Richard Smith253c2a32012-01-27 01:14:48 +000010841
10842 return Diags.empty();
10843}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010844
10845bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10846 const FunctionDecl *FD,
10847 SmallVectorImpl<
10848 PartialDiagnosticAt> &Diags) {
10849 Expr::EvalStatus Status;
10850 Status.Diag = &Diags;
10851
10852 EvalInfo Info(FD->getASTContext(), Status,
10853 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10854
10855 // Fabricate a call stack frame to give the arguments a plausible cover story.
10856 ArrayRef<const Expr*> Args;
10857 ArgVector ArgValues(0);
10858 bool Success = EvaluateArgs(Args, ArgValues, Info);
10859 (void)Success;
10860 assert(Success &&
10861 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010862 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010863
10864 APValue ResultScratch;
10865 Evaluate(ResultScratch, Info, E);
10866 return Diags.empty();
10867}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010868
10869bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10870 unsigned Type) const {
10871 if (!getType()->isPointerType())
10872 return false;
10873
10874 Expr::EvalStatus Status;
10875 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010876 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010877}