blob: 0abdaa879ec25398bd1200a43a87fc52907428e3 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
Richard Smitha8105bc2012-01-06 16:39:00 +0000125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000160 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000163 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000166 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
206 MostDerivedType, IsArray);
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// Callee - The function which was called.
314 const FunctionDecl *Callee;
315
Richard Smithd62306a2011-11-10 06:34:14 +0000316 /// This - The binding for the this pointer in this call, if any.
317 const LValue *This;
318
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000319 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000320 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000321 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000322
Eli Friedman4830ec82012-06-25 21:21:08 +0000323 // Note that we intentionally use std::map here so that references to
324 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000325 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000326 typedef MapTy::const_iterator temp_iterator;
327 /// Temporaries - Temporary lvalues materialized within this stack frame.
328 MapTy Temporaries;
329
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000330 /// CallLoc - The location of the call expression for this call.
331 SourceLocation CallLoc;
332
333 /// Index - The call index of this call.
334 unsigned Index;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000436 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith410306b2016-12-12 02:53:20 +0000472 /// The current array initialization index, if we're performing array
473 /// initialization.
474 uint64_t ArrayInitIndex = -1;
475
Richard Smith357362d2011-12-13 06:39:58 +0000476 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
477 /// notes attached to it will also be stored, otherwise they will not be.
478 bool HasActiveDiagnostic;
479
Richard Smith0c6124b2015-12-03 01:36:22 +0000480 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
481 /// fold (not just why it's not strictly a constant expression)?
482 bool HasFoldFailureDiagnostic;
483
George Burgess IV8c892b52016-05-25 22:31:54 +0000484 /// \brief Whether or not we're currently speculatively evaluating.
485 bool IsSpeculativelyEvaluating;
486
Richard Smith6d4c6582013-11-05 22:18:15 +0000487 enum EvaluationMode {
488 /// Evaluate as a constant expression. Stop if we find that the expression
489 /// is not a constant expression.
490 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000491
Richard Smith6d4c6582013-11-05 22:18:15 +0000492 /// Evaluate as a potential constant expression. Keep going if we hit a
493 /// construct that we can't evaluate yet (because we don't yet know the
494 /// value of something) but stop if we hit something that could never be
495 /// a constant expression.
496 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000497
Richard Smith6d4c6582013-11-05 22:18:15 +0000498 /// Fold the expression to a constant. Stop if we hit a side-effect that
499 /// we can't model.
500 EM_ConstantFold,
501
502 /// Evaluate the expression looking for integer overflow and similar
503 /// issues. Don't worry about side-effects, and try to visit all
504 /// subexpressions.
505 EM_EvaluateForOverflow,
506
507 /// Evaluate in any way we know how. Don't worry about side-effects that
508 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000509 EM_IgnoreSideEffects,
510
511 /// Evaluate as a constant expression. Stop if we find that the expression
512 /// is not a constant expression. Some expressions can be retried in the
513 /// optimizer if we don't constant fold them here, but in an unevaluated
514 /// context we try to fold them immediately since the optimizer never
515 /// gets a chance to look at it.
516 EM_ConstantExpressionUnevaluated,
517
518 /// Evaluate as a potential constant expression. Keep going if we hit a
519 /// construct that we can't evaluate yet (because we don't yet know the
520 /// value of something) but stop if we hit something that could never be
521 /// a constant expression. Some expressions can be retried in the
522 /// optimizer if we don't constant fold them here, but in an unevaluated
523 /// context we try to fold them immediately since the optimizer never
524 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000525 EM_PotentialConstantExpressionUnevaluated,
526
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000527 /// Evaluate as a constant expression. Continue evaluating if we find a
528 /// MemberExpr with a base that can't be evaluated.
529 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000530 } EvalMode;
531
532 /// Are we checking whether the expression is a potential constant
533 /// expression?
534 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000535 return EvalMode == EM_PotentialConstantExpression ||
536 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000537 }
538
539 /// Are we checking an expression for overflow?
540 // FIXME: We should check for any kind of undefined or suspicious behavior
541 // in such constructs, not just overflow.
542 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
543
544 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000545 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000546 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000547 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000548 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
549 EvaluatingDecl((const ValueDecl *)nullptr),
550 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000551 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
552 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000553
Richard Smith7525ff62013-05-09 07:14:00 +0000554 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
555 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000556 EvaluatingDeclValue = &Value;
557 }
558
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000560
Richard Smith357362d2011-12-13 06:39:58 +0000561 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000562 // Don't perform any constexpr calls (other than the call we're checking)
563 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000564 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000565 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000566 if (NextCallIndex == 0) {
567 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000568 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000569 return false;
570 }
Richard Smith357362d2011-12-13 06:39:58 +0000571 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
572 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000573 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000574 << getLangOpts().ConstexprCallDepth;
575 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000576 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000577
Richard Smithb228a862012-02-15 02:18:13 +0000578 CallStackFrame *getCallFrame(unsigned CallIndex) {
579 assert(CallIndex && "no call index in getCallFrame");
580 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
581 // be null in this loop.
582 CallStackFrame *Frame = CurrentCall;
583 while (Frame->Index > CallIndex)
584 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000585 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000586 }
587
Richard Smitha3d3bd22013-05-08 02:12:03 +0000588 bool nextStep(const Stmt *S) {
589 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000590 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000591 return false;
592 }
593 --StepsLeft;
594 return true;
595 }
596
Richard Smith357362d2011-12-13 06:39:58 +0000597 private:
598 /// Add a diagnostic to the diagnostics list.
599 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
600 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
601 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
602 return EvalStatus.Diag->back().second;
603 }
604
Richard Smithf6f003a2011-12-16 19:06:07 +0000605 /// Add notes containing a call stack to the current point of evaluation.
606 void addCallStack(unsigned Limit);
607
Faisal Valie690b7a2016-07-02 22:34:24 +0000608 private:
609 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
610 unsigned ExtraNotes, bool IsCCEDiag) {
611
Richard Smith92b1ce02011-12-12 09:28:41 +0000612 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000613 // If we have a prior diagnostic, it will be noting that the expression
614 // isn't a constant expression. This diagnostic is more important,
615 // unless we require this evaluation to produce a constant expression.
616 //
617 // FIXME: We might want to show both diagnostics to the user in
618 // EM_ConstantFold mode.
619 if (!EvalStatus.Diag->empty()) {
620 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000621 case EM_ConstantFold:
622 case EM_IgnoreSideEffects:
623 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000625 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000626 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 case EM_ConstantExpression:
628 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000629 case EM_ConstantExpressionUnevaluated:
630 case EM_PotentialConstantExpressionUnevaluated:
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000631 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 HasActiveDiagnostic = false;
633 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000634 }
635 }
636
Richard Smithf6f003a2011-12-16 19:06:07 +0000637 unsigned CallStackNotes = CallStackDepth - 1;
638 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
639 if (Limit)
640 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000642 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000643
Richard Smith357362d2011-12-13 06:39:58 +0000644 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000645 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000647 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
648 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000650 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 }
Richard Smith357362d2011-12-13 06:39:58 +0000653 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000654 return OptionalDiagnostic();
655 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000656 public:
657 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
658 OptionalDiagnostic
659 FFDiag(SourceLocation Loc,
660 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
661 unsigned ExtraNotes = 0) {
662 return Diag(Loc, DiagId, ExtraNotes, false);
663 }
664
665 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000666 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000667 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000668 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000669 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000670 HasActiveDiagnostic = false;
671 return OptionalDiagnostic();
672 }
673
Richard Smith92b1ce02011-12-12 09:28:41 +0000674 /// Diagnose that the evaluation does not produce a C++11 core constant
675 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 ///
677 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
678 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000679 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000680 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000681 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000682 // Don't override a previous diagnostic. Don't bother collecting
683 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000684 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000685 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000686 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000687 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000688 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000689 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000690 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
691 = diag::note_invalid_subexpr_in_const_expr,
692 unsigned ExtraNotes = 0) {
693 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
694 }
Richard Smith357362d2011-12-13 06:39:58 +0000695 /// Add a note to a prior diagnostic.
696 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
697 if (!HasActiveDiagnostic)
698 return OptionalDiagnostic();
699 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000700 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000701
702 /// Add a stack of notes to a prior diagnostic.
703 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
704 if (HasActiveDiagnostic) {
705 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
706 Diags.begin(), Diags.end());
707 }
708 }
Richard Smith253c2a32012-01-27 01:14:48 +0000709
Richard Smith6d4c6582013-11-05 22:18:15 +0000710 /// Should we continue evaluation after encountering a side-effect that we
711 /// couldn't model?
712 bool keepEvaluatingAfterSideEffect() {
713 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000714 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000715 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000716 case EM_EvaluateForOverflow:
717 case EM_IgnoreSideEffects:
718 return true;
719
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000721 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000722 case EM_ConstantFold:
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000723 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 return false;
725 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000726 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 }
728
729 /// Note that we have had a side-effect, and determine whether we should
730 /// keep evaluating.
731 bool noteSideEffect() {
732 EvalStatus.HasSideEffects = true;
733 return keepEvaluatingAfterSideEffect();
734 }
735
Richard Smithce8eca52015-12-08 03:21:47 +0000736 /// Should we continue evaluation after encountering undefined behavior?
737 bool keepEvaluatingAfterUndefinedBehavior() {
738 switch (EvalMode) {
739 case EM_EvaluateForOverflow:
740 case EM_IgnoreSideEffects:
741 case EM_ConstantFold:
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000742 case EM_DesignatorFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000743 return true;
744
745 case EM_PotentialConstantExpression:
746 case EM_PotentialConstantExpressionUnevaluated:
747 case EM_ConstantExpression:
748 case EM_ConstantExpressionUnevaluated:
749 return false;
750 }
751 llvm_unreachable("Missed EvalMode case");
752 }
753
754 /// Note that we hit something that was technically undefined behavior, but
755 /// that we can evaluate past it (such as signed overflow or floating-point
756 /// division by zero.)
757 bool noteUndefinedBehavior() {
758 EvalStatus.HasUndefinedBehavior = true;
759 return keepEvaluatingAfterUndefinedBehavior();
760 }
761
Richard Smith253c2a32012-01-27 01:14:48 +0000762 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000764 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000765 if (!StepsLeft)
766 return false;
767
768 switch (EvalMode) {
769 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000770 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 case EM_EvaluateForOverflow:
772 return true;
773
774 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000775 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 case EM_ConstantFold:
777 case EM_IgnoreSideEffects:
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000778 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000779 return false;
780 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000781 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000782 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000783
George Burgess IV8c892b52016-05-25 22:31:54 +0000784 /// Notes that we failed to evaluate an expression that other expressions
785 /// directly depend on, and determine if we should keep evaluating. This
786 /// should only be called if we actually intend to keep evaluating.
787 ///
788 /// Call noteSideEffect() instead if we may be able to ignore the value that
789 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
790 ///
791 /// (Foo(), 1) // use noteSideEffect
792 /// (Foo() || true) // use noteSideEffect
793 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000794 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000795 // Failure when evaluating some expression often means there is some
796 // subexpression whose evaluation was skipped. Therefore, (because we
797 // don't track whether we skipped an expression when unwinding after an
798 // evaluation failure) every evaluation failure that bubbles up from a
799 // subexpression implies that a side-effect has potentially happened. We
800 // skip setting the HasSideEffects flag to true until we decide to
801 // continue evaluating after that point, which happens here.
802 bool KeepGoing = keepEvaluatingAfterFailure();
803 EvalStatus.HasSideEffects |= KeepGoing;
804 return KeepGoing;
805 }
806
George Burgess IV3a03fab2015-09-04 21:28:13 +0000807 bool allowInvalidBaseExpr() const {
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000808 return EvalMode == EM_DesignatorFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000809 }
Richard Smith410306b2016-12-12 02:53:20 +0000810
811 class ArrayInitLoopIndex {
812 EvalInfo &Info;
813 uint64_t OuterIndex;
814
815 public:
816 ArrayInitLoopIndex(EvalInfo &Info)
817 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
818 Info.ArrayInitIndex = 0;
819 }
820 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
821
822 operator uint64_t&() { return Info.ArrayInitIndex; }
823 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000824 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000825
826 /// Object used to treat all foldable expressions as constant expressions.
827 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000829 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000830 bool HadNoPriorDiags;
831 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000832
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 explicit FoldConstant(EvalInfo &Info, bool Enabled)
834 : Info(Info),
835 Enabled(Enabled),
836 HadNoPriorDiags(Info.EvalStatus.Diag &&
837 Info.EvalStatus.Diag->empty() &&
838 !Info.EvalStatus.HasSideEffects),
839 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000840 if (Enabled &&
841 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
842 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000843 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000844 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000845 void keepDiagnostics() { Enabled = false; }
846 ~FoldConstant() {
847 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000848 !Info.EvalStatus.HasSideEffects)
849 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000851 }
852 };
Richard Smith17100ba2012-02-16 02:46:34 +0000853
George Burgess IV3a03fab2015-09-04 21:28:13 +0000854 /// RAII object used to treat the current evaluation as the correct pointer
855 /// offset fold for the current EvalMode
856 struct FoldOffsetRAII {
857 EvalInfo &Info;
858 EvalInfo::EvaluationMode OldMode;
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000859 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000860 : Info(Info), OldMode(Info.EvalMode) {
861 if (!Info.checkingPotentialConstantExpression())
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000862 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
863 : EvalInfo::EM_ConstantFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000864 }
865
866 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
867 };
868
George Burgess IV8c892b52016-05-25 22:31:54 +0000869 /// RAII object used to optionally suppress diagnostics and side-effects from
870 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000871 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000872 /// Pair of EvalInfo, and a bit that stores whether or not we were
873 /// speculatively evaluating when we created this RAII.
874 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000875 Expr::EvalStatus Old;
876
George Burgess IV8c892b52016-05-25 22:31:54 +0000877 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
878 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
879 Old = Other.Old;
880 Other.InfoAndOldSpecEval.setPointer(nullptr);
881 }
882
883 void maybeRestoreState() {
884 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
885 if (!Info)
886 return;
887
888 Info->EvalStatus = Old;
889 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
890 }
891
Richard Smith17100ba2012-02-16 02:46:34 +0000892 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000893 SpeculativeEvaluationRAII() = default;
894
895 SpeculativeEvaluationRAII(
896 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
897 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
898 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000899 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000900 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000901 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000902
903 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
904 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
905 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000906 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000907
908 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
909 maybeRestoreState();
910 moveFromAndCancel(std::move(Other));
911 return *this;
912 }
913
914 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000915 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000916
917 /// RAII object wrapping a full-expression or block scope, and handling
918 /// the ending of the lifetime of temporaries created within it.
919 template<bool IsFullExpression>
920 class ScopeRAII {
921 EvalInfo &Info;
922 unsigned OldStackSize;
923 public:
924 ScopeRAII(EvalInfo &Info)
925 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
926 ~ScopeRAII() {
927 // Body moved to a static method to encourage the compiler to inline away
928 // instances of this class.
929 cleanup(Info, OldStackSize);
930 }
931 private:
932 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
933 unsigned NewEnd = OldStackSize;
934 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
935 I != N; ++I) {
936 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
937 // Full-expression cleanup of a lifetime-extended temporary: nothing
938 // to do, just move this cleanup to the right place in the stack.
939 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
940 ++NewEnd;
941 } else {
942 // End the lifetime of the object.
943 Info.CleanupStack[I].endLifetime();
944 }
945 }
946 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
947 Info.CleanupStack.end());
948 }
949 };
950 typedef ScopeRAII<false> BlockScopeRAII;
951 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000952}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000953
Richard Smitha8105bc2012-01-06 16:39:00 +0000954bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Invalid)
957 return false;
958 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 setInvalid();
962 return false;
963 }
964 return true;
965}
966
967void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
968 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000969 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000971 << static_cast<int>(N) << /*array*/ 0
Chandler Carruthd7738fe2016-12-20 08:28:19 +0000972 << static_cast<unsigned>(MostDerivedArraySize);
Richard Smitha8105bc2012-01-06 16:39:00 +0000973 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000974 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 << static_cast<int>(N) << /*non-array*/ 1;
976 setInvalid();
977}
978
Richard Smithf6f003a2011-12-16 19:06:07 +0000979CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
980 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000981 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +0000982 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
983 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000984 Info.CurrentCall = this;
985 ++Info.CallStackDepth;
986}
987
988CallStackFrame::~CallStackFrame() {
989 assert(Info.CurrentCall == this && "calls retired out of order");
990 --Info.CallStackDepth;
991 Info.CurrentCall = Caller;
992}
993
Richard Smith08d6a2c2013-07-24 07:11:57 +0000994APValue &CallStackFrame::createTemporary(const void *Key,
995 bool IsLifetimeExtended) {
996 APValue &Result = Temporaries[Key];
997 assert(Result.isUninit() && "temporary created multiple times");
998 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
999 return Result;
1000}
1001
Richard Smith84401042013-06-03 05:03:02 +00001002static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001003
1004void EvalInfo::addCallStack(unsigned Limit) {
1005 // Determine which calls to skip, if any.
1006 unsigned ActiveCalls = CallStackDepth - 1;
1007 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1008 if (Limit && Limit < ActiveCalls) {
1009 SkipStart = Limit / 2 + Limit % 2;
1010 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001011 }
1012
Richard Smithf6f003a2011-12-16 19:06:07 +00001013 // Walk the call stack and add the diagnostics.
1014 unsigned CallIdx = 0;
1015 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1016 Frame = Frame->Caller, ++CallIdx) {
1017 // Skip this call?
1018 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1019 if (CallIdx == SkipStart) {
1020 // Note that we're skipping calls.
1021 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1022 << unsigned(ActiveCalls - Limit);
1023 }
1024 continue;
1025 }
1026
Richard Smith5179eb72016-06-28 19:03:57 +00001027 // Use a different note for an inheriting constructor, because from the
1028 // user's perspective it's not really a function at all.
1029 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1030 if (CD->isInheritingConstructor()) {
1031 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1032 << CD->getParent();
1033 continue;
1034 }
1035 }
1036
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001037 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001038 llvm::raw_svector_ostream Out(Buffer);
1039 describeCall(Frame, Out);
1040 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1041 }
1042}
1043
1044namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001045 struct ComplexValue {
1046 private:
1047 bool IsInt;
1048
1049 public:
1050 APSInt IntReal, IntImag;
1051 APFloat FloatReal, FloatImag;
1052
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001053 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001054
1055 void makeComplexFloat() { IsInt = false; }
1056 bool isComplexFloat() const { return !IsInt; }
1057 APFloat &getComplexFloatReal() { return FloatReal; }
1058 APFloat &getComplexFloatImag() { return FloatImag; }
1059
1060 void makeComplexInt() { IsInt = true; }
1061 bool isComplexInt() const { return IsInt; }
1062 APSInt &getComplexIntReal() { return IntReal; }
1063 APSInt &getComplexIntImag() { return IntImag; }
1064
Richard Smith2e312c82012-03-03 22:46:17 +00001065 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001066 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001067 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001068 else
Richard Smith2e312c82012-03-03 22:46:17 +00001069 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001070 }
Richard Smith2e312c82012-03-03 22:46:17 +00001071 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001072 assert(v.isComplexFloat() || v.isComplexInt());
1073 if (v.isComplexFloat()) {
1074 makeComplexFloat();
1075 FloatReal = v.getComplexFloatReal();
1076 FloatImag = v.getComplexFloatImag();
1077 } else {
1078 makeComplexInt();
1079 IntReal = v.getComplexIntReal();
1080 IntImag = v.getComplexIntImag();
1081 }
1082 }
John McCall93d91dc2010-05-07 17:22:02 +00001083 };
John McCall45d55e42010-05-07 21:00:08 +00001084
1085 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001086 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001087 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001088 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001090 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001091 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001092
Richard Smithce40ad62011-11-12 22:28:03 +00001093 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001094 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001095 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001096 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001097 SubobjectDesignator &getLValueDesignator() { return Designator; }
1098 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001099 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001100
Richard Smith2e312c82012-03-03 22:46:17 +00001101 void moveInto(APValue &V) const {
1102 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001103 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1104 IsNullPtr);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00001105 else
Richard Smith2e312c82012-03-03 22:46:17 +00001106 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001107 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
John McCall45d55e42010-05-07 21:00:08 +00001108 }
Richard Smith2e312c82012-03-03 22:46:17 +00001109 void setFrom(ASTContext &Ctx, const APValue &V) {
Chandler Carruthd7738fe2016-12-20 08:28:19 +00001110 assert(V.isLValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001111 Base = V.getLValueBase();
1112 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001113 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001114 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001115 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001116 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001117 }
1118
Yaxun Liu402804b2016-12-15 08:09:08 +00001119 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1120 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +00001121 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001122 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001123 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001124 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001126 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001127 }
1128
George Burgess IV3a03fab2015-09-04 21:28:13 +00001129 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1130 set(B, I, true);
1131 }
1132
Richard Smitha8105bc2012-01-06 16:39:00 +00001133 // Check that this LValue is not based on a null pointer. If it is, produce
1134 // a diagnostic and mark the designator as invalid.
1135 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1136 CheckSubobjectKind CSK) {
1137 if (Designator.Invalid)
1138 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001139 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001140 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001141 << CSK;
1142 Designator.setInvalid();
1143 return false;
1144 }
1145 return true;
1146 }
1147
1148 // Check this LValue refers to an object. If not, set the designator to be
1149 // invalid and emit a diagnostic.
1150 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001151 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001152 Designator.checkSubobject(Info, E, CSK);
1153 }
1154
1155 void addDecl(EvalInfo &Info, const Expr *E,
1156 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001157 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1158 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001159 }
1160 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001161 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1162 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001163 }
Richard Smith66c96992012-02-18 22:04:06 +00001164 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001165 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1166 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001167 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001168 void clearIsNullPointer() {
1169 IsNullPtr = false;
1170 }
1171 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1172 CharUnits ElementSize) {
1173 // Compute the new offset in the appropriate width.
1174 Offset += Index * ElementSize;
1175 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1176 Designator.adjustIndex(Info, E, Index);
1177 if (Index)
1178 clearIsNullPointer();
1179 }
1180 void adjustOffset(CharUnits N) {
1181 Offset += N;
1182 if (N.getQuantity())
1183 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001184 }
John McCall45d55e42010-05-07 21:00:08 +00001185 };
Richard Smith027bf112011-11-17 22:56:20 +00001186
1187 struct MemberPtr {
1188 MemberPtr() {}
1189 explicit MemberPtr(const ValueDecl *Decl) :
1190 DeclAndIsDerivedMember(Decl, false), Path() {}
1191
1192 /// The member or (direct or indirect) field referred to by this member
1193 /// pointer, or 0 if this is a null member pointer.
1194 const ValueDecl *getDecl() const {
1195 return DeclAndIsDerivedMember.getPointer();
1196 }
1197 /// Is this actually a member of some type derived from the relevant class?
1198 bool isDerivedMember() const {
1199 return DeclAndIsDerivedMember.getInt();
1200 }
1201 /// Get the class which the declaration actually lives in.
1202 const CXXRecordDecl *getContainingRecord() const {
1203 return cast<CXXRecordDecl>(
1204 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1205 }
1206
Richard Smith2e312c82012-03-03 22:46:17 +00001207 void moveInto(APValue &V) const {
1208 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001209 }
Richard Smith2e312c82012-03-03 22:46:17 +00001210 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001211 assert(V.isMemberPointer());
1212 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1213 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1214 Path.clear();
1215 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1216 Path.insert(Path.end(), P.begin(), P.end());
1217 }
1218
1219 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1220 /// whether the member is a member of some class derived from the class type
1221 /// of the member pointer.
1222 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1223 /// Path - The path of base/derived classes from the member declaration's
1224 /// class (exclusive) to the class type of the member pointer (inclusive).
1225 SmallVector<const CXXRecordDecl*, 4> Path;
1226
1227 /// Perform a cast towards the class of the Decl (either up or down the
1228 /// hierarchy).
1229 bool castBack(const CXXRecordDecl *Class) {
1230 assert(!Path.empty());
1231 const CXXRecordDecl *Expected;
1232 if (Path.size() >= 2)
1233 Expected = Path[Path.size() - 2];
1234 else
1235 Expected = getContainingRecord();
1236 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1237 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1238 // if B does not contain the original member and is not a base or
1239 // derived class of the class containing the original member, the result
1240 // of the cast is undefined.
1241 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1242 // (D::*). We consider that to be a language defect.
1243 return false;
1244 }
1245 Path.pop_back();
1246 return true;
1247 }
1248 /// Perform a base-to-derived member pointer cast.
1249 bool castToDerived(const CXXRecordDecl *Derived) {
1250 if (!getDecl())
1251 return true;
1252 if (!isDerivedMember()) {
1253 Path.push_back(Derived);
1254 return true;
1255 }
1256 if (!castBack(Derived))
1257 return false;
1258 if (Path.empty())
1259 DeclAndIsDerivedMember.setInt(false);
1260 return true;
1261 }
1262 /// Perform a derived-to-base member pointer cast.
1263 bool castToBase(const CXXRecordDecl *Base) {
1264 if (!getDecl())
1265 return true;
1266 if (Path.empty())
1267 DeclAndIsDerivedMember.setInt(true);
1268 if (isDerivedMember()) {
1269 Path.push_back(Base);
1270 return true;
1271 }
1272 return castBack(Base);
1273 }
1274 };
Richard Smith357362d2011-12-13 06:39:58 +00001275
Richard Smith7bb00672012-02-01 01:42:44 +00001276 /// Compare two member pointers, which are assumed to be of the same type.
1277 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1278 if (!LHS.getDecl() || !RHS.getDecl())
1279 return !LHS.getDecl() && !RHS.getDecl();
1280 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1281 return false;
1282 return LHS.Path == RHS.Path;
1283 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001284}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001285
Richard Smith2e312c82012-03-03 22:46:17 +00001286static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001287static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1288 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001289 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001290static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1291static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001292static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1293 EvalInfo &Info);
1294static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001295static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001296static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001297 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001298static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001299static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001300static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001301static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001302
1303//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001304// Misc utilities
1305//===----------------------------------------------------------------------===//
1306
Richard Smith84401042013-06-03 05:03:02 +00001307/// Produce a string describing the given constexpr call.
1308static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1309 unsigned ArgIndex = 0;
1310 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1311 !isa<CXXConstructorDecl>(Frame->Callee) &&
1312 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1313
1314 if (!IsMemberCall)
1315 Out << *Frame->Callee << '(';
1316
1317 if (Frame->This && IsMemberCall) {
1318 APValue Val;
1319 Frame->This->moveInto(Val);
1320 Val.printPretty(Out, Frame->Info.Ctx,
1321 Frame->This->Designator.MostDerivedType);
1322 // FIXME: Add parens around Val if needed.
1323 Out << "->" << *Frame->Callee << '(';
1324 IsMemberCall = false;
1325 }
1326
1327 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1328 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1329 if (ArgIndex > (unsigned)IsMemberCall)
1330 Out << ", ";
1331
1332 const ParmVarDecl *Param = *I;
1333 const APValue &Arg = Frame->Arguments[ArgIndex];
1334 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1335
1336 if (ArgIndex == 0 && IsMemberCall)
1337 Out << "->" << *Frame->Callee << '(';
1338 }
1339
1340 Out << ')';
1341}
1342
Richard Smithd9f663b2013-04-22 15:31:51 +00001343/// Evaluate an expression to see if it had side-effects, and discard its
1344/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001345/// \return \c true if the caller should keep evaluating.
1346static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001347 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001348 if (!Evaluate(Scratch, Info, E))
1349 // We don't need the value, but we might have skipped a side effect here.
1350 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001351 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001352}
1353
Richard Smith861b5b52013-05-07 23:34:45 +00001354/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1355/// return its existing value.
1356static int64_t getExtValue(const APSInt &Value) {
1357 return Value.isSigned() ? Value.getSExtValue()
1358 : static_cast<int64_t>(Value.getZExtValue());
1359}
1360
Richard Smithd62306a2011-11-10 06:34:14 +00001361/// Should this call expression be treated as a string literal?
1362static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001363 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001364 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1365 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1366}
1367
Richard Smithce40ad62011-11-12 22:28:03 +00001368static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001369 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1370 // constant expression of pointer type that evaluates to...
1371
1372 // ... a null pointer value, or a prvalue core constant expression of type
1373 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001374 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001375
Richard Smithce40ad62011-11-12 22:28:03 +00001376 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1377 // ... the address of an object with static storage duration,
1378 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1379 return VD->hasGlobalStorage();
1380 // ... the address of a function,
1381 return isa<FunctionDecl>(D);
1382 }
1383
1384 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001385 switch (E->getStmtClass()) {
1386 default:
1387 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001388 case Expr::CompoundLiteralExprClass: {
1389 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1390 return CLE->isFileScope() && CLE->isLValue();
1391 }
Richard Smithe6c01442013-06-05 00:46:14 +00001392 case Expr::MaterializeTemporaryExprClass:
1393 // A materialized temporary might have been lifetime-extended to static
1394 // storage duration.
1395 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001396 // A string literal has static storage duration.
1397 case Expr::StringLiteralClass:
1398 case Expr::PredefinedExprClass:
1399 case Expr::ObjCStringLiteralClass:
1400 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001401 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001402 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001403 return true;
1404 case Expr::CallExprClass:
1405 return IsStringLiteralCall(cast<CallExpr>(E));
1406 // For GCC compatibility, &&label has static storage duration.
1407 case Expr::AddrLabelExprClass:
1408 return true;
1409 // A Block literal expression may be used as the initialization value for
1410 // Block variables at global or local static scope.
1411 case Expr::BlockExprClass:
1412 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001413 case Expr::ImplicitValueInitExprClass:
1414 // FIXME:
1415 // We can never form an lvalue with an implicit value initialization as its
1416 // base through expression evaluation, so these only appear in one case: the
1417 // implicit variable declaration we invent when checking whether a constexpr
1418 // constructor can produce a constant expression. We must assume that such
1419 // an expression might be a global lvalue.
1420 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001421 }
John McCall95007602010-05-10 23:27:23 +00001422}
1423
Richard Smithb228a862012-02-15 02:18:13 +00001424static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1425 assert(Base && "no location for a null lvalue");
1426 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1427 if (VD)
1428 Info.Note(VD->getLocation(), diag::note_declared_at);
1429 else
Ted Kremenek28831752012-08-23 20:46:57 +00001430 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001431 diag::note_constexpr_temporary_here);
1432}
1433
Richard Smith80815602011-11-07 05:07:52 +00001434/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001435/// value for an address or reference constant expression. Return true if we
1436/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001437static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1438 QualType Type, const LValue &LVal) {
1439 bool IsReferenceType = Type->isReferenceType();
1440
Richard Smith357362d2011-12-13 06:39:58 +00001441 APValue::LValueBase Base = LVal.getLValueBase();
1442 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1443
Richard Smith0dea49e2012-02-18 04:58:18 +00001444 // Check that the object is a global. Note that the fake 'this' object we
1445 // manufacture when checking potential constant expressions is conservatively
1446 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001447 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001448 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001449 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001450 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001451 << IsReferenceType << !Designator.Entries.empty()
1452 << !!VD << VD;
1453 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001454 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001455 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001456 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001457 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001458 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001459 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001460 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001461 LVal.getLValueCallIndex() == 0) &&
1462 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001463
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001464 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1465 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001466 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001467 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001468 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001469
Hans Wennborg82dd8772014-06-25 22:19:48 +00001470 // A dllimport variable never acts like a constant.
1471 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001472 return false;
1473 }
1474 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1475 // __declspec(dllimport) must be handled very carefully:
1476 // We must never initialize an expression with the thunk in C++.
1477 // Doing otherwise would allow the same id-expression to yield
1478 // different addresses for the same function in different translation
1479 // units. However, this means that we must dynamically initialize the
1480 // expression with the contents of the import address table at runtime.
1481 //
1482 // The C language has no notion of ODR; furthermore, it has no notion of
1483 // dynamic initialization. This means that we are permitted to
1484 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001485 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001486 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001487 }
1488 }
1489
Richard Smitha8105bc2012-01-06 16:39:00 +00001490 // Allow address constant expressions to be past-the-end pointers. This is
1491 // an extension: the standard requires them to point to an object.
1492 if (!IsReferenceType)
1493 return true;
1494
1495 // A reference constant expression must refer to an object.
1496 if (!Base) {
1497 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001498 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001499 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001500 }
1501
Richard Smith357362d2011-12-13 06:39:58 +00001502 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001503 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001504 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001505 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001506 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001507 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001508 }
1509
Richard Smith80815602011-11-07 05:07:52 +00001510 return true;
1511}
1512
Richard Smithfddd3842011-12-30 21:15:51 +00001513/// Check that this core constant expression is of literal type, and if not,
1514/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001515static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001516 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001517 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001518 return true;
1519
Richard Smith7525ff62013-05-09 07:14:00 +00001520 // C++1y: A constant initializer for an object o [...] may also invoke
1521 // constexpr constructors for o and its subobjects even if those objects
1522 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001523 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001524 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001525 return true;
1526
Richard Smithfddd3842011-12-30 21:15:51 +00001527 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001528 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001529 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001530 << E->getType();
1531 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001532 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001533 return false;
1534}
1535
Richard Smith0b0a0b62011-10-29 20:57:55 +00001536/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001537/// constant expression. If not, report an appropriate diagnostic. Does not
1538/// check that the expression is of literal type.
1539static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1540 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001541 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001542 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001543 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001544 return false;
1545 }
1546
Richard Smith77be48a2014-07-31 06:31:19 +00001547 // We allow _Atomic(T) to be initialized from anything that T can be
1548 // initialized from.
1549 if (const AtomicType *AT = Type->getAs<AtomicType>())
1550 Type = AT->getValueType();
1551
Richard Smithb228a862012-02-15 02:18:13 +00001552 // Core issue 1454: For a literal constant expression of array or class type,
1553 // each subobject of its value shall have been initialized by a constant
1554 // expression.
1555 if (Value.isArray()) {
1556 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1557 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1558 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1559 Value.getArrayInitializedElt(I)))
1560 return false;
1561 }
1562 if (!Value.hasArrayFiller())
1563 return true;
1564 return CheckConstantExpression(Info, DiagLoc, EltTy,
1565 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001566 }
Richard Smithb228a862012-02-15 02:18:13 +00001567 if (Value.isUnion() && Value.getUnionField()) {
1568 return CheckConstantExpression(Info, DiagLoc,
1569 Value.getUnionField()->getType(),
1570 Value.getUnionValue());
1571 }
1572 if (Value.isStruct()) {
1573 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1574 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1575 unsigned BaseIndex = 0;
1576 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1577 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1578 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1579 Value.getStructBase(BaseIndex)))
1580 return false;
1581 }
1582 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001583 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001584 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1585 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001586 return false;
1587 }
1588 }
1589
1590 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001591 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001592 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001593 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1594 }
1595
1596 // Everything else is fine.
1597 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001598}
1599
Benjamin Kramer8407df72015-03-09 16:47:52 +00001600static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001601 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001602}
1603
1604static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001605 if (Value.CallIndex)
1606 return false;
1607 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1608 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001609}
1610
Richard Smithcecf1842011-11-01 21:06:14 +00001611static bool IsWeakLValue(const LValue &Value) {
1612 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001613 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001614}
1615
David Majnemerb5116032014-12-09 23:32:34 +00001616static bool isZeroSized(const LValue &Value) {
1617 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001618 if (Decl && isa<VarDecl>(Decl)) {
1619 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001620 if (Ty->isArrayType())
1621 return Ty->isIncompleteType() ||
1622 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001623 }
1624 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001625}
1626
Richard Smith2e312c82012-03-03 22:46:17 +00001627static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001628 // A null base expression indicates a null pointer. These are always
1629 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001630 if (!Value.getLValueBase()) {
1631 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001632 return true;
1633 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001634
Richard Smith027bf112011-11-17 22:56:20 +00001635 // We have a non-null base. These are generally known to be true, but if it's
1636 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001637 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001638 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001639 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001640}
1641
Richard Smith2e312c82012-03-03 22:46:17 +00001642static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001643 switch (Val.getKind()) {
1644 case APValue::Uninitialized:
1645 return false;
1646 case APValue::Int:
1647 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001648 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001649 case APValue::Float:
1650 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001651 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001652 case APValue::ComplexInt:
1653 Result = Val.getComplexIntReal().getBoolValue() ||
1654 Val.getComplexIntImag().getBoolValue();
1655 return true;
1656 case APValue::ComplexFloat:
1657 Result = !Val.getComplexFloatReal().isZero() ||
1658 !Val.getComplexFloatImag().isZero();
1659 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001660 case APValue::LValue:
1661 return EvalPointerValueAsBool(Val, Result);
1662 case APValue::MemberPointer:
1663 Result = Val.getMemberPointerDecl();
1664 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001665 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001666 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001667 case APValue::Struct:
1668 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001669 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001670 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001671 }
1672
Richard Smith11562c52011-10-28 17:51:58 +00001673 llvm_unreachable("unknown APValue kind");
1674}
1675
1676static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1677 EvalInfo &Info) {
1678 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001679 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001680 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001681 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001682 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001683}
1684
Richard Smith357362d2011-12-13 06:39:58 +00001685template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001686static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001687 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001688 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001689 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001690 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001691}
1692
1693static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1694 QualType SrcType, const APFloat &Value,
1695 QualType DestType, APSInt &Result) {
1696 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001697 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001698 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001699
Richard Smith357362d2011-12-13 06:39:58 +00001700 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001701 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001702 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1703 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001704 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001705 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001706}
1707
Richard Smith357362d2011-12-13 06:39:58 +00001708static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1709 QualType SrcType, QualType DestType,
1710 APFloat &Result) {
1711 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001712 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001713 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1714 APFloat::rmNearestTiesToEven, &ignored)
1715 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001716 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001717 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001718}
1719
Richard Smith911e1422012-01-30 22:27:01 +00001720static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1721 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001722 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001723 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001724 APSInt Result = Value;
1725 // Figure out if this is a truncate, extend or noop cast.
1726 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001727 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001728 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001729 return Result;
1730}
1731
Richard Smith357362d2011-12-13 06:39:58 +00001732static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1733 QualType SrcType, const APSInt &Value,
1734 QualType DestType, APFloat &Result) {
1735 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1736 if (Result.convertFromAPInt(Value, Value.isSigned(),
1737 APFloat::rmNearestTiesToEven)
1738 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001739 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001740 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001741}
1742
Richard Smith49ca8aa2013-08-06 07:09:20 +00001743static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1744 APValue &Value, const FieldDecl *FD) {
1745 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1746
1747 if (!Value.isInt()) {
1748 // Trying to store a pointer-cast-to-integer into a bitfield.
1749 // FIXME: In this case, we should provide the diagnostic for casting
1750 // a pointer to an integer.
1751 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001752 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001753 return false;
1754 }
1755
1756 APSInt &Int = Value.getInt();
1757 unsigned OldBitWidth = Int.getBitWidth();
1758 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1759 if (NewBitWidth < OldBitWidth)
1760 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1761 return true;
1762}
1763
Eli Friedman803acb32011-12-22 03:51:45 +00001764static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1765 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001766 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001767 if (!Evaluate(SVal, Info, E))
1768 return false;
1769 if (SVal.isInt()) {
1770 Res = SVal.getInt();
1771 return true;
1772 }
1773 if (SVal.isFloat()) {
1774 Res = SVal.getFloat().bitcastToAPInt();
1775 return true;
1776 }
1777 if (SVal.isVector()) {
1778 QualType VecTy = E->getType();
1779 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1780 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1781 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1782 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1783 Res = llvm::APInt::getNullValue(VecSize);
1784 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1785 APValue &Elt = SVal.getVectorElt(i);
1786 llvm::APInt EltAsInt;
1787 if (Elt.isInt()) {
1788 EltAsInt = Elt.getInt();
1789 } else if (Elt.isFloat()) {
1790 EltAsInt = Elt.getFloat().bitcastToAPInt();
1791 } else {
1792 // Don't try to handle vectors of anything other than int or float
1793 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001794 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001795 return false;
1796 }
1797 unsigned BaseEltSize = EltAsInt.getBitWidth();
1798 if (BigEndian)
1799 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1800 else
1801 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1802 }
1803 return true;
1804 }
1805 // Give up if the input isn't an int, float, or vector. For example, we
1806 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001807 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001808 return false;
1809}
1810
Richard Smith43e77732013-05-07 04:50:00 +00001811/// Perform the given integer operation, which is known to need at most BitWidth
1812/// bits, and check for overflow in the original type (if that type was not an
1813/// unsigned type).
1814template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001815static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1816 const APSInt &LHS, const APSInt &RHS,
1817 unsigned BitWidth, Operation Op,
1818 APSInt &Result) {
1819 if (LHS.isUnsigned()) {
1820 Result = Op(LHS, RHS);
1821 return true;
1822 }
Richard Smith43e77732013-05-07 04:50:00 +00001823
1824 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001825 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001826 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001827 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001828 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001829 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001830 << Result.toString(10) << E->getType();
1831 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001832 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001833 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001834 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001835}
1836
1837/// Perform the given binary integer operation.
1838static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1839 BinaryOperatorKind Opcode, APSInt RHS,
1840 APSInt &Result) {
1841 switch (Opcode) {
1842 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001843 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001844 return false;
1845 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001846 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1847 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001848 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001849 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1850 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001851 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001852 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1853 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001854 case BO_And: Result = LHS & RHS; return true;
1855 case BO_Xor: Result = LHS ^ RHS; return true;
1856 case BO_Or: Result = LHS | RHS; return true;
1857 case BO_Div:
1858 case BO_Rem:
1859 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001860 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001861 return false;
1862 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001863 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1864 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1865 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001866 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1867 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001868 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1869 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001870 return true;
1871 case BO_Shl: {
1872 if (Info.getLangOpts().OpenCL)
1873 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1874 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1875 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1876 RHS.isUnsigned());
1877 else if (RHS.isSigned() && RHS.isNegative()) {
1878 // During constant-folding, a negative shift is an opposite shift. Such
1879 // a shift is not a constant expression.
1880 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1881 RHS = -RHS;
1882 goto shift_right;
1883 }
1884 shift_left:
1885 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1886 // the shifted type.
1887 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1888 if (SA != RHS) {
1889 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1890 << RHS << E->getType() << LHS.getBitWidth();
1891 } else if (LHS.isSigned()) {
1892 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1893 // operand, and must not overflow the corresponding unsigned type.
1894 if (LHS.isNegative())
1895 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1896 else if (LHS.countLeadingZeros() < SA)
1897 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1898 }
1899 Result = LHS << SA;
1900 return true;
1901 }
1902 case BO_Shr: {
1903 if (Info.getLangOpts().OpenCL)
1904 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1905 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1906 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1907 RHS.isUnsigned());
1908 else if (RHS.isSigned() && RHS.isNegative()) {
1909 // During constant-folding, a negative shift is an opposite shift. Such a
1910 // shift is not a constant expression.
1911 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1912 RHS = -RHS;
1913 goto shift_left;
1914 }
1915 shift_right:
1916 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1917 // shifted type.
1918 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1919 if (SA != RHS)
1920 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1921 << RHS << E->getType() << LHS.getBitWidth();
1922 Result = LHS >> SA;
1923 return true;
1924 }
1925
1926 case BO_LT: Result = LHS < RHS; return true;
1927 case BO_GT: Result = LHS > RHS; return true;
1928 case BO_LE: Result = LHS <= RHS; return true;
1929 case BO_GE: Result = LHS >= RHS; return true;
1930 case BO_EQ: Result = LHS == RHS; return true;
1931 case BO_NE: Result = LHS != RHS; return true;
1932 }
1933}
1934
Richard Smith861b5b52013-05-07 23:34:45 +00001935/// Perform the given binary floating-point operation, in-place, on LHS.
1936static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1937 APFloat &LHS, BinaryOperatorKind Opcode,
1938 const APFloat &RHS) {
1939 switch (Opcode) {
1940 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001941 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001942 return false;
1943 case BO_Mul:
1944 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1945 break;
1946 case BO_Add:
1947 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1948 break;
1949 case BO_Sub:
1950 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1951 break;
1952 case BO_Div:
1953 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1954 break;
1955 }
1956
Richard Smith0c6124b2015-12-03 01:36:22 +00001957 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001958 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001959 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001960 }
Richard Smith861b5b52013-05-07 23:34:45 +00001961 return true;
1962}
1963
Richard Smitha8105bc2012-01-06 16:39:00 +00001964/// Cast an lvalue referring to a base subobject to a derived class, by
1965/// truncating the lvalue's path to the given length.
1966static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1967 const RecordDecl *TruncatedType,
1968 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001969 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001970
1971 // Check we actually point to a derived class object.
1972 if (TruncatedElements == D.Entries.size())
1973 return true;
1974 assert(TruncatedElements >= D.MostDerivedPathLength &&
1975 "not casting to a derived class");
1976 if (!Result.checkSubobject(Info, E, CSK_Derived))
1977 return false;
1978
1979 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001980 const RecordDecl *RD = TruncatedType;
1981 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001982 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001983 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1984 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001985 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001986 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001987 else
Richard Smithd62306a2011-11-10 06:34:14 +00001988 Result.Offset -= Layout.getBaseClassOffset(Base);
1989 RD = Base;
1990 }
Richard Smith027bf112011-11-17 22:56:20 +00001991 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001992 return true;
1993}
1994
John McCalld7bca762012-05-01 00:38:49 +00001995static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001996 const CXXRecordDecl *Derived,
1997 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001998 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001999 if (!RL) {
2000 if (Derived->isInvalidDecl()) return false;
2001 RL = &Info.Ctx.getASTRecordLayout(Derived);
2002 }
2003
Richard Smithd62306a2011-11-10 06:34:14 +00002004 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002005 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002006 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002007}
2008
Richard Smitha8105bc2012-01-06 16:39:00 +00002009static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002010 const CXXRecordDecl *DerivedDecl,
2011 const CXXBaseSpecifier *Base) {
2012 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2013
John McCalld7bca762012-05-01 00:38:49 +00002014 if (!Base->isVirtual())
2015 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002016
Richard Smitha8105bc2012-01-06 16:39:00 +00002017 SubobjectDesignator &D = Obj.Designator;
2018 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002019 return false;
2020
Richard Smitha8105bc2012-01-06 16:39:00 +00002021 // Extract most-derived object and corresponding type.
2022 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2023 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2024 return false;
2025
2026 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002027 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002028 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2029 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002030 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002031 return true;
2032}
2033
Richard Smith84401042013-06-03 05:03:02 +00002034static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2035 QualType Type, LValue &Result) {
2036 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2037 PathE = E->path_end();
2038 PathI != PathE; ++PathI) {
2039 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2040 *PathI))
2041 return false;
2042 Type = (*PathI)->getType();
2043 }
2044 return true;
2045}
2046
Richard Smithd62306a2011-11-10 06:34:14 +00002047/// Update LVal to refer to the given field, which must be a member of the type
2048/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002049static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002050 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002051 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002052 if (!RL) {
2053 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002054 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002055 }
Richard Smithd62306a2011-11-10 06:34:14 +00002056
2057 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002058 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002059 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002060 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002061}
2062
Richard Smith1b78b3d2012-01-25 22:15:11 +00002063/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002064static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002065 LValue &LVal,
2066 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002067 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002068 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002069 return false;
2070 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002071}
2072
Richard Smithd62306a2011-11-10 06:34:14 +00002073/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002074static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2075 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002076 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2077 // extension.
2078 if (Type->isVoidType() || Type->isFunctionType()) {
2079 Size = CharUnits::One();
2080 return true;
2081 }
2082
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002083 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002084 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002085 return false;
2086 }
2087
Richard Smithd62306a2011-11-10 06:34:14 +00002088 if (!Type->isConstantSizeType()) {
2089 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002090 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002091 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002092 return false;
2093 }
2094
2095 Size = Info.Ctx.getTypeSizeInChars(Type);
2096 return true;
2097}
2098
2099/// Update a pointer value to model pointer arithmetic.
2100/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002101/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002102/// \param LVal - The pointer value to be updated.
2103/// \param EltTy - The pointee type represented by LVal.
2104/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002105static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2106 LValue &LVal, QualType EltTy,
2107 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002108 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002109 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002110 return false;
2111
Yaxun Liu402804b2016-12-15 08:09:08 +00002112 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002113 return true;
2114}
2115
Richard Smith66c96992012-02-18 22:04:06 +00002116/// Update an lvalue to refer to a component of a complex number.
2117/// \param Info - Information about the ongoing evaluation.
2118/// \param LVal - The lvalue to be updated.
2119/// \param EltTy - The complex number's component type.
2120/// \param Imag - False for the real component, true for the imaginary.
2121static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2122 LValue &LVal, QualType EltTy,
2123 bool Imag) {
2124 if (Imag) {
2125 CharUnits SizeOfComponent;
2126 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2127 return false;
2128 LVal.Offset += SizeOfComponent;
2129 }
2130 LVal.addComplex(Info, E, EltTy, Imag);
2131 return true;
2132}
2133
Richard Smith27908702011-10-24 17:54:18 +00002134/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002135///
2136/// \param Info Information about the ongoing evaluation.
2137/// \param E An expression to be used when printing diagnostics.
2138/// \param VD The variable whose initializer should be obtained.
2139/// \param Frame The frame in which the variable was created. Must be null
2140/// if this variable is not local to the evaluation.
2141/// \param Result Filled in with a pointer to the value of the variable.
2142static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2143 const VarDecl *VD, CallStackFrame *Frame,
2144 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002145 // If this is a parameter to an active constexpr function call, perform
2146 // argument substitution.
2147 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002148 // Assume arguments of a potential constant expression are unknown
2149 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002150 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002151 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002152 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002154 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002155 }
Richard Smith3229b742013-05-05 21:17:10 +00002156 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002157 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002158 }
Richard Smith27908702011-10-24 17:54:18 +00002159
Richard Smithd9f663b2013-04-22 15:31:51 +00002160 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002161 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002162 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002163 if (!Result) {
2164 // Assume variables referenced within a lambda's call operator that were
2165 // not declared within the call operator are captures and during checking
2166 // of a potential constant expression, assume they are unknown constant
2167 // expressions.
2168 assert(isLambdaCallOperator(Frame->Callee) &&
2169 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2170 "missing value for local variable");
2171 if (Info.checkingPotentialConstantExpression())
2172 return false;
2173 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002174 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002175 diag::note_unimplemented_constexpr_lambda_feature_ast)
2176 << "captures not currently allowed";
2177 return false;
2178 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002179 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002180 }
2181
Richard Smithd0b4dd62011-12-19 06:19:21 +00002182 // Dig out the initializer, and use the declaration which it's attached to.
2183 const Expr *Init = VD->getAnyInitializer(VD);
2184 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002185 // If we're checking a potential constant expression, the variable could be
2186 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002187 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002188 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002189 return false;
2190 }
2191
Richard Smithd62306a2011-11-10 06:34:14 +00002192 // If we're currently evaluating the initializer of this declaration, use that
2193 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002194 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002195 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002196 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002197 }
2198
Richard Smithcecf1842011-11-01 21:06:14 +00002199 // Never evaluate the initializer of a weak variable. We can't be sure that
2200 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002201 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002202 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002203 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002204 }
Richard Smithcecf1842011-11-01 21:06:14 +00002205
Richard Smithd0b4dd62011-12-19 06:19:21 +00002206 // Check that we can fold the initializer. In C++, we will have already done
2207 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002208 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002209 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002210 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002211 Notes.size() + 1) << VD;
2212 Info.Note(VD->getLocation(), diag::note_declared_at);
2213 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002214 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002215 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002216 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217 Notes.size() + 1) << VD;
2218 Info.Note(VD->getLocation(), diag::note_declared_at);
2219 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002220 }
Richard Smith27908702011-10-24 17:54:18 +00002221
Richard Smith3229b742013-05-05 21:17:10 +00002222 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002223 return true;
Richard Smith27908702011-10-24 17:54:18 +00002224}
2225
Richard Smith11562c52011-10-28 17:51:58 +00002226static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002227 Qualifiers Quals = T.getQualifiers();
2228 return Quals.hasConst() && !Quals.hasVolatile();
2229}
2230
Richard Smithe97cbd72011-11-11 04:05:33 +00002231/// Get the base index of the given base class within an APValue representing
2232/// the given derived class.
2233static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2234 const CXXRecordDecl *Base) {
2235 Base = Base->getCanonicalDecl();
2236 unsigned Index = 0;
2237 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2238 E = Derived->bases_end(); I != E; ++I, ++Index) {
2239 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2240 return Index;
2241 }
2242
2243 llvm_unreachable("base class missing from derived class's bases list");
2244}
2245
Richard Smith3da88fa2013-04-26 14:36:30 +00002246/// Extract the value of a character from a string literal.
2247static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2248 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002249 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2250 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2251 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002252 const StringLiteral *S = cast<StringLiteral>(Lit);
2253 const ConstantArrayType *CAT =
2254 Info.Ctx.getAsConstantArrayType(S->getType());
2255 assert(CAT && "string literal isn't an array");
2256 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002257 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002258
2259 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002260 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002261 if (Index < S->getLength())
2262 Value = S->getCodeUnit(Index);
2263 return Value;
2264}
2265
Richard Smith3da88fa2013-04-26 14:36:30 +00002266// Expand a string literal into an array of characters.
2267static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2268 APValue &Result) {
2269 const StringLiteral *S = cast<StringLiteral>(Lit);
2270 const ConstantArrayType *CAT =
2271 Info.Ctx.getAsConstantArrayType(S->getType());
2272 assert(CAT && "string literal isn't an array");
2273 QualType CharType = CAT->getElementType();
2274 assert(CharType->isIntegerType() && "unexpected character type");
2275
2276 unsigned Elts = CAT->getSize().getZExtValue();
2277 Result = APValue(APValue::UninitArray(),
2278 std::min(S->getLength(), Elts), Elts);
2279 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2280 CharType->isUnsignedIntegerType());
2281 if (Result.hasArrayFiller())
2282 Result.getArrayFiller() = APValue(Value);
2283 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2284 Value = S->getCodeUnit(I);
2285 Result.getArrayInitializedElt(I) = APValue(Value);
2286 }
2287}
2288
2289// Expand an array so that it has more than Index filled elements.
2290static void expandArray(APValue &Array, unsigned Index) {
2291 unsigned Size = Array.getArraySize();
2292 assert(Index < Size);
2293
2294 // Always at least double the number of elements for which we store a value.
2295 unsigned OldElts = Array.getArrayInitializedElts();
2296 unsigned NewElts = std::max(Index+1, OldElts * 2);
2297 NewElts = std::min(Size, std::max(NewElts, 8u));
2298
2299 // Copy the data across.
2300 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2301 for (unsigned I = 0; I != OldElts; ++I)
2302 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2303 for (unsigned I = OldElts; I != NewElts; ++I)
2304 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2305 if (NewValue.hasArrayFiller())
2306 NewValue.getArrayFiller() = Array.getArrayFiller();
2307 Array.swap(NewValue);
2308}
2309
Richard Smithb01fe402014-09-16 01:24:02 +00002310/// Determine whether a type would actually be read by an lvalue-to-rvalue
2311/// conversion. If it's of class type, we may assume that the copy operation
2312/// is trivial. Note that this is never true for a union type with fields
2313/// (because the copy always "reads" the active member) and always true for
2314/// a non-class type.
2315static bool isReadByLvalueToRvalueConversion(QualType T) {
2316 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2317 if (!RD || (RD->isUnion() && !RD->field_empty()))
2318 return true;
2319 if (RD->isEmpty())
2320 return false;
2321
2322 for (auto *Field : RD->fields())
2323 if (isReadByLvalueToRvalueConversion(Field->getType()))
2324 return true;
2325
2326 for (auto &BaseSpec : RD->bases())
2327 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2328 return true;
2329
2330 return false;
2331}
2332
2333/// Diagnose an attempt to read from any unreadable field within the specified
2334/// type, which might be a class type.
2335static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2336 QualType T) {
2337 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2338 if (!RD)
2339 return false;
2340
2341 if (!RD->hasMutableFields())
2342 return false;
2343
2344 for (auto *Field : RD->fields()) {
2345 // If we're actually going to read this field in some way, then it can't
2346 // be mutable. If we're in a union, then assigning to a mutable field
2347 // (even an empty one) can change the active member, so that's not OK.
2348 // FIXME: Add core issue number for the union case.
2349 if (Field->isMutable() &&
2350 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002351 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002352 Info.Note(Field->getLocation(), diag::note_declared_at);
2353 return true;
2354 }
2355
2356 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2357 return true;
2358 }
2359
2360 for (auto &BaseSpec : RD->bases())
2361 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2362 return true;
2363
2364 // All mutable fields were empty, and thus not actually read.
2365 return false;
2366}
2367
Richard Smith861b5b52013-05-07 23:34:45 +00002368/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002369enum AccessKinds {
2370 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002371 AK_Assign,
2372 AK_Increment,
2373 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002374};
2375
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002376namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002377/// A handle to a complete object (an object that is not a subobject of
2378/// another object).
2379struct CompleteObject {
2380 /// The value of the complete object.
2381 APValue *Value;
2382 /// The type of the complete object.
2383 QualType Type;
2384
Craig Topper36250ad2014-05-12 05:36:57 +00002385 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002386 CompleteObject(APValue *Value, QualType Type)
2387 : Value(Value), Type(Type) {
2388 assert(Value && "missing value for complete object");
2389 }
2390
Aaron Ballman67347662015-02-15 22:00:28 +00002391 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002392};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002393} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002394
Richard Smith3da88fa2013-04-26 14:36:30 +00002395/// Find the designated sub-object of an rvalue.
2396template<typename SubobjectHandler>
2397typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002398findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002399 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002400 if (Sub.Invalid)
2401 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002402 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002403 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002404 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002405 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002406 << handler.AccessKind;
2407 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002408 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002409 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002410 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002411
Richard Smith3229b742013-05-05 21:17:10 +00002412 APValue *O = Obj.Value;
2413 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002414 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002415
Richard Smithd62306a2011-11-10 06:34:14 +00002416 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002417 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2418 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002419 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002420 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002421 return handler.failed();
2422 }
2423
Richard Smith49ca8aa2013-08-06 07:09:20 +00002424 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002425 // If we are reading an object of class type, there may still be more
2426 // things we need to check: if there are any mutable subobjects, we
2427 // cannot perform this read. (This only happens when performing a trivial
2428 // copy or assignment.)
2429 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2430 diagnoseUnreadableFields(Info, E, ObjType))
2431 return handler.failed();
2432
Richard Smith49ca8aa2013-08-06 07:09:20 +00002433 if (!handler.found(*O, ObjType))
2434 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002435
Richard Smith49ca8aa2013-08-06 07:09:20 +00002436 // If we modified a bit-field, truncate it to the right width.
2437 if (handler.AccessKind != AK_Read &&
2438 LastField && LastField->isBitField() &&
2439 !truncateBitfieldValue(Info, E, *O, LastField))
2440 return false;
2441
2442 return true;
2443 }
2444
Craig Topper36250ad2014-05-12 05:36:57 +00002445 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002446 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002447 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002448 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002449 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002450 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002451 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002452 // Note, it should not be possible to form a pointer with a valid
2453 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002454 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002455 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002456 << handler.AccessKind;
2457 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002459 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002460 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002461
2462 ObjType = CAT->getElementType();
2463
Richard Smith14a94132012-02-17 03:35:37 +00002464 // An array object is represented as either an Array APValue or as an
2465 // LValue which refers to a string literal.
2466 if (O->isLValue()) {
2467 assert(I == N - 1 && "extracting subobject of character?");
2468 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002469 if (handler.AccessKind != AK_Read)
2470 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2471 *O);
2472 else
2473 return handler.foundString(*O, ObjType, Index);
2474 }
2475
2476 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002477 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002478 else if (handler.AccessKind != AK_Read) {
2479 expandArray(*O, Index);
2480 O = &O->getArrayInitializedElt(Index);
2481 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002482 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002483 } else if (ObjType->isAnyComplexType()) {
2484 // Next subobject is a complex number.
2485 uint64_t Index = Sub.Entries[I].ArrayIndex;
2486 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002487 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002488 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 << handler.AccessKind;
2490 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002491 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002492 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002493 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002494
2495 bool WasConstQualified = ObjType.isConstQualified();
2496 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2497 if (WasConstQualified)
2498 ObjType.addConst();
2499
Richard Smith66c96992012-02-18 22:04:06 +00002500 assert(I == N - 1 && "extracting subobject of scalar?");
2501 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002502 return handler.found(Index ? O->getComplexIntImag()
2503 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002504 } else {
2505 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002506 return handler.found(Index ? O->getComplexFloatImag()
2507 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002508 }
Richard Smithd62306a2011-11-10 06:34:14 +00002509 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002510 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002511 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002512 << Field;
2513 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002514 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002515 }
2516
Richard Smithd62306a2011-11-10 06:34:14 +00002517 // Next subobject is a class, struct or union field.
2518 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2519 if (RD->isUnion()) {
2520 const FieldDecl *UnionField = O->getUnionField();
2521 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002522 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002523 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002524 << handler.AccessKind << Field << !UnionField << UnionField;
2525 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002526 }
Richard Smithd62306a2011-11-10 06:34:14 +00002527 O = &O->getUnionValue();
2528 } else
2529 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002530
2531 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002532 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002533 if (WasConstQualified && !Field->isMutable())
2534 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002535
2536 if (ObjType.isVolatileQualified()) {
2537 if (Info.getLangOpts().CPlusPlus) {
2538 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002539 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002540 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002541 Info.Note(Field->getLocation(), diag::note_declared_at);
2542 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002543 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002544 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002545 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002546 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002547
2548 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002549 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002550 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002551 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2552 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2553 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002554
2555 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002556 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 if (WasConstQualified)
2558 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002559 }
2560 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002561}
2562
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002563namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002564struct ExtractSubobjectHandler {
2565 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002566 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002567
2568 static const AccessKinds AccessKind = AK_Read;
2569
2570 typedef bool result_type;
2571 bool failed() { return false; }
2572 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002573 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002574 return true;
2575 }
2576 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002577 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002578 return true;
2579 }
2580 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002581 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002582 return true;
2583 }
2584 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002585 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002586 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2587 return true;
2588 }
2589};
Richard Smith3229b742013-05-05 21:17:10 +00002590} // end anonymous namespace
2591
Richard Smith3da88fa2013-04-26 14:36:30 +00002592const AccessKinds ExtractSubobjectHandler::AccessKind;
2593
2594/// Extract the designated sub-object of an rvalue.
2595static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002596 const CompleteObject &Obj,
2597 const SubobjectDesignator &Sub,
2598 APValue &Result) {
2599 ExtractSubobjectHandler Handler = { Info, Result };
2600 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002601}
2602
Richard Smith3229b742013-05-05 21:17:10 +00002603namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002604struct ModifySubobjectHandler {
2605 EvalInfo &Info;
2606 APValue &NewVal;
2607 const Expr *E;
2608
2609 typedef bool result_type;
2610 static const AccessKinds AccessKind = AK_Assign;
2611
2612 bool checkConst(QualType QT) {
2613 // Assigning to a const object has undefined behavior.
2614 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002615 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002616 return false;
2617 }
2618 return true;
2619 }
2620
2621 bool failed() { return false; }
2622 bool found(APValue &Subobj, QualType SubobjType) {
2623 if (!checkConst(SubobjType))
2624 return false;
2625 // We've been given ownership of NewVal, so just swap it in.
2626 Subobj.swap(NewVal);
2627 return true;
2628 }
2629 bool found(APSInt &Value, QualType SubobjType) {
2630 if (!checkConst(SubobjType))
2631 return false;
2632 if (!NewVal.isInt()) {
2633 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002634 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002635 return false;
2636 }
2637 Value = NewVal.getInt();
2638 return true;
2639 }
2640 bool found(APFloat &Value, QualType SubobjType) {
2641 if (!checkConst(SubobjType))
2642 return false;
2643 Value = NewVal.getFloat();
2644 return true;
2645 }
2646 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2647 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2648 }
2649};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002650} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002651
Richard Smith3229b742013-05-05 21:17:10 +00002652const AccessKinds ModifySubobjectHandler::AccessKind;
2653
Richard Smith3da88fa2013-04-26 14:36:30 +00002654/// Update the designated sub-object of an rvalue to the given value.
2655static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002656 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 const SubobjectDesignator &Sub,
2658 APValue &NewVal) {
2659 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002660 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002661}
2662
Richard Smith84f6dcf2012-02-02 01:16:57 +00002663/// Find the position where two subobject designators diverge, or equivalently
2664/// the length of the common initial subsequence.
2665static unsigned FindDesignatorMismatch(QualType ObjType,
2666 const SubobjectDesignator &A,
2667 const SubobjectDesignator &B,
2668 bool &WasArrayIndex) {
2669 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2670 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002671 if (!ObjType.isNull() &&
2672 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002673 // Next subobject is an array element.
2674 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2675 WasArrayIndex = true;
2676 return I;
2677 }
Richard Smith66c96992012-02-18 22:04:06 +00002678 if (ObjType->isAnyComplexType())
2679 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2680 else
2681 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002682 } else {
2683 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2684 WasArrayIndex = false;
2685 return I;
2686 }
2687 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2688 // Next subobject is a field.
2689 ObjType = FD->getType();
2690 else
2691 // Next subobject is a base class.
2692 ObjType = QualType();
2693 }
2694 }
2695 WasArrayIndex = false;
2696 return I;
2697}
2698
2699/// Determine whether the given subobject designators refer to elements of the
2700/// same array object.
2701static bool AreElementsOfSameArray(QualType ObjType,
2702 const SubobjectDesignator &A,
2703 const SubobjectDesignator &B) {
2704 if (A.Entries.size() != B.Entries.size())
2705 return false;
2706
George Burgess IVa51c4072015-10-16 01:49:01 +00002707 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002708 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2709 // A is a subobject of the array element.
2710 return false;
2711
2712 // If A (and B) designates an array element, the last entry will be the array
2713 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2714 // of length 1' case, and the entire path must match.
2715 bool WasArrayIndex;
2716 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2717 return CommonLength >= A.Entries.size() - IsArray;
2718}
2719
Richard Smith3229b742013-05-05 21:17:10 +00002720/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002721static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2722 AccessKinds AK, const LValue &LVal,
2723 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002724 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002725 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002726 return CompleteObject();
2727 }
2728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002730 if (LVal.CallIndex) {
2731 Frame = Info.getCallFrame(LVal.CallIndex);
2732 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002733 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002734 << AK << LVal.Base.is<const ValueDecl*>();
2735 NoteLValueLocation(Info, LVal.Base);
2736 return CompleteObject();
2737 }
Richard Smith3229b742013-05-05 21:17:10 +00002738 }
2739
2740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2741 // is not a constant expression (even if the object is non-volatile). We also
2742 // apply this rule to C++98, in order to conform to the expected 'volatile'
2743 // semantics.
2744 if (LValType.isVolatileQualified()) {
2745 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002746 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002747 << AK << LValType;
2748 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002749 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002750 return CompleteObject();
2751 }
2752
2753 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002754 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002755 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002756
2757 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2758 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2759 // In C++11, constexpr, non-volatile variables initialized with constant
2760 // expressions are constant expressions too. Inside constexpr functions,
2761 // parameters are constant expressions even if they're non-const.
2762 // In C++1y, objects local to a constant expression (those with a Frame) are
2763 // both readable and writable inside constant expressions.
2764 // In C, such things can also be folded, although they are not ICEs.
2765 const VarDecl *VD = dyn_cast<VarDecl>(D);
2766 if (VD) {
2767 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2768 VD = VDef;
2769 }
2770 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002771 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002772 return CompleteObject();
2773 }
2774
2775 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002776 if (BaseType.isVolatileQualified()) {
2777 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002778 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002779 << AK << 1 << VD;
2780 Info.Note(VD->getLocation(), diag::note_declared_at);
2781 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002782 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002783 }
2784 return CompleteObject();
2785 }
2786
2787 // Unless we're looking at a local variable or argument in a constexpr call,
2788 // the variable we're reading must be const.
2789 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002790 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002791 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2792 // OK, we can read and modify an object if we're in the process of
2793 // evaluating its initializer, because its lifetime began in this
2794 // evaluation.
2795 } else if (AK != AK_Read) {
2796 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002797 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002798 return CompleteObject();
Chandler Carruthd7738fe2016-12-20 08:28:19 +00002799 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002800 // OK, we can read this variable.
2801 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002802 // In OpenCL if a variable is in constant address space it is a const value.
2803 if (!(BaseType.isConstQualified() ||
2804 (Info.getLangOpts().OpenCL &&
2805 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002806 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002807 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002808 Info.Note(VD->getLocation(), diag::note_declared_at);
2809 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002810 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002811 }
2812 return CompleteObject();
2813 }
2814 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2815 // We support folding of const floating-point types, in order to make
2816 // static const data members of such types (supported as an extension)
2817 // more useful.
2818 if (Info.getLangOpts().CPlusPlus11) {
2819 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2820 Info.Note(VD->getLocation(), diag::note_declared_at);
2821 } else {
2822 Info.CCEDiag(E);
2823 }
2824 } else {
2825 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002826 if (Info.checkingPotentialConstantExpression() &&
2827 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2828 // The definition of this variable could be constexpr. We can't
2829 // access it right now, but may be able to in future.
2830 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002832 Info.Note(VD->getLocation(), diag::note_declared_at);
2833 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002834 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002835 }
2836 return CompleteObject();
2837 }
2838 }
2839
2840 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2841 return CompleteObject();
2842 } else {
2843 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2844
2845 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002846 if (const MaterializeTemporaryExpr *MTE =
2847 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2848 assert(MTE->getStorageDuration() == SD_Static &&
2849 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002850
Richard Smithe6c01442013-06-05 00:46:14 +00002851 // Per C++1y [expr.const]p2:
2852 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2853 // - a [...] glvalue of integral or enumeration type that refers to
2854 // a non-volatile const object [...]
2855 // [...]
2856 // - a [...] glvalue of literal type that refers to a non-volatile
2857 // object whose lifetime began within the evaluation of e.
2858 //
2859 // C++11 misses the 'began within the evaluation of e' check and
2860 // instead allows all temporaries, including things like:
2861 // int &&r = 1;
2862 // int x = ++r;
2863 // constexpr int k = r;
2864 // Therefore we use the C++1y rules in C++11 too.
2865 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2866 const ValueDecl *ED = MTE->getExtendingDecl();
2867 if (!(BaseType.isConstQualified() &&
2868 BaseType->isIntegralOrEnumerationType()) &&
2869 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002870 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002871 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2872 return CompleteObject();
2873 }
2874
2875 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2876 assert(BaseVal && "got reference to unevaluated temporary");
2877 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002878 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002879 return CompleteObject();
2880 }
2881 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002882 BaseVal = Frame->getTemporary(Base);
2883 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002884 }
Richard Smith3229b742013-05-05 21:17:10 +00002885
2886 // Volatile temporary objects cannot be accessed in constant expressions.
2887 if (BaseType.isVolatileQualified()) {
2888 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002890 << AK << 0;
2891 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2892 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002893 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002894 }
2895 return CompleteObject();
2896 }
2897 }
2898
Richard Smith7525ff62013-05-09 07:14:00 +00002899 // During the construction of an object, it is not yet 'const'.
2900 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2901 // and this doesn't do quite the right thing for const subobjects of the
2902 // object under construction.
2903 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2904 BaseType = Info.Ctx.getCanonicalType(BaseType);
2905 BaseType.removeLocalConst();
2906 }
2907
Richard Smith6d4c6582013-11-05 22:18:15 +00002908 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002909 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002910 //
2911 // FIXME: Not all local state is mutable. Allow local constant subobjects
2912 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002913 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2914 Info.EvalStatus.HasSideEffects) ||
2915 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002916 return CompleteObject();
2917
2918 return CompleteObject(BaseVal, BaseType);
2919}
2920
Richard Smith243ef902013-05-05 23:31:59 +00002921/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2922/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2923/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002924///
2925/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002926/// \param Conv - The expression for which we are performing the conversion.
2927/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002928/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2929/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002930/// \param LVal - The glvalue on which we are attempting to perform this action.
2931/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002932static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002933 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002934 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002935 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002936 return false;
2937
Richard Smith3229b742013-05-05 21:17:10 +00002938 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002939 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002940 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002941 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2942 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2943 // initializer until now for such expressions. Such an expression can't be
2944 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00002945 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002946 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002947 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002948 }
Richard Smith3229b742013-05-05 21:17:10 +00002949 APValue Lit;
2950 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2951 return false;
2952 CompleteObject LitObj(&Lit, Base->getType());
2953 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002954 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002955 // We represent a string literal array as an lvalue pointing at the
2956 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002957 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002958 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2959 CompleteObject StrObj(&Str, Base->getType());
2960 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002961 }
Richard Smith11562c52011-10-28 17:51:58 +00002962 }
2963
Richard Smith3229b742013-05-05 21:17:10 +00002964 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2965 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002966}
2967
2968/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002969static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002970 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002972 return false;
2973
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002974 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002975 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002976 return false;
2977 }
2978
Richard Smith3229b742013-05-05 21:17:10 +00002979 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2980 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002981}
2982
Richard Smith243ef902013-05-05 23:31:59 +00002983static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2984 return T->isSignedIntegerType() &&
2985 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2986}
2987
2988namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002989struct CompoundAssignSubobjectHandler {
2990 EvalInfo &Info;
2991 const Expr *E;
2992 QualType PromotedLHSType;
2993 BinaryOperatorKind Opcode;
2994 const APValue &RHS;
2995
2996 static const AccessKinds AccessKind = AK_Assign;
2997
2998 typedef bool result_type;
2999
3000 bool checkConst(QualType QT) {
3001 // Assigning to a const object has undefined behavior.
3002 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003003 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003004 return false;
3005 }
3006 return true;
3007 }
3008
3009 bool failed() { return false; }
3010 bool found(APValue &Subobj, QualType SubobjType) {
3011 switch (Subobj.getKind()) {
3012 case APValue::Int:
3013 return found(Subobj.getInt(), SubobjType);
3014 case APValue::Float:
3015 return found(Subobj.getFloat(), SubobjType);
3016 case APValue::ComplexInt:
3017 case APValue::ComplexFloat:
3018 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003019 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003020 return false;
3021 case APValue::LValue:
3022 return foundPointer(Subobj, SubobjType);
3023 default:
3024 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003025 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003026 return false;
3027 }
3028 }
3029 bool found(APSInt &Value, QualType SubobjType) {
3030 if (!checkConst(SubobjType))
3031 return false;
3032
3033 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3034 // We don't support compound assignment on integer-cast-to-pointer
3035 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003037 return false;
3038 }
3039
3040 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3041 SubobjType, Value);
3042 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3043 return false;
3044 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3045 return true;
3046 }
3047 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003048 return checkConst(SubobjType) &&
3049 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3050 Value) &&
3051 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3052 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003053 }
3054 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3055 if (!checkConst(SubobjType))
3056 return false;
3057
3058 QualType PointeeType;
3059 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3060 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003061
3062 if (PointeeType.isNull() || !RHS.isInt() ||
3063 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003065 return false;
3066 }
3067
Richard Smith861b5b52013-05-07 23:34:45 +00003068 int64_t Offset = getExtValue(RHS.getInt());
3069 if (Opcode == BO_Sub)
3070 Offset = -Offset;
3071
3072 LValue LVal;
3073 LVal.setFrom(Info.Ctx, Subobj);
3074 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3075 return false;
3076 LVal.moveInto(Subobj);
3077 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003078 }
3079 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3080 llvm_unreachable("shouldn't encounter string elements here");
3081 }
3082};
3083} // end anonymous namespace
3084
3085const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3086
3087/// Perform a compound assignment of LVal <op>= RVal.
3088static bool handleCompoundAssignment(
3089 EvalInfo &Info, const Expr *E,
3090 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3091 BinaryOperatorKind Opcode, const APValue &RVal) {
3092 if (LVal.Designator.Invalid)
3093 return false;
3094
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003095 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003096 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003097 return false;
3098 }
3099
3100 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3101 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3102 RVal };
3103 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3104}
3105
3106namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003107struct IncDecSubobjectHandler {
3108 EvalInfo &Info;
3109 const Expr *E;
3110 AccessKinds AccessKind;
3111 APValue *Old;
3112
3113 typedef bool result_type;
3114
3115 bool checkConst(QualType QT) {
3116 // Assigning to a const object has undefined behavior.
3117 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003119 return false;
3120 }
3121 return true;
3122 }
3123
3124 bool failed() { return false; }
3125 bool found(APValue &Subobj, QualType SubobjType) {
3126 // Stash the old value. Also clear Old, so we don't clobber it later
3127 // if we're post-incrementing a complex.
3128 if (Old) {
3129 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003130 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003131 }
3132
3133 switch (Subobj.getKind()) {
3134 case APValue::Int:
3135 return found(Subobj.getInt(), SubobjType);
3136 case APValue::Float:
3137 return found(Subobj.getFloat(), SubobjType);
3138 case APValue::ComplexInt:
3139 return found(Subobj.getComplexIntReal(),
3140 SubobjType->castAs<ComplexType>()->getElementType()
3141 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3142 case APValue::ComplexFloat:
3143 return found(Subobj.getComplexFloatReal(),
3144 SubobjType->castAs<ComplexType>()->getElementType()
3145 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3146 case APValue::LValue:
3147 return foundPointer(Subobj, SubobjType);
3148 default:
3149 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003151 return false;
3152 }
3153 }
3154 bool found(APSInt &Value, QualType SubobjType) {
3155 if (!checkConst(SubobjType))
3156 return false;
3157
3158 if (!SubobjType->isIntegerType()) {
3159 // We don't support increment / decrement on integer-cast-to-pointer
3160 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003162 return false;
3163 }
3164
3165 if (Old) *Old = APValue(Value);
3166
3167 // bool arithmetic promotes to int, and the conversion back to bool
3168 // doesn't reduce mod 2^n, so special-case it.
3169 if (SubobjType->isBooleanType()) {
3170 if (AccessKind == AK_Increment)
3171 Value = 1;
3172 else
3173 Value = !Value;
3174 return true;
3175 }
3176
3177 bool WasNegative = Value.isNegative();
3178 if (AccessKind == AK_Increment) {
3179 ++Value;
3180
3181 if (!WasNegative && Value.isNegative() &&
3182 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3183 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003184 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003185 }
3186 } else {
3187 --Value;
3188
3189 if (WasNegative && !Value.isNegative() &&
3190 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3191 unsigned BitWidth = Value.getBitWidth();
3192 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3193 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003194 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003195 }
3196 }
3197 return true;
3198 }
3199 bool found(APFloat &Value, QualType SubobjType) {
3200 if (!checkConst(SubobjType))
3201 return false;
3202
3203 if (Old) *Old = APValue(Value);
3204
3205 APFloat One(Value.getSemantics(), 1);
3206 if (AccessKind == AK_Increment)
3207 Value.add(One, APFloat::rmNearestTiesToEven);
3208 else
3209 Value.subtract(One, APFloat::rmNearestTiesToEven);
3210 return true;
3211 }
3212 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3213 if (!checkConst(SubobjType))
3214 return false;
3215
3216 QualType PointeeType;
3217 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3218 PointeeType = PT->getPointeeType();
3219 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003220 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003221 return false;
3222 }
3223
3224 LValue LVal;
3225 LVal.setFrom(Info.Ctx, Subobj);
3226 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3227 AccessKind == AK_Increment ? 1 : -1))
3228 return false;
3229 LVal.moveInto(Subobj);
3230 return true;
3231 }
3232 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3233 llvm_unreachable("shouldn't encounter string elements here");
3234 }
3235};
3236} // end anonymous namespace
3237
3238/// Perform an increment or decrement on LVal.
3239static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3240 QualType LValType, bool IsIncrement, APValue *Old) {
3241 if (LVal.Designator.Invalid)
3242 return false;
3243
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003244 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003245 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003246 return false;
3247 }
3248
3249 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3250 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3251 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3252 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3253}
3254
Richard Smithe97cbd72011-11-11 04:05:33 +00003255/// Build an lvalue for the object argument of a member function call.
3256static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3257 LValue &This) {
3258 if (Object->getType()->isPointerType())
3259 return EvaluatePointer(Object, This, Info);
3260
3261 if (Object->isGLValue())
3262 return EvaluateLValue(Object, This, Info);
3263
Richard Smithd9f663b2013-04-22 15:31:51 +00003264 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003265 return EvaluateTemporary(Object, This, Info);
3266
Faisal Valie690b7a2016-07-02 22:34:24 +00003267 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003268 return false;
3269}
3270
3271/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3272/// lvalue referring to the result.
3273///
3274/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003275/// \param LV - An lvalue referring to the base of the member pointer.
3276/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003277/// \param IncludeMember - Specifies whether the member itself is included in
3278/// the resulting LValue subobject designator. This is not possible when
3279/// creating a bound member function.
3280/// \return The field or method declaration to which the member pointer refers,
3281/// or 0 if evaluation fails.
3282static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003283 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003284 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003285 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003286 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003287 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003288 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003289 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003290
3291 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3292 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003293 if (!MemPtr.getDecl()) {
3294 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003296 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003297 }
Richard Smith253c2a32012-01-27 01:14:48 +00003298
Richard Smith027bf112011-11-17 22:56:20 +00003299 if (MemPtr.isDerivedMember()) {
3300 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003301 // The end of the derived-to-base path for the base object must match the
3302 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003303 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003304 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003305 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003306 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003307 }
Richard Smith027bf112011-11-17 22:56:20 +00003308 unsigned PathLengthToMember =
3309 LV.Designator.Entries.size() - MemPtr.Path.size();
3310 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3311 const CXXRecordDecl *LVDecl = getAsBaseClass(
3312 LV.Designator.Entries[PathLengthToMember + I]);
3313 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003314 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003315 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003316 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003317 }
Richard Smith027bf112011-11-17 22:56:20 +00003318 }
3319
3320 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003321 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003322 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003323 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003324 } else if (!MemPtr.Path.empty()) {
3325 // Extend the LValue path with the member pointer's path.
3326 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3327 MemPtr.Path.size() + IncludeMember);
3328
3329 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003330 if (const PointerType *PT = LVType->getAs<PointerType>())
3331 LVType = PT->getPointeeType();
3332 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3333 assert(RD && "member pointer access on non-class-type expression");
3334 // The first class in the path is that of the lvalue.
3335 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3336 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003337 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003338 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003339 RD = Base;
3340 }
3341 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003342 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3343 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003344 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003345 }
3346
3347 // Add the member. Note that we cannot build bound member functions here.
3348 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003349 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003350 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003351 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003352 } else if (const IndirectFieldDecl *IFD =
3353 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003354 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003355 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003356 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003357 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003358 }
Richard Smith027bf112011-11-17 22:56:20 +00003359 }
3360
3361 return MemPtr.getDecl();
3362}
3363
Richard Smith84401042013-06-03 05:03:02 +00003364static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3365 const BinaryOperator *BO,
3366 LValue &LV,
3367 bool IncludeMember = true) {
3368 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3369
3370 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003371 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003372 MemberPtr MemPtr;
3373 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3374 }
Craig Topper36250ad2014-05-12 05:36:57 +00003375 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003376 }
3377
3378 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3379 BO->getRHS(), IncludeMember);
3380}
3381
Richard Smith027bf112011-11-17 22:56:20 +00003382/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3383/// the provided lvalue, which currently refers to the base object.
3384static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3385 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003386 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003387 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003388 return false;
3389
Richard Smitha8105bc2012-01-06 16:39:00 +00003390 QualType TargetQT = E->getType();
3391 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3392 TargetQT = PT->getPointeeType();
3393
3394 // Check this cast lands within the final derived-to-base subobject path.
3395 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003396 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003397 << D.MostDerivedType << TargetQT;
3398 return false;
3399 }
3400
Richard Smith027bf112011-11-17 22:56:20 +00003401 // Check the type of the final cast. We don't need to check the path,
3402 // since a cast can only be formed if the path is unique.
3403 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003404 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3405 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003406 if (NewEntriesSize == D.MostDerivedPathLength)
3407 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3408 else
Richard Smith027bf112011-11-17 22:56:20 +00003409 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003410 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003411 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003412 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003413 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003414 }
Richard Smith027bf112011-11-17 22:56:20 +00003415
3416 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003417 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003418}
3419
Mike Stump876387b2009-10-27 22:09:17 +00003420namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003421enum EvalStmtResult {
3422 /// Evaluation failed.
3423 ESR_Failed,
3424 /// Hit a 'return' statement.
3425 ESR_Returned,
3426 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003427 ESR_Succeeded,
3428 /// Hit a 'continue' statement.
3429 ESR_Continue,
3430 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003431 ESR_Break,
3432 /// Still scanning for 'case' or 'default' statement.
3433 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003434};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003435}
Richard Smith254a73d2011-10-28 22:34:42 +00003436
Richard Smith97fcf4b2016-08-14 23:15:52 +00003437static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3438 // We don't need to evaluate the initializer for a static local.
3439 if (!VD->hasLocalStorage())
3440 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003441
Richard Smith97fcf4b2016-08-14 23:15:52 +00003442 LValue Result;
3443 Result.set(VD, Info.CurrentCall->Index);
3444 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003445
Richard Smith97fcf4b2016-08-14 23:15:52 +00003446 const Expr *InitE = VD->getInit();
3447 if (!InitE) {
3448 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3449 << false << VD->getType();
3450 Val = APValue();
3451 return false;
3452 }
Richard Smith51f03172013-06-20 03:00:05 +00003453
Richard Smith97fcf4b2016-08-14 23:15:52 +00003454 if (InitE->isValueDependent())
3455 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003456
Richard Smith97fcf4b2016-08-14 23:15:52 +00003457 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3458 // Wipe out any partially-computed value, to allow tracking that this
3459 // evaluation failed.
3460 Val = APValue();
3461 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003462 }
3463
3464 return true;
3465}
3466
Richard Smith97fcf4b2016-08-14 23:15:52 +00003467static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3468 bool OK = true;
3469
3470 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3471 OK &= EvaluateVarDecl(Info, VD);
3472
3473 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3474 for (auto *BD : DD->bindings())
3475 if (auto *VD = BD->getHoldingVar())
3476 OK &= EvaluateDecl(Info, VD);
3477
3478 return OK;
3479}
3480
3481
Richard Smith4e18ca52013-05-06 05:56:11 +00003482/// Evaluate a condition (either a variable declaration or an expression).
3483static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3484 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003485 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003486 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3487 return false;
3488 return EvaluateAsBooleanCondition(Cond, Result, Info);
3489}
3490
Richard Smith89210072016-04-04 23:29:43 +00003491namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003492/// \brief A location where the result (returned value) of evaluating a
3493/// statement should be stored.
3494struct StmtResult {
3495 /// The APValue that should be filled in with the returned value.
3496 APValue &Value;
3497 /// The location containing the result, if any (used to support RVO).
3498 const LValue *Slot;
3499};
Richard Smith89210072016-04-04 23:29:43 +00003500}
Richard Smith52a980a2015-08-28 02:43:42 +00003501
3502static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003503 const Stmt *S,
3504 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003505
3506/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003507static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003508 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003509 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003510 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003511 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003512 case ESR_Break:
3513 return ESR_Succeeded;
3514 case ESR_Succeeded:
3515 case ESR_Continue:
3516 return ESR_Continue;
3517 case ESR_Failed:
3518 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003519 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003520 return ESR;
3521 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003522 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003523}
3524
Richard Smith496ddcf2013-05-12 17:32:42 +00003525/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003526static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003527 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003528 BlockScopeRAII Scope(Info);
3529
Richard Smith496ddcf2013-05-12 17:32:42 +00003530 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003531 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003532 {
3533 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003534 if (const Stmt *Init = SS->getInit()) {
3535 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3536 if (ESR != ESR_Succeeded)
3537 return ESR;
3538 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003539 if (SS->getConditionVariable() &&
3540 !EvaluateDecl(Info, SS->getConditionVariable()))
3541 return ESR_Failed;
3542 if (!EvaluateInteger(SS->getCond(), Value, Info))
3543 return ESR_Failed;
3544 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003545
3546 // Find the switch case corresponding to the value of the condition.
3547 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003548 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003549 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3550 SC = SC->getNextSwitchCase()) {
3551 if (isa<DefaultStmt>(SC)) {
3552 Found = SC;
3553 continue;
3554 }
3555
3556 const CaseStmt *CS = cast<CaseStmt>(SC);
3557 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3558 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3559 : LHS;
3560 if (LHS <= Value && Value <= RHS) {
3561 Found = SC;
3562 break;
3563 }
3564 }
3565
3566 if (!Found)
3567 return ESR_Succeeded;
3568
3569 // Search the switch body for the switch case and evaluate it from there.
3570 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3571 case ESR_Break:
3572 return ESR_Succeeded;
3573 case ESR_Succeeded:
3574 case ESR_Continue:
3575 case ESR_Failed:
3576 case ESR_Returned:
3577 return ESR;
3578 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003579 // This can only happen if the switch case is nested within a statement
3580 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003581 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003582 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003583 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003584 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003585}
3586
Richard Smith254a73d2011-10-28 22:34:42 +00003587// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003588static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003589 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003590 if (!Info.nextStep(S))
3591 return ESR_Failed;
3592
Richard Smith496ddcf2013-05-12 17:32:42 +00003593 // If we're hunting down a 'case' or 'default' label, recurse through
3594 // substatements until we hit the label.
3595 if (Case) {
3596 // FIXME: We don't start the lifetime of objects whose initialization we
3597 // jump over. However, such objects must be of class type with a trivial
3598 // default constructor that initialize all subobjects, so must be empty,
3599 // so this almost never matters.
3600 switch (S->getStmtClass()) {
3601 case Stmt::CompoundStmtClass:
3602 // FIXME: Precompute which substatement of a compound statement we
3603 // would jump to, and go straight there rather than performing a
3604 // linear scan each time.
3605 case Stmt::LabelStmtClass:
3606 case Stmt::AttributedStmtClass:
3607 case Stmt::DoStmtClass:
3608 break;
3609
3610 case Stmt::CaseStmtClass:
3611 case Stmt::DefaultStmtClass:
3612 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003613 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003614 break;
3615
3616 case Stmt::IfStmtClass: {
3617 // FIXME: Precompute which side of an 'if' we would jump to, and go
3618 // straight there rather than scanning both sides.
3619 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620
3621 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3622 // preceded by our switch label.
3623 BlockScopeRAII Scope(Info);
3624
Richard Smith496ddcf2013-05-12 17:32:42 +00003625 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3626 if (ESR != ESR_CaseNotFound || !IS->getElse())
3627 return ESR;
3628 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3629 }
3630
3631 case Stmt::WhileStmtClass: {
3632 EvalStmtResult ESR =
3633 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3634 if (ESR != ESR_Continue)
3635 return ESR;
3636 break;
3637 }
3638
3639 case Stmt::ForStmtClass: {
3640 const ForStmt *FS = cast<ForStmt>(S);
3641 EvalStmtResult ESR =
3642 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3643 if (ESR != ESR_Continue)
3644 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003645 if (FS->getInc()) {
3646 FullExpressionRAII IncScope(Info);
3647 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3648 return ESR_Failed;
3649 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003650 break;
3651 }
3652
3653 case Stmt::DeclStmtClass:
3654 // FIXME: If the variable has initialization that can't be jumped over,
3655 // bail out of any immediately-surrounding compound-statement too.
3656 default:
3657 return ESR_CaseNotFound;
3658 }
3659 }
3660
Richard Smith254a73d2011-10-28 22:34:42 +00003661 switch (S->getStmtClass()) {
3662 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003663 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003664 // Don't bother evaluating beyond an expression-statement which couldn't
3665 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003666 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003667 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003668 return ESR_Failed;
3669 return ESR_Succeeded;
3670 }
3671
Faisal Valie690b7a2016-07-02 22:34:24 +00003672 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003673 return ESR_Failed;
3674
3675 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003676 return ESR_Succeeded;
3677
Richard Smithd9f663b2013-04-22 15:31:51 +00003678 case Stmt::DeclStmtClass: {
3679 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003680 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003681 // Each declaration initialization is its own full-expression.
3682 // FIXME: This isn't quite right; if we're performing aggregate
3683 // initialization, each braced subexpression is its own full-expression.
3684 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003685 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003686 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003687 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003688 return ESR_Succeeded;
3689 }
3690
Richard Smith357362d2011-12-13 06:39:58 +00003691 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003692 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003693 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003694 if (RetExpr &&
3695 !(Result.Slot
3696 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3697 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003698 return ESR_Failed;
3699 return ESR_Returned;
3700 }
Richard Smith254a73d2011-10-28 22:34:42 +00003701
3702 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003703 BlockScopeRAII Scope(Info);
3704
Richard Smith254a73d2011-10-28 22:34:42 +00003705 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003706 for (const auto *BI : CS->body()) {
3707 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003708 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003709 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003710 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003711 return ESR;
3712 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003713 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003714 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003715
3716 case Stmt::IfStmtClass: {
3717 const IfStmt *IS = cast<IfStmt>(S);
3718
3719 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003720 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003721 if (const Stmt *Init = IS->getInit()) {
3722 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3723 if (ESR != ESR_Succeeded)
3724 return ESR;
3725 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003726 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003727 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003728 return ESR_Failed;
3729
3730 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3731 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3732 if (ESR != ESR_Succeeded)
3733 return ESR;
3734 }
3735 return ESR_Succeeded;
3736 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003737
3738 case Stmt::WhileStmtClass: {
3739 const WhileStmt *WS = cast<WhileStmt>(S);
3740 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003741 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003742 bool Continue;
3743 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3744 Continue))
3745 return ESR_Failed;
3746 if (!Continue)
3747 break;
3748
3749 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3750 if (ESR != ESR_Continue)
3751 return ESR;
3752 }
3753 return ESR_Succeeded;
3754 }
3755
3756 case Stmt::DoStmtClass: {
3757 const DoStmt *DS = cast<DoStmt>(S);
3758 bool Continue;
3759 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003760 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003761 if (ESR != ESR_Continue)
3762 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003763 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003764
Richard Smith08d6a2c2013-07-24 07:11:57 +00003765 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003766 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3767 return ESR_Failed;
3768 } while (Continue);
3769 return ESR_Succeeded;
3770 }
3771
3772 case Stmt::ForStmtClass: {
3773 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003774 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003775 if (FS->getInit()) {
3776 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3777 if (ESR != ESR_Succeeded)
3778 return ESR;
3779 }
3780 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003781 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003782 bool Continue = true;
3783 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3784 FS->getCond(), Continue))
3785 return ESR_Failed;
3786 if (!Continue)
3787 break;
3788
3789 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3790 if (ESR != ESR_Continue)
3791 return ESR;
3792
Richard Smith08d6a2c2013-07-24 07:11:57 +00003793 if (FS->getInc()) {
3794 FullExpressionRAII IncScope(Info);
3795 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3796 return ESR_Failed;
3797 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 }
3799 return ESR_Succeeded;
3800 }
3801
Richard Smith896e0d72013-05-06 06:51:17 +00003802 case Stmt::CXXForRangeStmtClass: {
3803 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003804 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003805
3806 // Initialize the __range variable.
3807 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3808 if (ESR != ESR_Succeeded)
3809 return ESR;
3810
3811 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003812 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3813 if (ESR != ESR_Succeeded)
3814 return ESR;
3815 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003816 if (ESR != ESR_Succeeded)
3817 return ESR;
3818
3819 while (true) {
3820 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003821 {
3822 bool Continue = true;
3823 FullExpressionRAII CondExpr(Info);
3824 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3825 return ESR_Failed;
3826 if (!Continue)
3827 break;
3828 }
Richard Smith896e0d72013-05-06 06:51:17 +00003829
3830 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003831 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003832 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3833 if (ESR != ESR_Succeeded)
3834 return ESR;
3835
3836 // Loop body.
3837 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3838 if (ESR != ESR_Continue)
3839 return ESR;
3840
3841 // Increment: ++__begin
3842 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3843 return ESR_Failed;
3844 }
3845
3846 return ESR_Succeeded;
3847 }
3848
Richard Smith496ddcf2013-05-12 17:32:42 +00003849 case Stmt::SwitchStmtClass:
3850 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3851
Richard Smith4e18ca52013-05-06 05:56:11 +00003852 case Stmt::ContinueStmtClass:
3853 return ESR_Continue;
3854
3855 case Stmt::BreakStmtClass:
3856 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003857
3858 case Stmt::LabelStmtClass:
3859 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3860
3861 case Stmt::AttributedStmtClass:
3862 // As a general principle, C++11 attributes can be ignored without
3863 // any semantic impact.
3864 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3865 Case);
3866
3867 case Stmt::CaseStmtClass:
3868 case Stmt::DefaultStmtClass:
3869 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003870 }
3871}
3872
Richard Smithcc36f692011-12-22 02:22:31 +00003873/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3874/// default constructor. If so, we'll fold it whether or not it's marked as
3875/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3876/// so we need special handling.
3877static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003878 const CXXConstructorDecl *CD,
3879 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003880 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3881 return false;
3882
Richard Smith66e05fe2012-01-18 05:21:49 +00003883 // Value-initialization does not call a trivial default constructor, so such a
3884 // call is a core constant expression whether or not the constructor is
3885 // constexpr.
3886 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003887 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003888 // FIXME: If DiagDecl is an implicitly-declared special member function,
3889 // we should be much more explicit about why it's not constexpr.
3890 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3891 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3892 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003893 } else {
3894 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3895 }
3896 }
3897 return true;
3898}
3899
Richard Smith357362d2011-12-13 06:39:58 +00003900/// CheckConstexprFunction - Check that a function can be called in a constant
3901/// expression.
3902static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3903 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003904 const FunctionDecl *Definition,
3905 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003906 // Potential constant expressions can contain calls to declared, but not yet
3907 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003908 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003909 Declaration->isConstexpr())
3910 return false;
3911
Richard Smith0838f3a2013-05-14 05:18:44 +00003912 // Bail out with no diagnostic if the function declaration itself is invalid.
3913 // We will have produced a relevant diagnostic while parsing it.
3914 if (Declaration->isInvalidDecl())
3915 return false;
3916
Richard Smith357362d2011-12-13 06:39:58 +00003917 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003918 if (Definition && Definition->isConstexpr() &&
3919 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003920 return true;
3921
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003922 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003923 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003924
Richard Smith5179eb72016-06-28 19:03:57 +00003925 // If this function is not constexpr because it is an inherited
3926 // non-constexpr constructor, diagnose that directly.
3927 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3928 if (CD && CD->isInheritingConstructor()) {
3929 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3930 if (!Inherited->isConstexpr())
3931 DiagDecl = CD = Inherited;
3932 }
3933
3934 // FIXME: If DiagDecl is an implicitly-declared special member function
3935 // or an inheriting constructor, we should be much more explicit about why
3936 // it's not constexpr.
3937 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003938 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003939 << CD->getInheritedConstructor().getConstructor()->getParent();
3940 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003941 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003942 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003943 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3944 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003945 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003946 }
3947 return false;
3948}
3949
Richard Smithbe6dd812014-11-19 21:27:17 +00003950/// Determine if a class has any fields that might need to be copied by a
3951/// trivial copy or move operation.
3952static bool hasFields(const CXXRecordDecl *RD) {
3953 if (!RD || RD->isEmpty())
3954 return false;
3955 for (auto *FD : RD->fields()) {
3956 if (FD->isUnnamedBitfield())
3957 continue;
3958 return true;
3959 }
3960 for (auto &Base : RD->bases())
3961 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3962 return true;
3963 return false;
3964}
3965
Richard Smithd62306a2011-11-10 06:34:14 +00003966namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003967typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003968}
3969
3970/// EvaluateArgs - Evaluate the arguments to a function call.
3971static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3972 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003973 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003974 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003975 I != E; ++I) {
3976 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3977 // If we're checking for a potential constant expression, evaluate all
3978 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003979 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003980 return false;
3981 Success = false;
3982 }
3983 }
3984 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003985}
3986
Richard Smith254a73d2011-10-28 22:34:42 +00003987/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003988static bool HandleFunctionCall(SourceLocation CallLoc,
3989 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003990 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003991 EvalInfo &Info, APValue &Result,
3992 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003993 ArgVector ArgValues(Args.size());
3994 if (!EvaluateArgs(Args, ArgValues, Info))
3995 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003996
Richard Smith253c2a32012-01-27 01:14:48 +00003997 if (!Info.CheckCallLimit(CallLoc))
3998 return false;
3999
4000 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004001
4002 // For a trivial copy or move assignment, perform an APValue copy. This is
4003 // essential for unions, where the operations performed by the assignment
4004 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004005 //
4006 // Skip this for non-union classes with no fields; in that case, the defaulted
4007 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004008 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004009 if (MD && MD->isDefaulted() &&
4010 (MD->getParent()->isUnion() ||
4011 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004012 assert(This &&
4013 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4014 LValue RHS;
4015 RHS.setFrom(Info.Ctx, ArgValues[0]);
4016 APValue RHSValue;
4017 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4018 RHS, RHSValue))
4019 return false;
4020 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4021 RHSValue))
4022 return false;
4023 This->moveInto(Result);
4024 return true;
4025 }
4026
Richard Smith52a980a2015-08-28 02:43:42 +00004027 StmtResult Ret = {Result, ResultSlot};
4028 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004029 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004030 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004031 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004032 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004033 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004034 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004035}
4036
Richard Smithd62306a2011-11-10 06:34:14 +00004037/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004038static bool HandleConstructorCall(const Expr *E, const LValue &This,
4039 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004040 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004041 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004042 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004043 if (!Info.CheckCallLimit(CallLoc))
4044 return false;
4045
Richard Smith3607ffe2012-02-13 03:54:03 +00004046 const CXXRecordDecl *RD = Definition->getParent();
4047 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004048 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004049 return false;
4050 }
4051
Richard Smith5179eb72016-06-28 19:03:57 +00004052 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004053
Richard Smith52a980a2015-08-28 02:43:42 +00004054 // FIXME: Creating an APValue just to hold a nonexistent return value is
4055 // wasteful.
4056 APValue RetVal;
4057 StmtResult Ret = {RetVal, nullptr};
4058
Richard Smith5179eb72016-06-28 19:03:57 +00004059 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004060 if (Definition->isDelegatingConstructor()) {
4061 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004062 {
4063 FullExpressionRAII InitScope(Info);
4064 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4065 return false;
4066 }
Richard Smith52a980a2015-08-28 02:43:42 +00004067 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004068 }
4069
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004070 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004071 // essential for unions (or classes with anonymous union members), where the
4072 // operations performed by the constructor cannot be represented by
4073 // ctor-initializers.
4074 //
4075 // Skip this for empty non-union classes; we should not perform an
4076 // lvalue-to-rvalue conversion on them because their copy constructor does not
4077 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004078 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004079 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004080 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004081 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004082 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004083 return handleLValueToRValueConversion(
4084 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4085 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004086 }
4087
4088 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004089 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004090 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004091 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004092
John McCalld7bca762012-05-01 00:38:49 +00004093 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004094 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4095
Richard Smith08d6a2c2013-07-24 07:11:57 +00004096 // A scope for temporaries lifetime-extended by reference members.
4097 BlockScopeRAII LifetimeExtendedScope(Info);
4098
Richard Smith253c2a32012-01-27 01:14:48 +00004099 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004100 unsigned BasesSeen = 0;
4101#ifndef NDEBUG
4102 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4103#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004104 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004105 LValue Subobject = This;
4106 APValue *Value = &Result;
4107
4108 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004109 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004110 if (I->isBaseInitializer()) {
4111 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004112#ifndef NDEBUG
4113 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004114 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004115 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4116 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4117 "base class initializers not in expected order");
4118 ++BaseIt;
4119#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004120 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004121 BaseType->getAsCXXRecordDecl(), &Layout))
4122 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004123 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004124 } else if ((FD = I->getMember())) {
4125 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004126 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004127 if (RD->isUnion()) {
4128 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004129 Value = &Result.getUnionValue();
4130 } else {
4131 Value = &Result.getStructField(FD->getFieldIndex());
4132 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004133 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004134 // Walk the indirect field decl's chain to find the object to initialize,
4135 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004136 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004137 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004138 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4139 // Switch the union field if it differs. This happens if we had
4140 // preceding zero-initialization, and we're now initializing a union
4141 // subobject other than the first.
4142 // FIXME: In this case, the values of the other subobjects are
4143 // specified, since zero-initialization sets all padding bits to zero.
4144 if (Value->isUninit() ||
4145 (Value->isUnion() && Value->getUnionField() != FD)) {
4146 if (CD->isUnion())
4147 *Value = APValue(FD);
4148 else
4149 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004150 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004151 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004152 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004153 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004154 if (CD->isUnion())
4155 Value = &Value->getUnionValue();
4156 else
4157 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004158 }
Richard Smithd62306a2011-11-10 06:34:14 +00004159 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004160 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004161 }
Richard Smith253c2a32012-01-27 01:14:48 +00004162
Richard Smith08d6a2c2013-07-24 07:11:57 +00004163 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004164 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4165 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004166 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004167 // If we're checking for a potential constant expression, evaluate all
4168 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004169 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004170 return false;
4171 Success = false;
4172 }
Richard Smithd62306a2011-11-10 06:34:14 +00004173 }
4174
Richard Smithd9f663b2013-04-22 15:31:51 +00004175 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004176 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004177}
4178
Richard Smith5179eb72016-06-28 19:03:57 +00004179static bool HandleConstructorCall(const Expr *E, const LValue &This,
4180 ArrayRef<const Expr*> Args,
4181 const CXXConstructorDecl *Definition,
4182 EvalInfo &Info, APValue &Result) {
4183 ArgVector ArgValues(Args.size());
4184 if (!EvaluateArgs(Args, ArgValues, Info))
4185 return false;
4186
4187 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4188 Info, Result);
4189}
4190
Eli Friedman9a156e52008-11-12 09:44:48 +00004191//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004192// Generic Evaluation
4193//===----------------------------------------------------------------------===//
4194namespace {
4195
Aaron Ballman68af21c2014-01-03 19:26:43 +00004196template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004197class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004198 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004199private:
Richard Smith52a980a2015-08-28 02:43:42 +00004200 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004201 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004202 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004203 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004204 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004205 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004206 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004207
Richard Smith17100ba2012-02-16 02:46:34 +00004208 // Check whether a conditional operator with a non-constant condition is a
4209 // potential constant expression. If neither arm is a potential constant
4210 // expression, then the conditional operator is not either.
4211 template<typename ConditionalOperator>
4212 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004213 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004214
4215 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004216 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004217 {
Richard Smith17100ba2012-02-16 02:46:34 +00004218 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004219 StmtVisitorTy::Visit(E->getFalseExpr());
4220 if (Diag.empty())
4221 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004222 }
Richard Smith17100ba2012-02-16 02:46:34 +00004223
George Burgess IV8c892b52016-05-25 22:31:54 +00004224 {
4225 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004226 Diag.clear();
4227 StmtVisitorTy::Visit(E->getTrueExpr());
4228 if (Diag.empty())
4229 return;
4230 }
4231
4232 Error(E, diag::note_constexpr_conditional_never_const);
4233 }
4234
4235
4236 template<typename ConditionalOperator>
4237 bool HandleConditionalOperator(const ConditionalOperator *E) {
4238 bool BoolResult;
4239 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004240 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004241 CheckPotentialConstantConditional(E);
4242 return false;
4243 }
4244
4245 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4246 return StmtVisitorTy::Visit(EvalExpr);
4247 }
4248
Peter Collingbournee9200682011-05-13 03:29:01 +00004249protected:
4250 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004251 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004252 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4253
Richard Smith92b1ce02011-12-12 09:28:41 +00004254 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004255 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 }
4257
Aaron Ballman68af21c2014-01-03 19:26:43 +00004258 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004259
4260public:
4261 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4262
4263 EvalInfo &getEvalInfo() { return Info; }
4264
Richard Smithf57d8cb2011-12-09 22:58:01 +00004265 /// Report an evaluation error. This should only be called when an error is
4266 /// first discovered. When propagating an error, just return false.
4267 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004268 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return false;
4270 }
4271 bool Error(const Expr *E) {
4272 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4273 }
4274
Aaron Ballman68af21c2014-01-03 19:26:43 +00004275 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004276 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004277 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004278 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004279 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004280 }
4281
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004283 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004284 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004285 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004286 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004287 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004288 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004289 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004290 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004291 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004292 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004293 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004294 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004295 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004296 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004297 // The initializer may not have been parsed yet, or might be erroneous.
4298 if (!E->getExpr())
4299 return Error(E);
4300 return StmtVisitorTy::Visit(E->getExpr());
4301 }
Richard Smith5894a912011-12-19 22:12:41 +00004302 // We cannot create any objects for which cleanups are required, so there is
4303 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004304 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004305 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004306
Aaron Ballman68af21c2014-01-03 19:26:43 +00004307 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004308 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4309 return static_cast<Derived*>(this)->VisitCastExpr(E);
4310 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004311 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004312 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4313 return static_cast<Derived*>(this)->VisitCastExpr(E);
4314 }
4315
Aaron Ballman68af21c2014-01-03 19:26:43 +00004316 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004317 switch (E->getOpcode()) {
4318 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004319 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004320
4321 case BO_Comma:
4322 VisitIgnoredValue(E->getLHS());
4323 return StmtVisitorTy::Visit(E->getRHS());
4324
4325 case BO_PtrMemD:
4326 case BO_PtrMemI: {
4327 LValue Obj;
4328 if (!HandleMemberPointerAccess(Info, E, Obj))
4329 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004330 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004331 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004332 return false;
4333 return DerivedSuccess(Result, E);
4334 }
4335 }
4336 }
4337
Aaron Ballman68af21c2014-01-03 19:26:43 +00004338 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004339 // Evaluate and cache the common expression. We treat it as a temporary,
4340 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004341 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004342 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004343 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004344
Richard Smith17100ba2012-02-16 02:46:34 +00004345 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004346 }
4347
Aaron Ballman68af21c2014-01-03 19:26:43 +00004348 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004349 bool IsBcpCall = false;
4350 // If the condition (ignoring parens) is a __builtin_constant_p call,
4351 // the result is a constant expression if it can be folded without
4352 // side-effects. This is an important GNU extension. See GCC PR38377
4353 // for discussion.
4354 if (const CallExpr *CallCE =
4355 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004356 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004357 IsBcpCall = true;
4358
4359 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4360 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004361 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004362 return false;
4363
Richard Smith6d4c6582013-11-05 22:18:15 +00004364 FoldConstant Fold(Info, IsBcpCall);
4365 if (!HandleConditionalOperator(E)) {
4366 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004367 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004368 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004369
4370 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004371 }
4372
Aaron Ballman68af21c2014-01-03 19:26:43 +00004373 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004374 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4375 return DerivedSuccess(*Value, E);
4376
4377 const Expr *Source = E->getSourceExpr();
4378 if (!Source)
4379 return Error(E);
4380 if (Source == E) { // sanity checking.
4381 assert(0 && "OpaqueValueExpr recursively refers to itself");
4382 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004383 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004384 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004385 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004386
Aaron Ballman68af21c2014-01-03 19:26:43 +00004387 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004388 APValue Result;
4389 if (!handleCallExpr(E, Result, nullptr))
4390 return false;
4391 return DerivedSuccess(Result, E);
4392 }
4393
4394 bool handleCallExpr(const CallExpr *E, APValue &Result,
4395 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004396 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004397 QualType CalleeType = Callee->getType();
4398
Craig Topper36250ad2014-05-12 05:36:57 +00004399 const FunctionDecl *FD = nullptr;
4400 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004401 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004402 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004403
Richard Smithe97cbd72011-11-11 04:05:33 +00004404 // Extract function decl and 'this' pointer from the callee.
4405 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004406 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004407 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4408 // Explicit bound member calls, such as x.f() or p->g();
4409 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004410 return false;
4411 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004412 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004413 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004414 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4415 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4417 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004418 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004419 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004420 return Error(Callee);
4421
4422 FD = dyn_cast<FunctionDecl>(Member);
4423 if (!FD)
4424 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004425 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004426 LValue Call;
4427 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004428 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004429
Richard Smitha8105bc2012-01-06 16:39:00 +00004430 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004431 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004432 FD = dyn_cast_or_null<FunctionDecl>(
4433 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004434 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004435 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004436
4437 // Overloaded operator calls to member functions are represented as normal
4438 // calls with '*this' as the first argument.
4439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4440 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004441 // FIXME: When selecting an implicit conversion for an overloaded
4442 // operator delete, we sometimes try to evaluate calls to conversion
4443 // operators without a 'this' parameter!
4444 if (Args.empty())
4445 return Error(E);
4446
Richard Smithe97cbd72011-11-11 04:05:33 +00004447 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4448 return false;
4449 This = &ThisVal;
4450 Args = Args.slice(1);
4451 }
4452
4453 // Don't call function pointers which have been cast to some other type.
Richard Smithdfe85e22016-12-15 02:35:39 +00004454 // Per DR (no number yet), the caller and callee can differ in noexcept.
4455 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4456 CalleeType->getPointeeType(), FD->getType())) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004457 return Error(E);
Richard Smithdfe85e22016-12-15 02:35:39 +00004458 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004459 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004460 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004461
Richard Smith47b34932012-02-01 02:39:43 +00004462 if (This && !This->checkSubobject(Info, E, CSK_This))
4463 return false;
4464
Richard Smith3607ffe2012-02-13 03:54:03 +00004465 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4466 // calls to such functions in constant expressions.
4467 if (This && !HasQualifier &&
4468 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4469 return Error(E, diag::note_constexpr_virtual_call);
4470
Craig Topper36250ad2014-05-12 05:36:57 +00004471 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004472 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004473
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004474 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004475 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4476 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004477 return false;
4478
Richard Smith52a980a2015-08-28 02:43:42 +00004479 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004480 }
4481
Aaron Ballman68af21c2014-01-03 19:26:43 +00004482 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004483 return StmtVisitorTy::Visit(E->getInitializer());
4484 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004485 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004486 if (E->getNumInits() == 0)
4487 return DerivedZeroInitialization(E);
4488 if (E->getNumInits() == 1)
4489 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004490 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004491 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004493 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004494 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004495 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004496 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004497 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004498 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004499 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004500 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004501
Richard Smithd62306a2011-11-10 06:34:14 +00004502 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004503 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004504 assert(!E->isArrow() && "missing call to bound member function?");
4505
Richard Smith2e312c82012-03-03 22:46:17 +00004506 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004507 if (!Evaluate(Val, Info, E->getBase()))
4508 return false;
4509
4510 QualType BaseTy = E->getBase()->getType();
4511
4512 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004513 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004514 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004515 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004516 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4517
Richard Smith3229b742013-05-05 21:17:10 +00004518 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004519 SubobjectDesignator Designator(BaseTy);
4520 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004521
Richard Smith3229b742013-05-05 21:17:10 +00004522 APValue Result;
4523 return extractSubobject(Info, E, Obj, Designator, Result) &&
4524 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004525 }
4526
Aaron Ballman68af21c2014-01-03 19:26:43 +00004527 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004528 switch (E->getCastKind()) {
4529 default:
4530 break;
4531
Richard Smitha23ab512013-05-23 00:30:41 +00004532 case CK_AtomicToNonAtomic: {
4533 APValue AtomicVal;
4534 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4535 return false;
4536 return DerivedSuccess(AtomicVal, E);
4537 }
4538
Richard Smith11562c52011-10-28 17:51:58 +00004539 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004540 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004541 return StmtVisitorTy::Visit(E->getSubExpr());
4542
4543 case CK_LValueToRValue: {
4544 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004545 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4546 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004547 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004548 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004549 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004550 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004551 return false;
4552 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004553 }
4554 }
4555
Richard Smithf57d8cb2011-12-09 22:58:01 +00004556 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004557 }
4558
Aaron Ballman68af21c2014-01-03 19:26:43 +00004559 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004560 return VisitUnaryPostIncDec(UO);
4561 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004562 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004563 return VisitUnaryPostIncDec(UO);
4564 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004565 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004566 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004567 return Error(UO);
4568
4569 LValue LVal;
4570 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4571 return false;
4572 APValue RVal;
4573 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4574 UO->isIncrementOp(), &RVal))
4575 return false;
4576 return DerivedSuccess(RVal, UO);
4577 }
4578
Aaron Ballman68af21c2014-01-03 19:26:43 +00004579 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004580 // We will have checked the full-expressions inside the statement expression
4581 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004582 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004583 return Error(E);
4584
Richard Smith08d6a2c2013-07-24 07:11:57 +00004585 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004586 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004587 if (CS->body_empty())
4588 return true;
4589
Richard Smith51f03172013-06-20 03:00:05 +00004590 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4591 BE = CS->body_end();
4592 /**/; ++BI) {
4593 if (BI + 1 == BE) {
4594 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4595 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004596 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004597 diag::note_constexpr_stmt_expr_unsupported);
4598 return false;
4599 }
4600 return this->Visit(FinalExpr);
4601 }
4602
4603 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004604 StmtResult Result = { ReturnValue, nullptr };
4605 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004606 if (ESR != ESR_Succeeded) {
4607 // FIXME: If the statement-expression terminated due to 'return',
4608 // 'break', or 'continue', it would be nice to propagate that to
4609 // the outer statement evaluation rather than bailing out.
4610 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004611 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004612 diag::note_constexpr_stmt_expr_unsupported);
4613 return false;
4614 }
4615 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004616
4617 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004618 }
4619
Richard Smith4a678122011-10-24 18:44:57 +00004620 /// Visit a value which is evaluated, but whose value is ignored.
4621 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004622 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004623 }
David Majnemere9807b22016-02-26 04:23:19 +00004624
4625 /// Potentially visit a MemberExpr's base expression.
4626 void VisitIgnoredBaseExpression(const Expr *E) {
4627 // While MSVC doesn't evaluate the base expression, it does diagnose the
4628 // presence of side-effecting behavior.
4629 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4630 return;
4631 VisitIgnoredValue(E);
4632 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004633};
4634
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004635}
Peter Collingbournee9200682011-05-13 03:29:01 +00004636
4637//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004638// Common base class for lvalue and temporary evaluation.
4639//===----------------------------------------------------------------------===//
4640namespace {
4641template<class Derived>
4642class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004643 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004644protected:
4645 LValue &Result;
4646 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004647 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004648
4649 bool Success(APValue::LValueBase B) {
4650 Result.set(B);
4651 return true;
4652 }
4653
4654public:
4655 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4656 ExprEvaluatorBaseTy(Info), Result(Result) {}
4657
Richard Smith2e312c82012-03-03 22:46:17 +00004658 bool Success(const APValue &V, const Expr *E) {
4659 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004660 return true;
4661 }
Richard Smith027bf112011-11-17 22:56:20 +00004662
Richard Smith027bf112011-11-17 22:56:20 +00004663 bool VisitMemberExpr(const MemberExpr *E) {
4664 // Handle non-static data members.
4665 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004666 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004667 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004668 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004669 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004670 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004671 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004672 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004673 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004674 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004675 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004676 BaseTy = E->getBase()->getType();
4677 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004678 if (!EvalOK) {
4679 if (!this->Info.allowInvalidBaseExpr())
4680 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004681 Result.setInvalid(E);
4682 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004683 }
Richard Smith027bf112011-11-17 22:56:20 +00004684
Richard Smith1b78b3d2012-01-25 22:15:11 +00004685 const ValueDecl *MD = E->getMemberDecl();
4686 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4687 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4688 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4689 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004690 if (!HandleLValueMember(this->Info, E, Result, FD))
4691 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004692 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004693 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4694 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004695 } else
4696 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004697
Richard Smith1b78b3d2012-01-25 22:15:11 +00004698 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004699 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004700 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004701 RefValue))
4702 return false;
4703 return Success(RefValue, E);
4704 }
4705 return true;
4706 }
4707
4708 bool VisitBinaryOperator(const BinaryOperator *E) {
4709 switch (E->getOpcode()) {
4710 default:
4711 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4712
4713 case BO_PtrMemD:
4714 case BO_PtrMemI:
4715 return HandleMemberPointerAccess(this->Info, E, Result);
4716 }
4717 }
4718
4719 bool VisitCastExpr(const CastExpr *E) {
4720 switch (E->getCastKind()) {
4721 default:
4722 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4723
4724 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004725 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004726 if (!this->Visit(E->getSubExpr()))
4727 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004728
4729 // Now figure out the necessary offset to add to the base LV to get from
4730 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004731 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4732 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004733 }
4734 }
4735};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004736}
Richard Smith027bf112011-11-17 22:56:20 +00004737
4738//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004739// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004740//
4741// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4742// function designators (in C), decl references to void objects (in C), and
4743// temporaries (if building with -Wno-address-of-temporary).
4744//
4745// LValue evaluation produces values comprising a base expression of one of the
4746// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004747// - Declarations
4748// * VarDecl
4749// * FunctionDecl
4750// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004751// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004752// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004753// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004754// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004755// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004756// * ObjCEncodeExpr
4757// * AddrLabelExpr
4758// * BlockExpr
4759// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004760// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004761// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004762// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004763// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4764// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004765// * A MaterializeTemporaryExpr that has static storage duration, with no
4766// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004767// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004768//===----------------------------------------------------------------------===//
4769namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004770class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004771 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004772public:
Richard Smith027bf112011-11-17 22:56:20 +00004773 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4774 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004775
Richard Smith11562c52011-10-28 17:51:58 +00004776 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004777 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004778
Peter Collingbournee9200682011-05-13 03:29:01 +00004779 bool VisitDeclRefExpr(const DeclRefExpr *E);
4780 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004781 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004782 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4783 bool VisitMemberExpr(const MemberExpr *E);
4784 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4785 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004786 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004787 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004788 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4789 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004790 bool VisitUnaryReal(const UnaryOperator *E);
4791 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004792 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4793 return VisitUnaryPreIncDec(UO);
4794 }
4795 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4796 return VisitUnaryPreIncDec(UO);
4797 }
Richard Smith3229b742013-05-05 21:17:10 +00004798 bool VisitBinAssign(const BinaryOperator *BO);
4799 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004800
Peter Collingbournee9200682011-05-13 03:29:01 +00004801 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004802 switch (E->getCastKind()) {
4803 default:
Richard Smith027bf112011-11-17 22:56:20 +00004804 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004805
Eli Friedmance3e02a2011-10-11 00:13:24 +00004806 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004807 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004808 if (!Visit(E->getSubExpr()))
4809 return false;
4810 Result.Designator.setInvalid();
4811 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004812
Richard Smith027bf112011-11-17 22:56:20 +00004813 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004814 if (!Visit(E->getSubExpr()))
4815 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004816 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004817 }
4818 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004819};
4820} // end anonymous namespace
4821
Richard Smith11562c52011-10-28 17:51:58 +00004822/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004823/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004824/// * function designators in C, and
4825/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004826/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004827static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4828 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004829 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004830 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004831}
4832
Peter Collingbournee9200682011-05-13 03:29:01 +00004833bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004834 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004835 return Success(FD);
4836 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004837 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004838 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004839 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004840 return Error(E);
4841}
Richard Smith733237d2011-10-24 23:14:33 +00004842
Faisal Vali0528a312016-11-13 06:09:16 +00004843
Richard Smith11562c52011-10-28 17:51:58 +00004844bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004845 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004846 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4847 // Only if a local variable was declared in the function currently being
4848 // evaluated, do we expect to be able to find its value in the current
4849 // frame. (Otherwise it was likely declared in an enclosing context and
4850 // could either have a valid evaluatable value (for e.g. a constexpr
4851 // variable) or be ill-formed (and trigger an appropriate evaluation
4852 // diagnostic)).
4853 if (Info.CurrentCall->Callee &&
4854 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4855 Frame = Info.CurrentCall;
4856 }
4857 }
Richard Smith3229b742013-05-05 21:17:10 +00004858
Richard Smithfec09922011-11-01 16:57:24 +00004859 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004860 if (Frame) {
4861 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004862 return true;
4863 }
Richard Smithce40ad62011-11-12 22:28:03 +00004864 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004865 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004866
Richard Smith3229b742013-05-05 21:17:10 +00004867 APValue *V;
4868 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004869 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004870 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004871 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004872 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004873 return false;
4874 }
Richard Smith3229b742013-05-05 21:17:10 +00004875 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004876}
4877
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004878bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4879 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004880 // Walk through the expression to find the materialized temporary itself.
4881 SmallVector<const Expr *, 2> CommaLHSs;
4882 SmallVector<SubobjectAdjustment, 2> Adjustments;
4883 const Expr *Inner = E->GetTemporaryExpr()->
4884 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004885
Richard Smith84401042013-06-03 05:03:02 +00004886 // If we passed any comma operators, evaluate their LHSs.
4887 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4888 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4889 return false;
4890
Richard Smithe6c01442013-06-05 00:46:14 +00004891 // A materialized temporary with static storage duration can appear within the
4892 // result of a constant expression evaluation, so we need to preserve its
4893 // value for use outside this evaluation.
4894 APValue *Value;
4895 if (E->getStorageDuration() == SD_Static) {
4896 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004897 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004898 Result.set(E);
4899 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004900 Value = &Info.CurrentCall->
4901 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004902 Result.set(E, Info.CurrentCall->Index);
4903 }
4904
Richard Smithea4ad5d2013-06-06 08:19:16 +00004905 QualType Type = Inner->getType();
4906
Richard Smith84401042013-06-03 05:03:02 +00004907 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004908 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4909 (E->getStorageDuration() == SD_Static &&
4910 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4911 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004912 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004913 }
Richard Smith84401042013-06-03 05:03:02 +00004914
4915 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004916 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4917 --I;
4918 switch (Adjustments[I].Kind) {
4919 case SubobjectAdjustment::DerivedToBaseAdjustment:
4920 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4921 Type, Result))
4922 return false;
4923 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4924 break;
4925
4926 case SubobjectAdjustment::FieldAdjustment:
4927 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4928 return false;
4929 Type = Adjustments[I].Field->getType();
4930 break;
4931
4932 case SubobjectAdjustment::MemberPointerAdjustment:
4933 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4934 Adjustments[I].Ptr.RHS))
4935 return false;
4936 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4937 break;
4938 }
4939 }
4940
4941 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004942}
4943
Peter Collingbournee9200682011-05-13 03:29:01 +00004944bool
4945LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00004946 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
4947 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00004948 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4949 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004950 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004951}
4952
Richard Smith6e525142011-12-27 12:18:28 +00004953bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004954 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004955 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004956
Faisal Valie690b7a2016-07-02 22:34:24 +00004957 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004958 << E->getExprOperand()->getType()
4959 << E->getExprOperand()->getSourceRange();
4960 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004961}
4962
Francois Pichet0066db92012-04-16 04:08:35 +00004963bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4964 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004965}
Francois Pichet0066db92012-04-16 04:08:35 +00004966
Peter Collingbournee9200682011-05-13 03:29:01 +00004967bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004968 // Handle static data members.
4969 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004970 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004971 return VisitVarDecl(E, VD);
4972 }
4973
Richard Smith254a73d2011-10-28 22:34:42 +00004974 // Handle static member functions.
4975 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4976 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004977 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004978 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004979 }
4980 }
4981
Richard Smithd62306a2011-11-10 06:34:14 +00004982 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004983 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004984}
4985
Peter Collingbournee9200682011-05-13 03:29:01 +00004986bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004987 // FIXME: Deal with vectors as array subscript bases.
4988 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004989 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004990
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004991 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004992 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004993
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004994 APSInt Index;
4995 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004996 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004997
Richard Smith861b5b52013-05-07 23:34:45 +00004998 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4999 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005000}
Eli Friedman9a156e52008-11-12 09:44:48 +00005001
Peter Collingbournee9200682011-05-13 03:29:01 +00005002bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005003 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005004}
5005
Richard Smith66c96992012-02-18 22:04:06 +00005006bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5007 if (!Visit(E->getSubExpr()))
5008 return false;
5009 // __real is a no-op on scalar lvalues.
5010 if (E->getSubExpr()->getType()->isAnyComplexType())
5011 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5012 return true;
5013}
5014
5015bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5016 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5017 "lvalue __imag__ on scalar?");
5018 if (!Visit(E->getSubExpr()))
5019 return false;
5020 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5021 return true;
5022}
5023
Richard Smith243ef902013-05-05 23:31:59 +00005024bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005025 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005026 return Error(UO);
5027
5028 if (!this->Visit(UO->getSubExpr()))
5029 return false;
5030
Richard Smith243ef902013-05-05 23:31:59 +00005031 return handleIncDec(
5032 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005033 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005034}
5035
5036bool LValueExprEvaluator::VisitCompoundAssignOperator(
5037 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005038 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005039 return Error(CAO);
5040
Richard Smith3229b742013-05-05 21:17:10 +00005041 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005042
5043 // The overall lvalue result is the result of evaluating the LHS.
5044 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005045 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005046 Evaluate(RHS, this->Info, CAO->getRHS());
5047 return false;
5048 }
5049
Richard Smith3229b742013-05-05 21:17:10 +00005050 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5051 return false;
5052
Richard Smith43e77732013-05-07 04:50:00 +00005053 return handleCompoundAssignment(
5054 this->Info, CAO,
5055 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5056 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005057}
5058
5059bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005060 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005061 return Error(E);
5062
Richard Smith3229b742013-05-05 21:17:10 +00005063 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005064
5065 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005066 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005067 Evaluate(NewVal, this->Info, E->getRHS());
5068 return false;
5069 }
5070
Richard Smith3229b742013-05-05 21:17:10 +00005071 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5072 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005073
5074 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005075 NewVal);
5076}
5077
Eli Friedman9a156e52008-11-12 09:44:48 +00005078//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005079// Pointer Evaluation
5080//===----------------------------------------------------------------------===//
5081
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005082namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005083class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005084 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005085 LValue &Result;
5086
Peter Collingbournee9200682011-05-13 03:29:01 +00005087 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005088 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005089 return true;
5090 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005091public:
Mike Stump11289f42009-09-09 15:08:12 +00005092
John McCall45d55e42010-05-07 21:00:08 +00005093 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005094 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005095
Richard Smith2e312c82012-03-03 22:46:17 +00005096 bool Success(const APValue &V, const Expr *E) {
5097 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005098 return true;
5099 }
Richard Smithfddd3842011-12-30 21:15:51 +00005100 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005101 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5102 Result.set((Expr*)nullptr, 0, false, true, Offset);
5103 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005104 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005105
John McCall45d55e42010-05-07 21:00:08 +00005106 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005107 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005108 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005109 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005110 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005111 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005112 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005113 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005114 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005115 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005116 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005117 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005118 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005119 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005120 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005121 }
Richard Smithd62306a2011-11-10 06:34:14 +00005122 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005123 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005124 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005125 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005126 if (!Info.CurrentCall->This) {
5127 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005128 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005129 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005130 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005131 return false;
5132 }
Richard Smithd62306a2011-11-10 06:34:14 +00005133 Result = *Info.CurrentCall->This;
5134 return true;
5135 }
John McCallc07a0c72011-02-17 10:25:35 +00005136
Eli Friedman449fe542009-03-23 04:56:01 +00005137 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005138};
Chris Lattner05706e882008-07-11 18:11:29 +00005139} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005140
John McCall45d55e42010-05-07 21:00:08 +00005141static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005142 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005143 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005144}
5145
John McCall45d55e42010-05-07 21:00:08 +00005146bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005147 if (E->getOpcode() != BO_Add &&
5148 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005149 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005150
Chris Lattner05706e882008-07-11 18:11:29 +00005151 const Expr *PExp = E->getLHS();
5152 const Expr *IExp = E->getRHS();
5153 if (IExp->getType()->isPointerType())
5154 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005155
Richard Smith253c2a32012-01-27 01:14:48 +00005156 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005157 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005158 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005159
John McCall45d55e42010-05-07 21:00:08 +00005160 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005161 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005162 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005163
5164 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005165 if (E->getOpcode() == BO_Sub)
5166 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005167
Ted Kremenek28831752012-08-23 20:46:57 +00005168 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005169 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5170 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005171}
Eli Friedman9a156e52008-11-12 09:44:48 +00005172
John McCall45d55e42010-05-07 21:00:08 +00005173bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5174 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005175}
Mike Stump11289f42009-09-09 15:08:12 +00005176
Peter Collingbournee9200682011-05-13 03:29:01 +00005177bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5178 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005179
Eli Friedman847a2bc2009-12-27 05:43:15 +00005180 switch (E->getCastKind()) {
5181 default:
5182 break;
5183
John McCalle3027922010-08-25 11:45:40 +00005184 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005185 case CK_CPointerToObjCPointerCast:
5186 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005187 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005188 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005189 if (!Visit(SubExpr))
5190 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005191 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5192 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5193 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005194 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005195 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005196 if (SubExpr->getType()->isVoidPointerType())
5197 CCEDiag(E, diag::note_constexpr_invalid_cast)
5198 << 3 << SubExpr->getType();
5199 else
5200 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5201 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005202 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5203 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005204 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005205
Anders Carlsson18275092010-10-31 20:41:46 +00005206 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005207 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005208 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005209 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005210 if (!Result.Base && Result.Offset.isZero())
5211 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005212
Richard Smithd62306a2011-11-10 06:34:14 +00005213 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005214 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005215 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5216 castAs<PointerType>()->getPointeeType(),
5217 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005218
Richard Smith027bf112011-11-17 22:56:20 +00005219 case CK_BaseToDerived:
5220 if (!Visit(E->getSubExpr()))
5221 return false;
5222 if (!Result.Base && Result.Offset.isZero())
5223 return true;
5224 return HandleBaseToDerivedCast(Info, E, Result);
5225
Richard Smith0b0a0b62011-10-29 20:57:55 +00005226 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005227 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005228 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005229
John McCalle3027922010-08-25 11:45:40 +00005230 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005231 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5232
Richard Smith2e312c82012-03-03 22:46:17 +00005233 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005234 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005235 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005236
John McCall45d55e42010-05-07 21:00:08 +00005237 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005238 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5239 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005240 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005241 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005242 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005243 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005244 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005245 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005246 return true;
5247 } else {
5248 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005249 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005250 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005251 }
5252 }
John McCalle3027922010-08-25 11:45:40 +00005253 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005254 if (SubExpr->isGLValue()) {
5255 if (!EvaluateLValue(SubExpr, Result, Info))
5256 return false;
5257 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005258 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005259 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005260 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005261 return false;
5262 }
Richard Smith96e0c102011-11-04 02:25:55 +00005263 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005264 if (const ConstantArrayType *CAT
5265 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5266 Result.addArray(Info, E, CAT);
5267 else
5268 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005269 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005270
John McCalle3027922010-08-25 11:45:40 +00005271 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005272 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005273 }
5274
Richard Smith11562c52011-10-28 17:51:58 +00005275 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005276}
Chris Lattner05706e882008-07-11 18:11:29 +00005277
Hal Finkel0dd05d42014-10-03 17:18:37 +00005278static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5279 // C++ [expr.alignof]p3:
5280 // When alignof is applied to a reference type, the result is the
5281 // alignment of the referenced type.
5282 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5283 T = Ref->getPointeeType();
5284
5285 // __alignof is defined to return the preferred alignment.
5286 return Info.Ctx.toCharUnitsFromBits(
5287 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5288}
5289
5290static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5291 E = E->IgnoreParens();
5292
5293 // The kinds of expressions that we have special-case logic here for
5294 // should be kept up to date with the special checks for those
5295 // expressions in Sema.
5296
5297 // alignof decl is always accepted, even if it doesn't make sense: we default
5298 // to 1 in those cases.
5299 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5300 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5301 /*RefAsPointee*/true);
5302
5303 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5304 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5305 /*RefAsPointee*/true);
5306
5307 return GetAlignOfType(Info, E->getType());
5308}
5309
Peter Collingbournee9200682011-05-13 03:29:01 +00005310bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005311 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005312 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005313
Richard Smith6328cbd2016-11-16 00:57:23 +00005314 if (unsigned BuiltinOp = E->getBuiltinCallee())
5315 return VisitBuiltinCallExpr(E, BuiltinOp);
5316
Chandler Carruthd7738fe2016-12-20 08:28:19 +00005317 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005318}
5319
5320bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5321 unsigned BuiltinOp) {
5322 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005323 case Builtin::BI__builtin_addressof:
5324 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005325 case Builtin::BI__builtin_assume_aligned: {
5326 // We need to be very careful here because: if the pointer does not have the
5327 // asserted alignment, then the behavior is undefined, and undefined
5328 // behavior is non-constant.
5329 if (!EvaluatePointer(E->getArg(0), Result, Info))
5330 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005331
Hal Finkel0dd05d42014-10-03 17:18:37 +00005332 LValue OffsetResult(Result);
5333 APSInt Alignment;
5334 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5335 return false;
5336 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5337
5338 if (E->getNumArgs() > 2) {
5339 APSInt Offset;
5340 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5341 return false;
5342
5343 int64_t AdditionalOffset = -getExtValue(Offset);
5344 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5345 }
5346
5347 // If there is a base object, then it must have the correct alignment.
5348 if (OffsetResult.Base) {
5349 CharUnits BaseAlignment;
5350 if (const ValueDecl *VD =
5351 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5352 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5353 } else {
5354 BaseAlignment =
5355 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5356 }
5357
5358 if (BaseAlignment < Align) {
5359 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005360 // FIXME: Quantities here cast to integers because the plural modifier
5361 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005362 CCEDiag(E->getArg(0),
5363 diag::note_constexpr_baa_insufficient_alignment) << 0
5364 << (int) BaseAlignment.getQuantity()
5365 << (unsigned) getExtValue(Alignment);
5366 return false;
5367 }
5368 }
5369
5370 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005371 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005372 Result.Designator.setInvalid();
5373 APSInt Offset(64, false);
5374 Offset = OffsetResult.Offset.getQuantity();
5375
5376 if (OffsetResult.Base)
5377 CCEDiag(E->getArg(0),
5378 diag::note_constexpr_baa_insufficient_alignment) << 1
5379 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5380 else
5381 CCEDiag(E->getArg(0),
5382 diag::note_constexpr_baa_value_insufficient_alignment)
5383 << Offset << (unsigned) getExtValue(Alignment);
5384
5385 return false;
5386 }
5387
5388 return true;
5389 }
Richard Smithe9507952016-11-12 01:39:56 +00005390
5391 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005392 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005393 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005394 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005395 if (Info.getLangOpts().CPlusPlus11)
5396 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5397 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005398 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005399 else
5400 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5401 // Fall through.
5402 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005403 case Builtin::BI__builtin_wcschr:
5404 case Builtin::BI__builtin_memchr:
5405 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005406 if (!Visit(E->getArg(0)))
5407 return false;
5408 APSInt Desired;
5409 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5410 return false;
5411 uint64_t MaxLength = uint64_t(-1);
5412 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005413 BuiltinOp != Builtin::BIwcschr &&
5414 BuiltinOp != Builtin::BI__builtin_strchr &&
5415 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005416 APSInt N;
5417 if (!EvaluateInteger(E->getArg(2), N, Info))
5418 return false;
5419 MaxLength = N.getExtValue();
5420 }
5421
Richard Smith8110c9d2016-11-29 19:45:17 +00005422 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005423
Richard Smith8110c9d2016-11-29 19:45:17 +00005424 // Figure out what value we're actually looking for (after converting to
5425 // the corresponding unsigned type if necessary).
5426 uint64_t DesiredVal;
5427 bool StopAtNull = false;
5428 switch (BuiltinOp) {
5429 case Builtin::BIstrchr:
5430 case Builtin::BI__builtin_strchr:
5431 // strchr compares directly to the passed integer, and therefore
5432 // always fails if given an int that is not a char.
5433 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5434 E->getArg(1)->getType(),
5435 Desired),
5436 Desired))
5437 return ZeroInitialization(E);
5438 StopAtNull = true;
5439 // Fall through.
5440 case Builtin::BImemchr:
5441 case Builtin::BI__builtin_memchr:
5442 // memchr compares by converting both sides to unsigned char. That's also
5443 // correct for strchr if we get this far (to cope with plain char being
5444 // unsigned in the strchr case).
5445 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5446 break;
Richard Smithe9507952016-11-12 01:39:56 +00005447
Richard Smith8110c9d2016-11-29 19:45:17 +00005448 case Builtin::BIwcschr:
5449 case Builtin::BI__builtin_wcschr:
5450 StopAtNull = true;
5451 // Fall through.
5452 case Builtin::BIwmemchr:
5453 case Builtin::BI__builtin_wmemchr:
5454 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5455 DesiredVal = Desired.getZExtValue();
5456 break;
5457 }
Richard Smithe9507952016-11-12 01:39:56 +00005458
5459 for (; MaxLength; --MaxLength) {
5460 APValue Char;
5461 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5462 !Char.isInt())
5463 return false;
5464 if (Char.getInt().getZExtValue() == DesiredVal)
5465 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005466 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005467 break;
5468 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5469 return false;
5470 }
5471 // Not found: return nullptr.
5472 return ZeroInitialization(E);
5473 }
5474
Richard Smith6cbd65d2013-07-11 02:27:57 +00005475 default:
Chandler Carruthd7738fe2016-12-20 08:28:19 +00005476 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005477 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005478}
Chris Lattner05706e882008-07-11 18:11:29 +00005479
5480//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005481// Member Pointer Evaluation
5482//===----------------------------------------------------------------------===//
5483
5484namespace {
5485class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005486 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005487 MemberPtr &Result;
5488
5489 bool Success(const ValueDecl *D) {
5490 Result = MemberPtr(D);
5491 return true;
5492 }
5493public:
5494
5495 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5496 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5497
Richard Smith2e312c82012-03-03 22:46:17 +00005498 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005499 Result.setFrom(V);
5500 return true;
5501 }
Richard Smithfddd3842011-12-30 21:15:51 +00005502 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005503 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005504 }
5505
5506 bool VisitCastExpr(const CastExpr *E);
5507 bool VisitUnaryAddrOf(const UnaryOperator *E);
5508};
5509} // end anonymous namespace
5510
5511static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5512 EvalInfo &Info) {
5513 assert(E->isRValue() && E->getType()->isMemberPointerType());
5514 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5515}
5516
5517bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5518 switch (E->getCastKind()) {
5519 default:
5520 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5521
5522 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005523 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005524 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005525
5526 case CK_BaseToDerivedMemberPointer: {
5527 if (!Visit(E->getSubExpr()))
5528 return false;
5529 if (E->path_empty())
5530 return true;
5531 // Base-to-derived member pointer casts store the path in derived-to-base
5532 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5533 // the wrong end of the derived->base arc, so stagger the path by one class.
5534 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5535 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5536 PathI != PathE; ++PathI) {
5537 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5538 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5539 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005540 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005541 }
5542 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5543 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005544 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005545 return true;
5546 }
5547
5548 case CK_DerivedToBaseMemberPointer:
5549 if (!Visit(E->getSubExpr()))
5550 return false;
5551 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5552 PathE = E->path_end(); PathI != PathE; ++PathI) {
5553 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5554 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5555 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005556 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005557 }
5558 return true;
5559 }
5560}
5561
5562bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5563 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5564 // member can be formed.
5565 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5566}
5567
5568//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005569// Record Evaluation
5570//===----------------------------------------------------------------------===//
5571
5572namespace {
5573 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005574 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005575 const LValue &This;
5576 APValue &Result;
5577 public:
5578
5579 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5580 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5581
Richard Smith2e312c82012-03-03 22:46:17 +00005582 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005583 Result = V;
5584 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005585 }
Richard Smithb8348f52016-05-12 22:16:28 +00005586 bool ZeroInitialization(const Expr *E) {
5587 return ZeroInitialization(E, E->getType());
5588 }
5589 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005590
Richard Smith52a980a2015-08-28 02:43:42 +00005591 bool VisitCallExpr(const CallExpr *E) {
5592 return handleCallExpr(E, Result, &This);
5593 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005594 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005595 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005596 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5597 return VisitCXXConstructExpr(E, E->getType());
5598 }
Richard Smith5179eb72016-06-28 19:03:57 +00005599 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005600 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005601 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005602 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005603}
Richard Smithd62306a2011-11-10 06:34:14 +00005604
Richard Smithfddd3842011-12-30 21:15:51 +00005605/// Perform zero-initialization on an object of non-union class type.
5606/// C++11 [dcl.init]p5:
5607/// To zero-initialize an object or reference of type T means:
5608/// [...]
5609/// -- if T is a (possibly cv-qualified) non-union class type,
5610/// each non-static data member and each base-class subobject is
5611/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005612static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5613 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005614 const LValue &This, APValue &Result) {
5615 assert(!RD->isUnion() && "Expected non-union class type");
5616 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5617 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005618 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005619
John McCalld7bca762012-05-01 00:38:49 +00005620 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005621 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5622
5623 if (CD) {
5624 unsigned Index = 0;
5625 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005626 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005627 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5628 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005629 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5630 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005631 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005632 Result.getStructBase(Index)))
5633 return false;
5634 }
5635 }
5636
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005637 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005638 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005639 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005640 continue;
5641
5642 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005643 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005644 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005645
David Blaikie2d7c57e2012-04-30 02:36:29 +00005646 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005647 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005648 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005649 return false;
5650 }
5651
5652 return true;
5653}
5654
Richard Smithb8348f52016-05-12 22:16:28 +00005655bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5656 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005657 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005658 if (RD->isUnion()) {
5659 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5660 // object's first non-static named data member is zero-initialized
5661 RecordDecl::field_iterator I = RD->field_begin();
5662 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005663 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005664 return true;
5665 }
5666
5667 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005668 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005669 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005670 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005671 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005672 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005673 }
5674
Richard Smith5d108602012-02-17 00:44:16 +00005675 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005676 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005677 return false;
5678 }
5679
Richard Smitha8105bc2012-01-06 16:39:00 +00005680 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005681}
5682
Richard Smithe97cbd72011-11-11 04:05:33 +00005683bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5684 switch (E->getCastKind()) {
5685 default:
5686 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5687
5688 case CK_ConstructorConversion:
5689 return Visit(E->getSubExpr());
5690
5691 case CK_DerivedToBase:
5692 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005693 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005694 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005695 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005696 if (!DerivedObject.isStruct())
5697 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005698
5699 // Derived-to-base rvalue conversion: just slice off the derived part.
5700 APValue *Value = &DerivedObject;
5701 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5702 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5703 PathE = E->path_end(); PathI != PathE; ++PathI) {
5704 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5705 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5706 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5707 RD = Base;
5708 }
5709 Result = *Value;
5710 return true;
5711 }
5712 }
5713}
5714
Richard Smithd62306a2011-11-10 06:34:14 +00005715bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005716 if (E->isTransparent())
5717 return Visit(E->getInit(0));
5718
Richard Smithd62306a2011-11-10 06:34:14 +00005719 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005720 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005721 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5722
5723 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005724 const FieldDecl *Field = E->getInitializedFieldInUnion();
5725 Result = APValue(Field);
5726 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005727 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005728
5729 // If the initializer list for a union does not contain any elements, the
5730 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005731 // FIXME: The element should be initialized from an initializer list.
5732 // Is this difference ever observable for initializer lists which
5733 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005734 ImplicitValueInitExpr VIE(Field->getType());
5735 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5736
Richard Smithd62306a2011-11-10 06:34:14 +00005737 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005738 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5739 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005740
5741 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5742 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5743 isa<CXXDefaultInitExpr>(InitExpr));
5744
Richard Smithb228a862012-02-15 02:18:13 +00005745 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005746 }
5747
Richard Smith872307e2016-03-08 22:17:41 +00005748 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005749 if (Result.isUninit())
5750 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5751 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005752 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005753 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005754
5755 // Initialize base classes.
5756 if (CXXRD) {
5757 for (const auto &Base : CXXRD->bases()) {
5758 assert(ElementNo < E->getNumInits() && "missing init for base class");
5759 const Expr *Init = E->getInit(ElementNo);
5760
5761 LValue Subobject = This;
5762 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5763 return false;
5764
5765 APValue &FieldVal = Result.getStructBase(ElementNo);
5766 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005767 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005768 return false;
5769 Success = false;
5770 }
5771 ++ElementNo;
5772 }
5773 }
5774
5775 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005776 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005777 // Anonymous bit-fields are not considered members of the class for
5778 // purposes of aggregate initialization.
5779 if (Field->isUnnamedBitfield())
5780 continue;
5781
5782 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005783
Richard Smith253c2a32012-01-27 01:14:48 +00005784 bool HaveInit = ElementNo < E->getNumInits();
5785
5786 // FIXME: Diagnostics here should point to the end of the initializer
5787 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005788 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005789 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005790 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005791
5792 // Perform an implicit value-initialization for members beyond the end of
5793 // the initializer list.
5794 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005795 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005796
Richard Smith852c9db2013-04-20 22:23:05 +00005797 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5798 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5799 isa<CXXDefaultInitExpr>(Init));
5800
Richard Smith49ca8aa2013-08-06 07:09:20 +00005801 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5802 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5803 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005804 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005805 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005806 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005807 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005808 }
5809 }
5810
Richard Smith253c2a32012-01-27 01:14:48 +00005811 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005812}
5813
Richard Smithb8348f52016-05-12 22:16:28 +00005814bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5815 QualType T) {
5816 // Note that E's type is not necessarily the type of our class here; we might
5817 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005818 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005819 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5820
Richard Smithfddd3842011-12-30 21:15:51 +00005821 bool ZeroInit = E->requiresZeroInitialization();
5822 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005823 // If we've already performed zero-initialization, we're already done.
5824 if (!Result.isUninit())
5825 return true;
5826
Richard Smithda3f4fd2014-03-05 23:32:50 +00005827 // We can get here in two different ways:
5828 // 1) We're performing value-initialization, and should zero-initialize
5829 // the object, or
5830 // 2) We're performing default-initialization of an object with a trivial
5831 // constexpr default constructor, in which case we should start the
5832 // lifetimes of all the base subobjects (there can be no data member
5833 // subobjects in this case) per [basic.life]p1.
5834 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005835 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005836 }
5837
Craig Topper36250ad2014-05-12 05:36:57 +00005838 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005839 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005840
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005841 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005842 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005843
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005844 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005845 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005846 if (const MaterializeTemporaryExpr *ME
5847 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5848 return Visit(ME->GetTemporaryExpr());
5849
Richard Smithb8348f52016-05-12 22:16:28 +00005850 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005851 return false;
5852
Craig Topper5fc8fc22014-08-27 06:28:36 +00005853 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005854 return HandleConstructorCall(E, This, Args,
5855 cast<CXXConstructorDecl>(Definition), Info,
5856 Result);
5857}
5858
5859bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5860 const CXXInheritedCtorInitExpr *E) {
5861 if (!Info.CurrentCall) {
5862 assert(Info.checkingPotentialConstantExpression());
5863 return false;
5864 }
5865
5866 const CXXConstructorDecl *FD = E->getConstructor();
5867 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5868 return false;
5869
5870 const FunctionDecl *Definition = nullptr;
5871 auto Body = FD->getBody(Definition);
5872
5873 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5874 return false;
5875
5876 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005877 cast<CXXConstructorDecl>(Definition), Info,
5878 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005879}
5880
Richard Smithcc1b96d2013-06-12 22:31:48 +00005881bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5882 const CXXStdInitializerListExpr *E) {
5883 const ConstantArrayType *ArrayType =
5884 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5885
5886 LValue Array;
5887 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5888 return false;
5889
5890 // Get a pointer to the first element of the array.
5891 Array.addArray(Info, E, ArrayType);
5892
5893 // FIXME: Perform the checks on the field types in SemaInit.
5894 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5895 RecordDecl::field_iterator Field = Record->field_begin();
5896 if (Field == Record->field_end())
5897 return Error(E);
5898
5899 // Start pointer.
5900 if (!Field->getType()->isPointerType() ||
5901 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5902 ArrayType->getElementType()))
5903 return Error(E);
5904
5905 // FIXME: What if the initializer_list type has base classes, etc?
5906 Result = APValue(APValue::UninitStruct(), 0, 2);
5907 Array.moveInto(Result.getStructField(0));
5908
5909 if (++Field == Record->field_end())
5910 return Error(E);
5911
5912 if (Field->getType()->isPointerType() &&
5913 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5914 ArrayType->getElementType())) {
5915 // End pointer.
5916 if (!HandleLValueArrayAdjustment(Info, E, Array,
5917 ArrayType->getElementType(),
5918 ArrayType->getSize().getZExtValue()))
5919 return false;
5920 Array.moveInto(Result.getStructField(1));
5921 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5922 // Length.
5923 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5924 else
5925 return Error(E);
5926
5927 if (++Field != Record->field_end())
5928 return Error(E);
5929
5930 return true;
5931}
5932
Richard Smithd62306a2011-11-10 06:34:14 +00005933static bool EvaluateRecord(const Expr *E, const LValue &This,
5934 APValue &Result, EvalInfo &Info) {
5935 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005936 "can't evaluate expression as a record rvalue");
5937 return RecordExprEvaluator(Info, This, Result).Visit(E);
5938}
5939
5940//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005941// Temporary Evaluation
5942//
5943// Temporaries are represented in the AST as rvalues, but generally behave like
5944// lvalues. The full-object of which the temporary is a subobject is implicitly
5945// materialized so that a reference can bind to it.
5946//===----------------------------------------------------------------------===//
5947namespace {
5948class TemporaryExprEvaluator
5949 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5950public:
5951 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5952 LValueExprEvaluatorBaseTy(Info, Result) {}
5953
5954 /// Visit an expression which constructs the value of this temporary.
5955 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005956 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005957 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5958 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005959 }
5960
5961 bool VisitCastExpr(const CastExpr *E) {
5962 switch (E->getCastKind()) {
5963 default:
5964 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5965
5966 case CK_ConstructorConversion:
5967 return VisitConstructExpr(E->getSubExpr());
5968 }
5969 }
5970 bool VisitInitListExpr(const InitListExpr *E) {
5971 return VisitConstructExpr(E);
5972 }
5973 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5974 return VisitConstructExpr(E);
5975 }
5976 bool VisitCallExpr(const CallExpr *E) {
5977 return VisitConstructExpr(E);
5978 }
Richard Smith513955c2014-12-17 19:24:30 +00005979 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5980 return VisitConstructExpr(E);
5981 }
Richard Smith027bf112011-11-17 22:56:20 +00005982};
5983} // end anonymous namespace
5984
5985/// Evaluate an expression of record type as a temporary.
5986static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005987 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005988 return TemporaryExprEvaluator(Info, Result).Visit(E);
5989}
5990
5991//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005992// Vector Evaluation
5993//===----------------------------------------------------------------------===//
5994
5995namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005996 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005997 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005998 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005999 public:
Mike Stump11289f42009-09-09 15:08:12 +00006000
Richard Smith2d406342011-10-22 21:10:00 +00006001 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6002 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006003
Craig Topper9798b932015-09-29 04:30:05 +00006004 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006005 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6006 // FIXME: remove this APValue copy.
6007 Result = APValue(V.data(), V.size());
6008 return true;
6009 }
Richard Smith2e312c82012-03-03 22:46:17 +00006010 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006011 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006012 Result = V;
6013 return true;
6014 }
Richard Smithfddd3842011-12-30 21:15:51 +00006015 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006016
Richard Smith2d406342011-10-22 21:10:00 +00006017 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006018 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006019 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006020 bool VisitInitListExpr(const InitListExpr *E);
6021 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006022 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006023 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006024 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006025 };
6026} // end anonymous namespace
6027
6028static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006029 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006030 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006031}
6032
George Burgess IV533ff002015-12-11 00:23:35 +00006033bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006034 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006035 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006036
Richard Smith161f09a2011-12-06 22:44:34 +00006037 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006038 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006039
Eli Friedmanc757de22011-03-25 00:43:55 +00006040 switch (E->getCastKind()) {
6041 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006042 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006043 if (SETy->isIntegerType()) {
6044 APSInt IntResult;
6045 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006046 return false;
6047 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006048 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006049 APFloat FloatResult(0.0);
6050 if (!EvaluateFloat(SE, FloatResult, Info))
6051 return false;
6052 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006053 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006054 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006055 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006056
6057 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006058 SmallVector<APValue, 4> Elts(NElts, Val);
6059 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006060 }
Eli Friedman803acb32011-12-22 03:51:45 +00006061 case CK_BitCast: {
6062 // Evaluate the operand into an APInt we can extract from.
6063 llvm::APInt SValInt;
6064 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6065 return false;
6066 // Extract the elements
6067 QualType EltTy = VTy->getElementType();
6068 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6069 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6070 SmallVector<APValue, 4> Elts;
6071 if (EltTy->isRealFloatingType()) {
6072 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006073 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006074 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006075 FloatEltSize = 80;
6076 for (unsigned i = 0; i < NElts; i++) {
6077 llvm::APInt Elt;
6078 if (BigEndian)
6079 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6080 else
6081 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006082 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006083 }
6084 } else if (EltTy->isIntegerType()) {
6085 for (unsigned i = 0; i < NElts; i++) {
6086 llvm::APInt Elt;
6087 if (BigEndian)
6088 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6089 else
6090 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6091 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6092 }
6093 } else {
6094 return Error(E);
6095 }
6096 return Success(Elts, E);
6097 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006098 default:
Richard Smith11562c52011-10-28 17:51:58 +00006099 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006100 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006101}
6102
Richard Smith2d406342011-10-22 21:10:00 +00006103bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006104VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006105 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006106 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006107 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006108
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006109 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006110 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006111
Eli Friedmanb9c71292012-01-03 23:24:20 +00006112 // The number of initializers can be less than the number of
6113 // vector elements. For OpenCL, this can be due to nested vector
6114 // initialization. For GCC compatibility, missing trailing elements
6115 // should be initialized with zeroes.
6116 unsigned CountInits = 0, CountElts = 0;
6117 while (CountElts < NumElements) {
6118 // Handle nested vector initialization.
6119 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006120 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006121 APValue v;
6122 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6123 return Error(E);
6124 unsigned vlen = v.getVectorLength();
6125 for (unsigned j = 0; j < vlen; j++)
6126 Elements.push_back(v.getVectorElt(j));
6127 CountElts += vlen;
6128 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006129 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006130 if (CountInits < NumInits) {
6131 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006132 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006133 } else // trailing integer zero.
6134 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6135 Elements.push_back(APValue(sInt));
6136 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006137 } else {
6138 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006139 if (CountInits < NumInits) {
6140 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006141 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006142 } else // trailing float zero.
6143 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6144 Elements.push_back(APValue(f));
6145 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006146 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006147 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006148 }
Richard Smith2d406342011-10-22 21:10:00 +00006149 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006150}
6151
Richard Smith2d406342011-10-22 21:10:00 +00006152bool
Richard Smithfddd3842011-12-30 21:15:51 +00006153VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006154 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006155 QualType EltTy = VT->getElementType();
6156 APValue ZeroElement;
6157 if (EltTy->isIntegerType())
6158 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6159 else
6160 ZeroElement =
6161 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6162
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006163 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006164 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006165}
6166
Richard Smith2d406342011-10-22 21:10:00 +00006167bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006168 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006169 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006170}
6171
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006172//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006173// Array Evaluation
6174//===----------------------------------------------------------------------===//
6175
6176namespace {
6177 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006178 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006179 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006180 APValue &Result;
6181 public:
6182
Richard Smithd62306a2011-11-10 06:34:14 +00006183 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6184 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006185
6186 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006187 assert((V.isArray() || V.isLValue()) &&
6188 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006189 Result = V;
6190 return true;
6191 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006192
Richard Smithfddd3842011-12-30 21:15:51 +00006193 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006194 const ConstantArrayType *CAT =
6195 Info.Ctx.getAsConstantArrayType(E->getType());
6196 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006197 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006198
6199 Result = APValue(APValue::UninitArray(), 0,
6200 CAT->getSize().getZExtValue());
6201 if (!Result.hasArrayFiller()) return true;
6202
Richard Smithfddd3842011-12-30 21:15:51 +00006203 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006204 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006205 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006206 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006207 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006208 }
6209
Richard Smith52a980a2015-08-28 02:43:42 +00006210 bool VisitCallExpr(const CallExpr *E) {
6211 return handleCallExpr(E, Result, &This);
6212 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006213 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006214 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006215 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006216 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6217 const LValue &Subobject,
6218 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006219 };
6220} // end anonymous namespace
6221
Richard Smithd62306a2011-11-10 06:34:14 +00006222static bool EvaluateArray(const Expr *E, const LValue &This,
6223 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006224 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006225 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006226}
6227
6228bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6229 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6230 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006231 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006232
Richard Smithca2cfbf2011-12-22 01:07:19 +00006233 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6234 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006235 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006236 LValue LV;
6237 if (!EvaluateLValue(E->getInit(0), LV, Info))
6238 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006239 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006240 LV.moveInto(Val);
6241 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006242 }
6243
Richard Smith253c2a32012-01-27 01:14:48 +00006244 bool Success = true;
6245
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006246 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6247 "zero-initialized array shouldn't have any initialized elts");
6248 APValue Filler;
6249 if (Result.isArray() && Result.hasArrayFiller())
6250 Filler = Result.getArrayFiller();
6251
Richard Smith9543c5e2013-04-22 14:44:29 +00006252 unsigned NumEltsToInit = E->getNumInits();
6253 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006254 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006255
6256 // If the initializer might depend on the array index, run it for each
6257 // array element. For now, just whitelist non-class value-initialization.
6258 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6259 NumEltsToInit = NumElts;
6260
6261 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006262
6263 // If the array was previously zero-initialized, preserve the
6264 // zero-initialized values.
6265 if (!Filler.isUninit()) {
6266 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6267 Result.getArrayInitializedElt(I) = Filler;
6268 if (Result.hasArrayFiller())
6269 Result.getArrayFiller() = Filler;
6270 }
6271
Richard Smithd62306a2011-11-10 06:34:14 +00006272 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006273 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006274 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6275 const Expr *Init =
6276 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006277 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006278 Info, Subobject, Init) ||
6279 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006280 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006281 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006282 return false;
6283 Success = false;
6284 }
Richard Smithd62306a2011-11-10 06:34:14 +00006285 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006286
Richard Smith9543c5e2013-04-22 14:44:29 +00006287 if (!Result.hasArrayFiller())
6288 return Success;
6289
6290 // If we get here, we have a trivial filler, which we can just evaluate
6291 // once and splat over the rest of the array elements.
6292 assert(FillerExpr && "no array filler for incomplete init list");
6293 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6294 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006295}
6296
Richard Smith410306b2016-12-12 02:53:20 +00006297bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6298 if (E->getCommonExpr() &&
6299 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6300 Info, E->getCommonExpr()->getSourceExpr()))
6301 return false;
6302
6303 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6304
6305 uint64_t Elements = CAT->getSize().getZExtValue();
6306 Result = APValue(APValue::UninitArray(), Elements, Elements);
6307
6308 LValue Subobject = This;
6309 Subobject.addArray(Info, E, CAT);
6310
6311 bool Success = true;
6312 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6313 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6314 Info, Subobject, E->getSubExpr()) ||
6315 !HandleLValueArrayAdjustment(Info, E, Subobject,
6316 CAT->getElementType(), 1)) {
6317 if (!Info.noteFailure())
6318 return false;
6319 Success = false;
6320 }
6321 }
6322
6323 return Success;
6324}
6325
Richard Smith027bf112011-11-17 22:56:20 +00006326bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006327 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6328}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006329
Richard Smith9543c5e2013-04-22 14:44:29 +00006330bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6331 const LValue &Subobject,
6332 APValue *Value,
6333 QualType Type) {
6334 bool HadZeroInit = !Value->isUninit();
6335
6336 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6337 unsigned N = CAT->getSize().getZExtValue();
6338
6339 // Preserve the array filler if we had prior zero-initialization.
6340 APValue Filler =
6341 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6342 : APValue();
6343
6344 *Value = APValue(APValue::UninitArray(), N, N);
6345
6346 if (HadZeroInit)
6347 for (unsigned I = 0; I != N; ++I)
6348 Value->getArrayInitializedElt(I) = Filler;
6349
6350 // Initialize the elements.
6351 LValue ArrayElt = Subobject;
6352 ArrayElt.addArray(Info, E, CAT);
6353 for (unsigned I = 0; I != N; ++I)
6354 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6355 CAT->getElementType()) ||
6356 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6357 CAT->getElementType(), 1))
6358 return false;
6359
6360 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006361 }
Richard Smith027bf112011-11-17 22:56:20 +00006362
Richard Smith9543c5e2013-04-22 14:44:29 +00006363 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006364 return Error(E);
6365
Richard Smithb8348f52016-05-12 22:16:28 +00006366 return RecordExprEvaluator(Info, Subobject, *Value)
6367 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006368}
6369
Richard Smithf3e9e432011-11-07 09:22:26 +00006370//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006371// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006372//
6373// As a GNU extension, we support casting pointers to sufficiently-wide integer
6374// types and back in constant folding. Integer values are thus represented
6375// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006376//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006377
6378namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006379class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006380 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006381 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006382public:
Richard Smith2e312c82012-03-03 22:46:17 +00006383 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006384 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006386 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006387 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006388 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006389 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006390 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006391 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006392 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006393 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006394 return true;
6395 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006396 bool Success(const llvm::APSInt &SI, const Expr *E) {
6397 return Success(SI, E, Result);
6398 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006399
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006400 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006401 assert(E->getType()->isIntegralOrEnumerationType() &&
6402 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006403 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006404 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006405 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006406 Result.getInt().setIsUnsigned(
6407 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006408 return true;
6409 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006410 bool Success(const llvm::APInt &I, const Expr *E) {
6411 return Success(I, E, Result);
6412 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006413
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006414 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006415 assert(E->getType()->isIntegralOrEnumerationType() &&
6416 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006417 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006418 return true;
6419 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006420 bool Success(uint64_t Value, const Expr *E) {
6421 return Success(Value, E, Result);
6422 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006423
Ken Dyckdbc01912011-03-11 02:13:43 +00006424 bool Success(CharUnits Size, const Expr *E) {
6425 return Success(Size.getQuantity(), E);
6426 }
6427
Richard Smith2e312c82012-03-03 22:46:17 +00006428 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006429 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006430 Result = V;
6431 return true;
6432 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006433 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006434 }
Mike Stump11289f42009-09-09 15:08:12 +00006435
Richard Smithfddd3842011-12-30 21:15:51 +00006436 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006437
Peter Collingbournee9200682011-05-13 03:29:01 +00006438 //===--------------------------------------------------------------------===//
6439 // Visitor Methods
6440 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006441
Chris Lattner7174bf32008-07-12 00:38:25 +00006442 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006443 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006444 }
6445 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006446 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006447 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006448
6449 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6450 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006451 if (CheckReferencedDecl(E, E->getDecl()))
6452 return true;
6453
6454 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006455 }
6456 bool VisitMemberExpr(const MemberExpr *E) {
6457 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006458 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006459 return true;
6460 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006461
6462 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006463 }
6464
Peter Collingbournee9200682011-05-13 03:29:01 +00006465 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006466 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006467 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006468 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006469 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006470
Peter Collingbournee9200682011-05-13 03:29:01 +00006471 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006472 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006473
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006474 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006475 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006476 }
Mike Stump11289f42009-09-09 15:08:12 +00006477
Ted Kremeneke65b0862012-03-06 20:05:56 +00006478 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6479 return Success(E->getValue(), E);
6480 }
Richard Smith410306b2016-12-12 02:53:20 +00006481
6482 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6483 if (Info.ArrayInitIndex == uint64_t(-1)) {
6484 // We were asked to evaluate this subexpression independent of the
6485 // enclosing ArrayInitLoopExpr. We can't do that.
6486 Info.FFDiag(E);
6487 return false;
6488 }
6489 return Success(Info.ArrayInitIndex, E);
6490 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006491
Richard Smith4ce706a2011-10-11 21:43:33 +00006492 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006493 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006494 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006495 }
6496
Douglas Gregor29c42f22012-02-24 07:38:34 +00006497 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6498 return Success(E->getValue(), E);
6499 }
6500
John Wiegley6242b6a2011-04-28 00:16:57 +00006501 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6502 return Success(E->getValue(), E);
6503 }
6504
John Wiegleyf9f65842011-04-25 06:54:41 +00006505 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6506 return Success(E->getValue(), E);
6507 }
6508
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006509 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006510 bool VisitUnaryImag(const UnaryOperator *E);
6511
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006512 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006513 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006514
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006515private:
6516 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006517 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006518};
Chris Lattner05706e882008-07-11 18:11:29 +00006519} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006520
Richard Smith11562c52011-10-28 17:51:58 +00006521/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6522/// produce either the integer value or a pointer.
6523///
6524/// GCC has a heinous extension which folds casts between pointer types and
6525/// pointer-sized integral types. We support this by allowing the evaluation of
6526/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6527/// Some simple arithmetic on such values is supported (they are treated much
6528/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006529static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006530 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006531 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006532 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006533}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006534
Richard Smithf57d8cb2011-12-09 22:58:01 +00006535static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006536 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006537 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006538 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006539 if (!Val.isInt()) {
6540 // FIXME: It would be better to produce the diagnostic for casting
6541 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006542 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006543 return false;
6544 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006545 Result = Val.getInt();
6546 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006547}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006548
Richard Smithf57d8cb2011-12-09 22:58:01 +00006549/// Check whether the given declaration can be directly converted to an integral
6550/// rvalue. If not, no diagnostic is produced; there are other things we can
6551/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006552bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006553 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006554 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006555 // Check for signedness/width mismatches between E type and ECD value.
6556 bool SameSign = (ECD->getInitVal().isSigned()
6557 == E->getType()->isSignedIntegerOrEnumerationType());
6558 bool SameWidth = (ECD->getInitVal().getBitWidth()
6559 == Info.Ctx.getIntWidth(E->getType()));
6560 if (SameSign && SameWidth)
6561 return Success(ECD->getInitVal(), E);
6562 else {
6563 // Get rid of mismatch (otherwise Success assertions will fail)
6564 // by computing a new value matching the type of E.
6565 llvm::APSInt Val = ECD->getInitVal();
6566 if (!SameSign)
6567 Val.setIsSigned(!ECD->getInitVal().isSigned());
6568 if (!SameWidth)
6569 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6570 return Success(Val, E);
6571 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006572 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006573 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006574}
6575
Chris Lattner86ee2862008-10-06 06:40:35 +00006576/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6577/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006578static int EvaluateBuiltinClassifyType(const CallExpr *E,
6579 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006580 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006581 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006582 enum gcc_type_class {
6583 no_type_class = -1,
6584 void_type_class, integer_type_class, char_type_class,
6585 enumeral_type_class, boolean_type_class,
6586 pointer_type_class, reference_type_class, offset_type_class,
6587 real_type_class, complex_type_class,
6588 function_type_class, method_type_class,
6589 record_type_class, union_type_class,
6590 array_type_class, string_type_class,
6591 lang_type_class
6592 };
Mike Stump11289f42009-09-09 15:08:12 +00006593
6594 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006595 // ideal, however it is what gcc does.
6596 if (E->getNumArgs() == 0)
6597 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006598
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006599 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6600 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6601
6602 switch (CanTy->getTypeClass()) {
6603#define TYPE(ID, BASE)
6604#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6605#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6606#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6607#include "clang/AST/TypeNodes.def"
6608 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6609
6610 case Type::Builtin:
6611 switch (BT->getKind()) {
6612#define BUILTIN_TYPE(ID, SINGLETON_ID)
6613#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6614#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6615#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6616#include "clang/AST/BuiltinTypes.def"
6617 case BuiltinType::Void:
6618 return void_type_class;
6619
6620 case BuiltinType::Bool:
6621 return boolean_type_class;
6622
6623 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6624 case BuiltinType::UChar:
6625 case BuiltinType::UShort:
6626 case BuiltinType::UInt:
6627 case BuiltinType::ULong:
6628 case BuiltinType::ULongLong:
6629 case BuiltinType::UInt128:
6630 return integer_type_class;
6631
6632 case BuiltinType::NullPtr:
6633 return pointer_type_class;
6634
6635 case BuiltinType::WChar_U:
6636 case BuiltinType::Char16:
6637 case BuiltinType::Char32:
6638 case BuiltinType::ObjCId:
6639 case BuiltinType::ObjCClass:
6640 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006641#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6642 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006643#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006644 case BuiltinType::OCLSampler:
6645 case BuiltinType::OCLEvent:
6646 case BuiltinType::OCLClkEvent:
6647 case BuiltinType::OCLQueue:
6648 case BuiltinType::OCLNDRange:
6649 case BuiltinType::OCLReserveID:
6650 case BuiltinType::Dependent:
6651 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6652 };
6653
6654 case Type::Enum:
6655 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6656 break;
6657
6658 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006659 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006660 break;
6661
6662 case Type::MemberPointer:
6663 if (CanTy->isMemberDataPointerType())
6664 return offset_type_class;
6665 else {
6666 // We expect member pointers to be either data or function pointers,
6667 // nothing else.
6668 assert(CanTy->isMemberFunctionPointerType());
6669 return method_type_class;
6670 }
6671
6672 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006673 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006674
6675 case Type::FunctionNoProto:
6676 case Type::FunctionProto:
6677 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6678
6679 case Type::Record:
6680 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6681 switch (RT->getDecl()->getTagKind()) {
6682 case TagTypeKind::TTK_Struct:
6683 case TagTypeKind::TTK_Class:
6684 case TagTypeKind::TTK_Interface:
6685 return record_type_class;
6686
6687 case TagTypeKind::TTK_Enum:
6688 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6689
6690 case TagTypeKind::TTK_Union:
6691 return union_type_class;
6692 }
6693 }
David Blaikie83d382b2011-09-23 05:06:16 +00006694 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006695
6696 case Type::ConstantArray:
6697 case Type::VariableArray:
6698 case Type::IncompleteArray:
6699 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6700
6701 case Type::BlockPointer:
6702 case Type::LValueReference:
6703 case Type::RValueReference:
6704 case Type::Vector:
6705 case Type::ExtVector:
6706 case Type::Auto:
6707 case Type::ObjCObject:
6708 case Type::ObjCInterface:
6709 case Type::ObjCObjectPointer:
6710 case Type::Pipe:
6711 case Type::Atomic:
6712 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6713 }
6714
6715 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006716}
6717
Richard Smith5fab0c92011-12-28 19:48:30 +00006718/// EvaluateBuiltinConstantPForLValue - Determine the result of
6719/// __builtin_constant_p when applied to the given lvalue.
6720///
6721/// An lvalue is only "constant" if it is a pointer or reference to the first
6722/// character of a string literal.
6723template<typename LValue>
6724static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006725 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006726 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6727}
6728
6729/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6730/// GCC as we can manage.
6731static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6732 QualType ArgType = Arg->getType();
6733
6734 // __builtin_constant_p always has one operand. The rules which gcc follows
6735 // are not precisely documented, but are as follows:
6736 //
6737 // - If the operand is of integral, floating, complex or enumeration type,
6738 // and can be folded to a known value of that type, it returns 1.
6739 // - If the operand and can be folded to a pointer to the first character
6740 // of a string literal (or such a pointer cast to an integral type), it
6741 // returns 1.
6742 //
6743 // Otherwise, it returns 0.
6744 //
6745 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6746 // its support for this does not currently work.
6747 if (ArgType->isIntegralOrEnumerationType()) {
6748 Expr::EvalResult Result;
6749 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6750 return false;
6751
6752 APValue &V = Result.Val;
6753 if (V.getKind() == APValue::Int)
6754 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006755 if (V.getKind() == APValue::LValue)
6756 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006757 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6758 return Arg->isEvaluatable(Ctx);
6759 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6760 LValue LV;
6761 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006762 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006763 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6764 : EvaluatePointer(Arg, LV, Info)) &&
6765 !Status.HasSideEffects)
6766 return EvaluateBuiltinConstantPForLValue(LV);
6767 }
6768
6769 // Anything else isn't considered to be sufficiently constant.
6770 return false;
6771}
6772
John McCall95007602010-05-10 23:27:23 +00006773/// Retrieves the "underlying object type" of the given expression,
6774/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006775static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006776 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6777 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006778 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006779 } else if (const Expr *E = B.get<const Expr*>()) {
6780 if (isa<CompoundLiteralExpr>(E))
6781 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006782 }
6783
6784 return QualType();
6785}
6786
George Burgess IV3a03fab2015-09-04 21:28:13 +00006787/// A more selective version of E->IgnoreParenCasts for
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006788/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00006789/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006790/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6791///
6792/// Always returns an RValue with a pointer representation.
6793static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6794 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6795
6796 auto *NoParens = E->IgnoreParens();
6797 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006798 if (Cast == nullptr)
6799 return NoParens;
6800
6801 // We only conservatively allow a few kinds of casts, because this code is
6802 // inherently a simple solution that seeks to support the common case.
6803 auto CastKind = Cast->getCastKind();
6804 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6805 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006806 return NoParens;
6807
6808 auto *SubExpr = Cast->getSubExpr();
6809 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6810 return NoParens;
6811 return ignorePointerCastsAndParens(SubExpr);
6812}
6813
George Burgess IVa51c4072015-10-16 01:49:01 +00006814/// Checks to see if the given LValue's Designator is at the end of the LValue's
6815/// record layout. e.g.
6816/// struct { struct { int a, b; } fst, snd; } obj;
6817/// obj.fst // no
6818/// obj.snd // yes
6819/// obj.fst.a // no
6820/// obj.fst.b // no
6821/// obj.snd.a // no
6822/// obj.snd.b // yes
6823///
6824/// Please note: this function is specialized for how __builtin_object_size
6825/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006826///
6827/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006828static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6829 assert(!LVal.Designator.Invalid);
6830
George Burgess IV4168d752016-06-27 19:40:41 +00006831 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6832 const RecordDecl *Parent = FD->getParent();
6833 Invalid = Parent->isInvalidDecl();
6834 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006835 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006836 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006837 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6838 };
6839
6840 auto &Base = LVal.getLValueBase();
6841 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6842 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006843 bool Invalid;
6844 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6845 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006846 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006847 for (auto *FD : IFD->chain()) {
6848 bool Invalid;
6849 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6850 return Invalid;
6851 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006852 }
6853 }
6854
6855 QualType BaseType = getType(Base);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006856 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
George Burgess IVa51c4072015-10-16 01:49:01 +00006857 if (BaseType->isArrayType()) {
6858 // Because __builtin_object_size treats arrays as objects, we can ignore
6859 // the index iff this is the last array in the Designator.
6860 if (I + 1 == E)
6861 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006862 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6863 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00006864 if (Index + 1 != CAT->getSize())
6865 return false;
6866 BaseType = CAT->getElementType();
6867 } else if (BaseType->isAnyComplexType()) {
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006868 auto *CT = BaseType->castAs<ComplexType>();
6869 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00006870 if (Index != 1)
6871 return false;
6872 BaseType = CT->getElementType();
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006873 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006874 bool Invalid;
6875 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6876 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006877 BaseType = FD->getType();
6878 } else {
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006879 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6880 "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00006881 return false;
6882 }
6883 }
6884 return true;
6885}
6886
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006887/// Tests to see if the LValue has a designator (that isn't necessarily valid).
George Burgess IVa51c4072015-10-16 01:49:01 +00006888static bool refersToCompleteObject(const LValue &LVal) {
6889 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6890 return false;
6891
6892 if (!LVal.InvalidBase)
6893 return true;
6894
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006895 auto *E = LVal.Base.dyn_cast<const Expr *>();
6896 (void)E;
6897 assert(E != nullptr && isa<MemberExpr>(E));
6898 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006899}
6900
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006901/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6902/// true and stores the result in @p Size.
George Burgess IVa7470272016-12-20 01:05:42 +00006903///
6904/// If @p WasError is non-null, this will report whether the failure to evaluate
6905/// is to be treated as an Error in IntExprEvaluator.
6906static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006907 EvalInfo &Info, uint64_t &Size,
6908 bool *WasError = nullptr) {
6909 if (WasError != nullptr)
6910 *WasError = false;
6911
6912 auto Error = [&](const Expr *E) {
6913 if (WasError != nullptr)
6914 *WasError = true;
6915 return false;
6916 };
6917
6918 auto Success = [&](uint64_t S, const Expr *E) {
6919 Size = S;
6920 return true;
6921 };
6922
George Burgess IVa7470272016-12-20 01:05:42 +00006923 // Determine the denoted object.
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006924 LValue Base;
George Burgess IVa7470272016-12-20 01:05:42 +00006925 {
6926 // The operand of __builtin_object_size is never evaluated for side-effects.
6927 // If there are any, but we can determine the pointed-to object anyway, then
6928 // ignore the side-effects.
6929 SpeculativeEvaluationRAII SpeculativeEval(Info);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006930 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IVa7470272016-12-20 01:05:42 +00006931
6932 if (E->isGLValue()) {
6933 // It's possible for us to be given GLValues if we're called via
6934 // Expr::tryEvaluateObjectSize.
6935 APValue RVal;
6936 if (!EvaluateAsRValue(Info, E, RVal))
6937 return false;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006938 Base.setFrom(Info.Ctx, RVal);
6939 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
George Burgess IVa7470272016-12-20 01:05:42 +00006940 return false;
6941 }
6942
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006943 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IVa7470272016-12-20 01:05:42 +00006944 // If we point to before the start of the object, there are no accessible
6945 // bytes.
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006946 if (BaseOffset.isNegative())
6947 return Success(0, E);
6948
6949 // In the case where we're not dealing with a subobject, we discard the
6950 // subobject bit.
6951 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
6952
6953 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6954 // exist. If we can't verify the base, then we can't do that.
6955 //
6956 // As a special case, we produce a valid object size for an unknown object
6957 // with a known designator if Type & 1 is 1. For instance:
6958 //
6959 // extern struct X { char buff[32]; int a, b, c; } *p;
6960 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6961 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6962 //
6963 // This matches GCC's behavior.
6964 if (Base.InvalidBase && !SubobjectOnly)
6965 return Error(E);
6966
6967 // If we're not examining only the subobject, then we reset to a complete
6968 // object designator
6969 //
6970 // If Type is 1 and we've lost track of the subobject, just find the complete
6971 // object instead. (If Type is 3, that's not correct behavior and we should
6972 // return 0 instead.)
6973 LValue End = Base;
6974 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
6975 QualType T = getObjectType(End.getLValueBase());
6976 if (T.isNull())
6977 End.Designator.setInvalid();
6978 else {
6979 End.Designator = SubobjectDesignator(T);
6980 End.Offset = CharUnits::Zero();
6981 }
George Burgess IVa7470272016-12-20 01:05:42 +00006982 }
6983
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006984 // If it is not possible to determine which objects ptr points to at compile
6985 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6986 // and (size_t) 0 for type 2 or 3.
6987 if (End.Designator.Invalid)
George Burgess IVa7470272016-12-20 01:05:42 +00006988 return false;
6989
Chandler Carruthd7738fe2016-12-20 08:28:19 +00006990 // According to the GCC documentation, we want the size of the subobject
6991 // denoted by the pointer. But that's not quite right -- what we actually
6992 // want is the size of the immediately-enclosing array, if there is one.
6993 int64_t AmountToAdd = 1;
6994 if (End.Designator.MostDerivedIsArrayElement &&
6995 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6996 // We got a pointer to an array. Step to its end.
6997 AmountToAdd = End.Designator.MostDerivedArraySize -
6998 End.Designator.Entries.back().ArrayIndex;
6999 } else if (End.Designator.isOnePastTheEnd()) {
7000 // We're already pointing at the end of the object.
7001 AmountToAdd = 0;
7002 }
7003
7004 QualType PointeeType = End.Designator.MostDerivedType;
7005 assert(!PointeeType.isNull());
7006 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
7007 return Error(E);
7008
7009 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
7010 AmountToAdd))
7011 return false;
7012
7013 auto EndOffset = End.getLValueOffset();
7014
7015 // The following is a moderately common idiom in C:
7016 //
7017 // struct Foo { int a; char c[1]; };
7018 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7019 // strcpy(&F->c[0], Bar);
7020 //
7021 // So, if we see that we're examining an array at the end of a struct with an
7022 // unknown base, we give up instead of breaking code that behaves this way.
7023 // Note that we only do this when Type=1, because Type=3 is a lower bound, so
7024 // answering conservatively is fine.
7025 //
7026 // We used to be a bit more aggressive here; we'd only be conservative if the
7027 // array at the end was flexible, or if it had 0 or 1 elements. This broke
7028 // some common standard library extensions (PR30346), but was otherwise
7029 // seemingly fine. It may be useful to reintroduce this behavior with some
7030 // sort of whitelist. OTOH, it seems that GCC is always conservative with the
7031 // last element in structs (if it's an array), so our current behavior is more
7032 // compatible than a whitelisting approach would be.
7033 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
7034 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
7035 End.Designator.MostDerivedIsArrayElement &&
7036 isDesignatorAtObjectEnd(Info.Ctx, End))
7037 return false;
7038
7039 if (BaseOffset > EndOffset)
7040 return Success(0, E);
7041
7042 return Success((EndOffset - BaseOffset).getQuantity(), E);
7043}
7044
7045bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
7046 unsigned Type) {
7047 uint64_t Size;
7048 bool WasError;
7049 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
7050 return Success(Size, E);
7051 if (WasError)
7052 return Error(E);
7053 return false;
John McCall95007602010-05-10 23:27:23 +00007054}
7055
Peter Collingbournee9200682011-05-13 03:29:01 +00007056bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007057 if (unsigned BuiltinOp = E->getBuiltinCallee())
7058 return VisitBuiltinCallExpr(E, BuiltinOp);
7059
7060 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7061}
7062
7063bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7064 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007065 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007066 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007067 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007068
7069 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007070 // The type was checked when we built the expression.
7071 unsigned Type =
7072 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7073 assert(Type <= 3 && "unexpected type");
7074
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007075 if (TryEvaluateBuiltinObjectSize(E, Type))
7076 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00007077
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007078 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007079 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007080
Richard Smith01ade172012-05-23 04:13:20 +00007081 // Expression had no side effects, but we couldn't statically determine the
7082 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007083 switch (Info.EvalMode) {
7084 case EvalInfo::EM_ConstantExpression:
7085 case EvalInfo::EM_PotentialConstantExpression:
7086 case EvalInfo::EM_ConstantFold:
7087 case EvalInfo::EM_EvaluateForOverflow:
7088 case EvalInfo::EM_IgnoreSideEffects:
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007089 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007090 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007091 return Error(E);
7092 case EvalInfo::EM_ConstantExpressionUnevaluated:
7093 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007094 // Reduce it to a constant now.
7095 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007096 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007097
7098 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007099 }
7100
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007101 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007102 case Builtin::BI__builtin_bswap32:
7103 case Builtin::BI__builtin_bswap64: {
7104 APSInt Val;
7105 if (!EvaluateInteger(E->getArg(0), Val, Info))
7106 return false;
7107
7108 return Success(Val.byteSwap(), E);
7109 }
7110
Richard Smith8889a3d2013-06-13 06:26:32 +00007111 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007112 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007113
7114 // FIXME: BI__builtin_clrsb
7115 // FIXME: BI__builtin_clrsbl
7116 // FIXME: BI__builtin_clrsbll
7117
Richard Smith80b3c8e2013-06-13 05:04:16 +00007118 case Builtin::BI__builtin_clz:
7119 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007120 case Builtin::BI__builtin_clzll:
7121 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007122 APSInt Val;
7123 if (!EvaluateInteger(E->getArg(0), Val, Info))
7124 return false;
7125 if (!Val)
7126 return Error(E);
7127
7128 return Success(Val.countLeadingZeros(), E);
7129 }
7130
Richard Smith8889a3d2013-06-13 06:26:32 +00007131 case Builtin::BI__builtin_constant_p:
7132 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7133
Richard Smith80b3c8e2013-06-13 05:04:16 +00007134 case Builtin::BI__builtin_ctz:
7135 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007136 case Builtin::BI__builtin_ctzll:
7137 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007138 APSInt Val;
7139 if (!EvaluateInteger(E->getArg(0), Val, Info))
7140 return false;
7141 if (!Val)
7142 return Error(E);
7143
7144 return Success(Val.countTrailingZeros(), E);
7145 }
7146
Richard Smith8889a3d2013-06-13 06:26:32 +00007147 case Builtin::BI__builtin_eh_return_data_regno: {
7148 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7149 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7150 return Success(Operand, E);
7151 }
7152
7153 case Builtin::BI__builtin_expect:
7154 return Visit(E->getArg(0));
7155
7156 case Builtin::BI__builtin_ffs:
7157 case Builtin::BI__builtin_ffsl:
7158 case Builtin::BI__builtin_ffsll: {
7159 APSInt Val;
7160 if (!EvaluateInteger(E->getArg(0), Val, Info))
7161 return false;
7162
7163 unsigned N = Val.countTrailingZeros();
7164 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7165 }
7166
7167 case Builtin::BI__builtin_fpclassify: {
7168 APFloat Val(0.0);
7169 if (!EvaluateFloat(E->getArg(5), Val, Info))
7170 return false;
7171 unsigned Arg;
7172 switch (Val.getCategory()) {
7173 case APFloat::fcNaN: Arg = 0; break;
7174 case APFloat::fcInfinity: Arg = 1; break;
7175 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7176 case APFloat::fcZero: Arg = 4; break;
7177 }
7178 return Visit(E->getArg(Arg));
7179 }
7180
7181 case Builtin::BI__builtin_isinf_sign: {
7182 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007183 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007184 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7185 }
7186
Richard Smithea3019d2013-10-15 19:07:14 +00007187 case Builtin::BI__builtin_isinf: {
7188 APFloat Val(0.0);
7189 return EvaluateFloat(E->getArg(0), Val, Info) &&
7190 Success(Val.isInfinity() ? 1 : 0, E);
7191 }
7192
7193 case Builtin::BI__builtin_isfinite: {
7194 APFloat Val(0.0);
7195 return EvaluateFloat(E->getArg(0), Val, Info) &&
7196 Success(Val.isFinite() ? 1 : 0, E);
7197 }
7198
7199 case Builtin::BI__builtin_isnan: {
7200 APFloat Val(0.0);
7201 return EvaluateFloat(E->getArg(0), Val, Info) &&
7202 Success(Val.isNaN() ? 1 : 0, E);
7203 }
7204
7205 case Builtin::BI__builtin_isnormal: {
7206 APFloat Val(0.0);
7207 return EvaluateFloat(E->getArg(0), Val, Info) &&
7208 Success(Val.isNormal() ? 1 : 0, E);
7209 }
7210
Richard Smith8889a3d2013-06-13 06:26:32 +00007211 case Builtin::BI__builtin_parity:
7212 case Builtin::BI__builtin_parityl:
7213 case Builtin::BI__builtin_parityll: {
7214 APSInt Val;
7215 if (!EvaluateInteger(E->getArg(0), Val, Info))
7216 return false;
7217
7218 return Success(Val.countPopulation() % 2, E);
7219 }
7220
Richard Smith80b3c8e2013-06-13 05:04:16 +00007221 case Builtin::BI__builtin_popcount:
7222 case Builtin::BI__builtin_popcountl:
7223 case Builtin::BI__builtin_popcountll: {
7224 APSInt Val;
7225 if (!EvaluateInteger(E->getArg(0), Val, Info))
7226 return false;
7227
7228 return Success(Val.countPopulation(), E);
7229 }
7230
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007231 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007232 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007233 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007234 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007235 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007236 << /*isConstexpr*/0 << /*isConstructor*/0
7237 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007238 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007239 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007240 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007241 case Builtin::BI__builtin_strlen:
7242 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007243 // As an extension, we support __builtin_strlen() as a constant expression,
7244 // and support folding strlen() to a constant.
7245 LValue String;
7246 if (!EvaluatePointer(E->getArg(0), String, Info))
7247 return false;
7248
Richard Smith8110c9d2016-11-29 19:45:17 +00007249 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7250
Richard Smithe6c19f22013-11-15 02:10:04 +00007251 // Fast path: if it's a string literal, search the string value.
7252 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7253 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007254 // The string literal may have embedded null characters. Find the first
7255 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007256 StringRef Str = S->getBytes();
7257 int64_t Off = String.Offset.getQuantity();
7258 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007259 S->getCharByteWidth() == 1 &&
7260 // FIXME: Add fast-path for wchar_t too.
7261 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007262 Str = Str.substr(Off);
7263
7264 StringRef::size_type Pos = Str.find(0);
7265 if (Pos != StringRef::npos)
7266 Str = Str.substr(0, Pos);
7267
7268 return Success(Str.size(), E);
7269 }
7270
7271 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007272 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007273
7274 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007275 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7276 APValue Char;
7277 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7278 !Char.isInt())
7279 return false;
7280 if (!Char.getInt())
7281 return Success(Strlen, E);
7282 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7283 return false;
7284 }
7285 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007286
Richard Smithe151bab2016-11-11 23:43:35 +00007287 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007288 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007289 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007290 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007291 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007292 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007293 // A call to strlen is not a constant expression.
7294 if (Info.getLangOpts().CPlusPlus11)
7295 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7296 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007297 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007298 else
7299 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7300 // Fall through.
7301 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007302 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007303 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007304 case Builtin::BI__builtin_wcsncmp:
7305 case Builtin::BI__builtin_memcmp:
7306 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007307 LValue String1, String2;
7308 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7309 !EvaluatePointer(E->getArg(1), String2, Info))
7310 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007311
7312 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7313
Richard Smithe151bab2016-11-11 23:43:35 +00007314 uint64_t MaxLength = uint64_t(-1);
7315 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007316 BuiltinOp != Builtin::BIwcscmp &&
7317 BuiltinOp != Builtin::BI__builtin_strcmp &&
7318 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007319 APSInt N;
7320 if (!EvaluateInteger(E->getArg(2), N, Info))
7321 return false;
7322 MaxLength = N.getExtValue();
7323 }
7324 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007325 BuiltinOp != Builtin::BIwmemcmp &&
7326 BuiltinOp != Builtin::BI__builtin_memcmp &&
7327 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007328 for (; MaxLength; --MaxLength) {
7329 APValue Char1, Char2;
7330 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7331 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7332 !Char1.isInt() || !Char2.isInt())
7333 return false;
7334 if (Char1.getInt() != Char2.getInt())
7335 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7336 if (StopAtNull && !Char1.getInt())
7337 return Success(0, E);
7338 assert(!(StopAtNull && !Char2.getInt()));
7339 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7340 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7341 return false;
7342 }
7343 // We hit the strncmp / memcmp limit.
7344 return Success(0, E);
7345 }
7346
Richard Smith01ba47d2012-04-13 00:45:38 +00007347 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007348 case Builtin::BI__atomic_is_lock_free:
7349 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007350 APSInt SizeVal;
7351 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7352 return false;
7353
7354 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7355 // of two less than the maximum inline atomic width, we know it is
7356 // lock-free. If the size isn't a power of two, or greater than the
7357 // maximum alignment where we promote atomics, we know it is not lock-free
7358 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7359 // the answer can only be determined at runtime; for example, 16-byte
7360 // atomics have lock-free implementations on some, but not all,
7361 // x86-64 processors.
7362
7363 // Check power-of-two.
7364 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007365 if (Size.isPowerOfTwo()) {
7366 // Check against inlining width.
7367 unsigned InlineWidthBits =
7368 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7369 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7370 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7371 Size == CharUnits::One() ||
7372 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7373 Expr::NPC_NeverValueDependent))
7374 // OK, we will inline appropriately-aligned operations of this size,
7375 // and _Atomic(T) is appropriately-aligned.
7376 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007377
Richard Smith01ba47d2012-04-13 00:45:38 +00007378 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7379 castAs<PointerType>()->getPointeeType();
7380 if (!PointeeType->isIncompleteType() &&
7381 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7382 // OK, we will inline operations on this object.
7383 return Success(1, E);
7384 }
7385 }
7386 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007387
Richard Smith01ba47d2012-04-13 00:45:38 +00007388 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7389 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007390 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007391 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007392}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007393
Richard Smith8b3497e2011-10-31 01:37:14 +00007394static bool HasSameBase(const LValue &A, const LValue &B) {
7395 if (!A.getLValueBase())
7396 return !B.getLValueBase();
7397 if (!B.getLValueBase())
7398 return false;
7399
Richard Smithce40ad62011-11-12 22:28:03 +00007400 if (A.getLValueBase().getOpaqueValue() !=
7401 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007402 const Decl *ADecl = GetLValueBaseDecl(A);
7403 if (!ADecl)
7404 return false;
7405 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007406 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007407 return false;
7408 }
7409
7410 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007411 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007412}
7413
Richard Smithd20f1e62014-10-21 23:01:04 +00007414/// \brief Determine whether this is a pointer past the end of the complete
7415/// object referred to by the lvalue.
7416static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7417 const LValue &LV) {
7418 // A null pointer can be viewed as being "past the end" but we don't
7419 // choose to look at it that way here.
7420 if (!LV.getLValueBase())
7421 return false;
7422
7423 // If the designator is valid and refers to a subobject, we're not pointing
7424 // past the end.
7425 if (!LV.getLValueDesignator().Invalid &&
7426 !LV.getLValueDesignator().isOnePastTheEnd())
7427 return false;
7428
David Majnemerc378ca52015-08-29 08:32:55 +00007429 // A pointer to an incomplete type might be past-the-end if the type's size is
7430 // zero. We cannot tell because the type is incomplete.
7431 QualType Ty = getType(LV.getLValueBase());
7432 if (Ty->isIncompleteType())
7433 return true;
7434
Richard Smithd20f1e62014-10-21 23:01:04 +00007435 // We're a past-the-end pointer if we point to the byte after the object,
7436 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007437 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007438 return LV.getLValueOffset() == Size;
7439}
7440
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007441namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007442
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007443/// \brief Data recursive integer evaluator of certain binary operators.
7444///
7445/// We use a data recursive algorithm for binary operators so that we are able
7446/// to handle extreme cases of chained binary operators without causing stack
7447/// overflow.
7448class DataRecursiveIntBinOpEvaluator {
7449 struct EvalResult {
7450 APValue Val;
7451 bool Failed;
7452
7453 EvalResult() : Failed(false) { }
7454
7455 void swap(EvalResult &RHS) {
7456 Val.swap(RHS.Val);
7457 Failed = RHS.Failed;
7458 RHS.Failed = false;
7459 }
7460 };
7461
7462 struct Job {
7463 const Expr *E;
7464 EvalResult LHSResult; // meaningful only for binary operator expression.
7465 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007466
David Blaikie73726062015-08-12 23:09:24 +00007467 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007468 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007469
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007470 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007471 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007472 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007473
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007474 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007475 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007476 };
7477
7478 SmallVector<Job, 16> Queue;
7479
7480 IntExprEvaluator &IntEval;
7481 EvalInfo &Info;
7482 APValue &FinalResult;
7483
7484public:
7485 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7486 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7487
7488 /// \brief True if \param E is a binary operator that we are going to handle
7489 /// data recursively.
7490 /// We handle binary operators that are comma, logical, or that have operands
7491 /// with integral or enumeration type.
7492 static bool shouldEnqueue(const BinaryOperator *E) {
7493 return E->getOpcode() == BO_Comma ||
7494 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007495 (E->isRValue() &&
7496 E->getType()->isIntegralOrEnumerationType() &&
7497 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007498 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007499 }
7500
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007501 bool Traverse(const BinaryOperator *E) {
7502 enqueue(E);
7503 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007504 while (!Queue.empty())
7505 process(PrevResult);
7506
7507 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007508
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007509 FinalResult.swap(PrevResult.Val);
7510 return true;
7511 }
7512
7513private:
7514 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7515 return IntEval.Success(Value, E, Result);
7516 }
7517 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7518 return IntEval.Success(Value, E, Result);
7519 }
7520 bool Error(const Expr *E) {
7521 return IntEval.Error(E);
7522 }
7523 bool Error(const Expr *E, diag::kind D) {
7524 return IntEval.Error(E, D);
7525 }
7526
7527 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7528 return Info.CCEDiag(E, D);
7529 }
7530
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007531 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7532 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007533 bool &SuppressRHSDiags);
7534
7535 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7536 const BinaryOperator *E, APValue &Result);
7537
7538 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7539 Result.Failed = !Evaluate(Result.Val, Info, E);
7540 if (Result.Failed)
7541 Result.Val = APValue();
7542 }
7543
Richard Trieuba4d0872012-03-21 23:30:30 +00007544 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007545
7546 void enqueue(const Expr *E) {
7547 E = E->IgnoreParens();
7548 Queue.resize(Queue.size()+1);
7549 Queue.back().E = E;
7550 Queue.back().Kind = Job::AnyExprKind;
7551 }
7552};
7553
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007554}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007555
7556bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007557 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007558 bool &SuppressRHSDiags) {
7559 if (E->getOpcode() == BO_Comma) {
7560 // Ignore LHS but note if we could not evaluate it.
7561 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007562 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007563 return true;
7564 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007565
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007566 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007567 bool LHSAsBool;
7568 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007569 // We were able to evaluate the LHS, see if we can get away with not
7570 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007571 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7572 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007573 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007574 }
7575 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007576 LHSResult.Failed = true;
7577
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007578 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007579 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007580 if (!Info.noteSideEffect())
7581 return false;
7582
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007583 // We can't evaluate the LHS; however, sometimes the result
7584 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7585 // Don't ignore RHS and suppress diagnostics from this arm.
7586 SuppressRHSDiags = true;
7587 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007588
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007589 return true;
7590 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007591
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007592 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7593 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007594
George Burgess IVa145e252016-05-25 22:38:36 +00007595 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007596 return false; // Ignore RHS;
7597
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007598 return true;
7599}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007600
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007601bool DataRecursiveIntBinOpEvaluator::
7602 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7603 const BinaryOperator *E, APValue &Result) {
7604 if (E->getOpcode() == BO_Comma) {
7605 if (RHSResult.Failed)
7606 return false;
7607 Result = RHSResult.Val;
7608 return true;
7609 }
7610
7611 if (E->isLogicalOp()) {
7612 bool lhsResult, rhsResult;
7613 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7614 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7615
7616 if (LHSIsOK) {
7617 if (RHSIsOK) {
7618 if (E->getOpcode() == BO_LOr)
7619 return Success(lhsResult || rhsResult, E, Result);
7620 else
7621 return Success(lhsResult && rhsResult, E, Result);
7622 }
7623 } else {
7624 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007625 // We can't evaluate the LHS; however, sometimes the result
7626 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7627 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007628 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007629 }
7630 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007631
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007632 return false;
7633 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007634
7635 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7636 E->getRHS()->getType()->isIntegralOrEnumerationType());
7637
7638 if (LHSResult.Failed || RHSResult.Failed)
7639 return false;
7640
7641 const APValue &LHSVal = LHSResult.Val;
7642 const APValue &RHSVal = RHSResult.Val;
7643
7644 // Handle cases like (unsigned long)&a + 4.
7645 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7646 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007647 CharUnits AdditionalOffset =
7648 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007649 if (E->getOpcode() == BO_Add)
7650 Result.getLValueOffset() += AdditionalOffset;
7651 else
7652 Result.getLValueOffset() -= AdditionalOffset;
7653 return true;
7654 }
7655
7656 // Handle cases like 4 + (unsigned long)&a
7657 if (E->getOpcode() == BO_Add &&
7658 RHSVal.isLValue() && LHSVal.isInt()) {
7659 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007660 Result.getLValueOffset() +=
7661 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007662 return true;
7663 }
7664
7665 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7666 // Handle (intptr_t)&&A - (intptr_t)&&B.
7667 if (!LHSVal.getLValueOffset().isZero() ||
7668 !RHSVal.getLValueOffset().isZero())
7669 return false;
7670 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7671 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7672 if (!LHSExpr || !RHSExpr)
7673 return false;
7674 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7675 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7676 if (!LHSAddrExpr || !RHSAddrExpr)
7677 return false;
7678 // Make sure both labels come from the same function.
7679 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7680 RHSAddrExpr->getLabel()->getDeclContext())
7681 return false;
7682 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7683 return true;
7684 }
Richard Smith43e77732013-05-07 04:50:00 +00007685
7686 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007687 if (!LHSVal.isInt() || !RHSVal.isInt())
7688 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007689
7690 // Set up the width and signedness manually, in case it can't be deduced
7691 // from the operation we're performing.
7692 // FIXME: Don't do this in the cases where we can deduce it.
7693 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7694 E->getType()->isUnsignedIntegerOrEnumerationType());
7695 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7696 RHSVal.getInt(), Value))
7697 return false;
7698 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007699}
7700
Richard Trieuba4d0872012-03-21 23:30:30 +00007701void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007702 Job &job = Queue.back();
7703
7704 switch (job.Kind) {
7705 case Job::AnyExprKind: {
7706 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7707 if (shouldEnqueue(Bop)) {
7708 job.Kind = Job::BinOpKind;
7709 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007710 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007711 }
7712 }
7713
7714 EvaluateExpr(job.E, Result);
7715 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007716 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007717 }
7718
7719 case Job::BinOpKind: {
7720 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007721 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007722 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007723 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007724 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007725 }
7726 if (SuppressRHSDiags)
7727 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007728 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007729 job.Kind = Job::BinOpVisitedLHSKind;
7730 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007731 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007732 }
7733
7734 case Job::BinOpVisitedLHSKind: {
7735 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7736 EvalResult RHS;
7737 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007738 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007739 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007740 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007741 }
7742 }
7743
7744 llvm_unreachable("Invalid Job::Kind!");
7745}
7746
George Burgess IV8c892b52016-05-25 22:31:54 +00007747namespace {
7748/// Used when we determine that we should fail, but can keep evaluating prior to
7749/// noting that we had a failure.
7750class DelayedNoteFailureRAII {
7751 EvalInfo &Info;
7752 bool NoteFailure;
7753
7754public:
7755 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7756 : Info(Info), NoteFailure(NoteFailure) {}
7757 ~DelayedNoteFailureRAII() {
7758 if (NoteFailure) {
7759 bool ContinueAfterFailure = Info.noteFailure();
7760 (void)ContinueAfterFailure;
7761 assert(ContinueAfterFailure &&
7762 "Shouldn't have kept evaluating on failure.");
7763 }
7764 }
7765};
7766}
7767
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007768bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007769 // We don't call noteFailure immediately because the assignment happens after
7770 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007771 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007772 return Error(E);
7773
George Burgess IV8c892b52016-05-25 22:31:54 +00007774 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007775 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7776 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007777
Anders Carlssonacc79812008-11-16 07:17:21 +00007778 QualType LHSTy = E->getLHS()->getType();
7779 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007780
Chandler Carruthb29a7432014-10-11 11:03:30 +00007781 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007782 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007783 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007784 if (E->isAssignmentOp()) {
7785 LValue LV;
7786 EvaluateLValue(E->getLHS(), LV, Info);
7787 LHSOK = false;
7788 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007789 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7790 if (LHSOK) {
7791 LHS.makeComplexFloat();
7792 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7793 }
7794 } else {
7795 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7796 }
George Burgess IVa145e252016-05-25 22:38:36 +00007797 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007798 return false;
7799
Chandler Carruthb29a7432014-10-11 11:03:30 +00007800 if (E->getRHS()->getType()->isRealFloatingType()) {
7801 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7802 return false;
7803 RHS.makeComplexFloat();
7804 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7805 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007806 return false;
7807
7808 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007809 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007810 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007811 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007812 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7813
John McCalle3027922010-08-25 11:45:40 +00007814 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007815 return Success((CR_r == APFloat::cmpEqual &&
7816 CR_i == APFloat::cmpEqual), E);
7817 else {
John McCalle3027922010-08-25 11:45:40 +00007818 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007819 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007820 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007821 CR_r == APFloat::cmpLessThan ||
7822 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007823 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007824 CR_i == APFloat::cmpLessThan ||
7825 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007826 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007827 } else {
John McCalle3027922010-08-25 11:45:40 +00007828 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007829 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7830 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7831 else {
John McCalle3027922010-08-25 11:45:40 +00007832 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007833 "Invalid compex comparison.");
7834 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7835 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7836 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007837 }
7838 }
Mike Stump11289f42009-09-09 15:08:12 +00007839
Anders Carlssonacc79812008-11-16 07:17:21 +00007840 if (LHSTy->isRealFloatingType() &&
7841 RHSTy->isRealFloatingType()) {
7842 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007843
Richard Smith253c2a32012-01-27 01:14:48 +00007844 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007845 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007846 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007847
Richard Smith253c2a32012-01-27 01:14:48 +00007848 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007849 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007850
Anders Carlssonacc79812008-11-16 07:17:21 +00007851 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007852
Anders Carlssonacc79812008-11-16 07:17:21 +00007853 switch (E->getOpcode()) {
7854 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007855 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007856 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007857 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007858 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007859 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007860 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007861 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007862 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007863 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007864 E);
John McCalle3027922010-08-25 11:45:40 +00007865 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007866 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007867 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007868 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007869 || CR == APFloat::cmpLessThan
7870 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007871 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007872 }
Mike Stump11289f42009-09-09 15:08:12 +00007873
Eli Friedmana38da572009-04-28 19:17:36 +00007874 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007875 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007876 LValue LHSValue, RHSValue;
7877
7878 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007879 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007880 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007881
Richard Smith253c2a32012-01-27 01:14:48 +00007882 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007883 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007884
Richard Smith8b3497e2011-10-31 01:37:14 +00007885 // Reject differing bases from the normal codepath; we special-case
7886 // comparisons to null.
7887 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007888 if (E->getOpcode() == BO_Sub) {
7889 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007890 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007891 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007892 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007893 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007894 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007895 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007896 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7897 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7898 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007899 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007900 // Make sure both labels come from the same function.
7901 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7902 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007903 return Error(E);
7904 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007905 }
Richard Smith83c68212011-10-31 05:11:32 +00007906 // Inequalities and subtractions between unrelated pointers have
7907 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007908 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007909 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007910 // A constant address may compare equal to the address of a symbol.
7911 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007912 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007913 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7914 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007915 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007916 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007917 // distinct addresses. In clang, the result of such a comparison is
7918 // unspecified, so it is not a constant expression. However, we do know
7919 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007920 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7921 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007922 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007923 // We can't tell whether weak symbols will end up pointing to the same
7924 // object.
7925 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007926 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007927 // We can't compare the address of the start of one object with the
7928 // past-the-end address of another object, per C++ DR1652.
7929 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7930 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7931 (RHSValue.Base && RHSValue.Offset.isZero() &&
7932 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7933 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007934 // We can't tell whether an object is at the same address as another
7935 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007936 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7937 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007938 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007939 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007940 // (Note that clang defaults to -fmerge-all-constants, which can
7941 // lead to inconsistent results for comparisons involving the address
7942 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007943 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007944 }
Eli Friedman64004332009-03-23 04:38:34 +00007945
Richard Smith1b470412012-02-01 08:10:20 +00007946 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7947 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7948
Richard Smith84f6dcf2012-02-02 01:16:57 +00007949 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7950 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7951
John McCalle3027922010-08-25 11:45:40 +00007952 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007953 // C++11 [expr.add]p6:
7954 // Unless both pointers point to elements of the same array object, or
7955 // one past the last element of the array object, the behavior is
7956 // undefined.
7957 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7958 !AreElementsOfSameArray(getType(LHSValue.Base),
7959 LHSDesignator, RHSDesignator))
7960 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7961
Chris Lattner882bdf22010-04-20 17:13:14 +00007962 QualType Type = E->getLHS()->getType();
7963 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007964
Richard Smithd62306a2011-11-10 06:34:14 +00007965 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007966 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007967 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007968
Richard Smith84c6b3d2013-09-10 21:34:14 +00007969 // As an extension, a type may have zero size (empty struct or union in
7970 // C, array of zero length). Pointer subtraction in such cases has
7971 // undefined behavior, so is not constant.
7972 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007973 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007974 << ElementType;
7975 return false;
7976 }
7977
Richard Smith1b470412012-02-01 08:10:20 +00007978 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7979 // and produce incorrect results when it overflows. Such behavior
7980 // appears to be non-conforming, but is common, so perhaps we should
7981 // assume the standard intended for such cases to be undefined behavior
7982 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007983
Richard Smith1b470412012-02-01 08:10:20 +00007984 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7985 // overflow in the final conversion to ptrdiff_t.
7986 APSInt LHS(
7987 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7988 APSInt RHS(
7989 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7990 APSInt ElemSize(
7991 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7992 APSInt TrueResult = (LHS - RHS) / ElemSize;
7993 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7994
Richard Smith0c6124b2015-12-03 01:36:22 +00007995 if (Result.extend(65) != TrueResult &&
7996 !HandleOverflow(Info, E, TrueResult, E->getType()))
7997 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007998 return Success(Result, E);
7999 }
Richard Smithde21b242012-01-31 06:41:30 +00008000
8001 // C++11 [expr.rel]p3:
8002 // Pointers to void (after pointer conversions) can be compared, with a
8003 // result defined as follows: If both pointers represent the same
8004 // address or are both the null pointer value, the result is true if the
8005 // operator is <= or >= and false otherwise; otherwise the result is
8006 // unspecified.
8007 // We interpret this as applying to pointers to *cv* void.
8008 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008009 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008010 CCEDiag(E, diag::note_constexpr_void_comparison);
8011
Richard Smith84f6dcf2012-02-02 01:16:57 +00008012 // C++11 [expr.rel]p2:
8013 // - If two pointers point to non-static data members of the same object,
8014 // or to subobjects or array elements fo such members, recursively, the
8015 // pointer to the later declared member compares greater provided the
8016 // two members have the same access control and provided their class is
8017 // not a union.
8018 // [...]
8019 // - Otherwise pointer comparisons are unspecified.
8020 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8021 E->isRelationalOp()) {
8022 bool WasArrayIndex;
8023 unsigned Mismatch =
8024 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8025 RHSDesignator, WasArrayIndex);
8026 // At the point where the designators diverge, the comparison has a
8027 // specified value if:
8028 // - we are comparing array indices
8029 // - we are comparing fields of a union, or fields with the same access
8030 // Otherwise, the result is unspecified and thus the comparison is not a
8031 // constant expression.
8032 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8033 Mismatch < RHSDesignator.Entries.size()) {
8034 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8035 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8036 if (!LF && !RF)
8037 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8038 else if (!LF)
8039 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8040 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8041 << RF->getParent() << RF;
8042 else if (!RF)
8043 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8044 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8045 << LF->getParent() << LF;
8046 else if (!LF->getParent()->isUnion() &&
8047 LF->getAccess() != RF->getAccess())
8048 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8049 << LF << LF->getAccess() << RF << RF->getAccess()
8050 << LF->getParent();
8051 }
8052 }
8053
Eli Friedman6c31cb42012-04-16 04:30:08 +00008054 // The comparison here must be unsigned, and performed with the same
8055 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008056 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8057 uint64_t CompareLHS = LHSOffset.getQuantity();
8058 uint64_t CompareRHS = RHSOffset.getQuantity();
8059 assert(PtrSize <= 64 && "Unexpected pointer width");
8060 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8061 CompareLHS &= Mask;
8062 CompareRHS &= Mask;
8063
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008064 // If there is a base and this is a relational operator, we can only
8065 // compare pointers within the object in question; otherwise, the result
8066 // depends on where the object is located in memory.
8067 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8068 QualType BaseTy = getType(LHSValue.Base);
8069 if (BaseTy->isIncompleteType())
8070 return Error(E);
8071 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8072 uint64_t OffsetLimit = Size.getQuantity();
8073 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8074 return Error(E);
8075 }
8076
Richard Smith8b3497e2011-10-31 01:37:14 +00008077 switch (E->getOpcode()) {
8078 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008079 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8080 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8081 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8082 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8083 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8084 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008085 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008086 }
8087 }
Richard Smith7bb00672012-02-01 01:42:44 +00008088
8089 if (LHSTy->isMemberPointerType()) {
8090 assert(E->isEqualityOp() && "unexpected member pointer operation");
8091 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8092
8093 MemberPtr LHSValue, RHSValue;
8094
8095 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008096 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008097 return false;
8098
8099 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8100 return false;
8101
8102 // C++11 [expr.eq]p2:
8103 // If both operands are null, they compare equal. Otherwise if only one is
8104 // null, they compare unequal.
8105 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8106 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8107 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8108 }
8109
8110 // Otherwise if either is a pointer to a virtual member function, the
8111 // result is unspecified.
8112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8113 if (MD->isVirtual())
8114 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8115 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8116 if (MD->isVirtual())
8117 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8118
8119 // Otherwise they compare equal if and only if they would refer to the
8120 // same member of the same most derived object or the same subobject if
8121 // they were dereferenced with a hypothetical object of the associated
8122 // class type.
8123 bool Equal = LHSValue == RHSValue;
8124 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8125 }
8126
Richard Smithab44d9b2012-02-14 22:35:28 +00008127 if (LHSTy->isNullPtrType()) {
8128 assert(E->isComparisonOp() && "unexpected nullptr operation");
8129 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8130 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8131 // are compared, the result is true of the operator is <=, >= or ==, and
8132 // false otherwise.
8133 BinaryOperator::Opcode Opcode = E->getOpcode();
8134 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8135 }
8136
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008137 assert((!LHSTy->isIntegralOrEnumerationType() ||
8138 !RHSTy->isIntegralOrEnumerationType()) &&
8139 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8140 // We can't continue from here for non-integral types.
8141 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008142}
8143
Peter Collingbournee190dee2011-03-11 19:24:49 +00008144/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8145/// a result as the expression's type.
8146bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8147 const UnaryExprOrTypeTraitExpr *E) {
8148 switch(E->getKind()) {
8149 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008150 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008151 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008152 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008153 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008154 }
Eli Friedman64004332009-03-23 04:38:34 +00008155
Peter Collingbournee190dee2011-03-11 19:24:49 +00008156 case UETT_VecStep: {
8157 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008158
Peter Collingbournee190dee2011-03-11 19:24:49 +00008159 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008160 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008161
Peter Collingbournee190dee2011-03-11 19:24:49 +00008162 // The vec_step built-in functions that take a 3-component
8163 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8164 if (n == 3)
8165 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008166
Peter Collingbournee190dee2011-03-11 19:24:49 +00008167 return Success(n, E);
8168 } else
8169 return Success(1, E);
8170 }
8171
8172 case UETT_SizeOf: {
8173 QualType SrcTy = E->getTypeOfArgument();
8174 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8175 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008176 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8177 SrcTy = Ref->getPointeeType();
8178
Richard Smithd62306a2011-11-10 06:34:14 +00008179 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008180 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008181 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008182 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008183 }
Alexey Bataev00396512015-07-02 03:40:19 +00008184 case UETT_OpenMPRequiredSimdAlign:
8185 assert(E->isArgumentType());
8186 return Success(
8187 Info.Ctx.toCharUnitsFromBits(
8188 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8189 .getQuantity(),
8190 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008191 }
8192
8193 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008194}
8195
Peter Collingbournee9200682011-05-13 03:29:01 +00008196bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008197 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008198 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008199 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008200 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008201 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008202 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008203 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008204 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008205 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008206 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008207 APSInt IdxResult;
8208 if (!EvaluateInteger(Idx, IdxResult, Info))
8209 return false;
8210 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8211 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008212 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008213 CurrentType = AT->getElementType();
8214 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8215 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008216 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008217 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008218
James Y Knight7281c352015-12-29 22:31:18 +00008219 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008220 FieldDecl *MemberDecl = ON.getField();
8221 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008222 if (!RT)
8223 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008224 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008225 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008226 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008227 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008228 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008229 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008230 CurrentType = MemberDecl->getType().getNonReferenceType();
8231 break;
8232 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008233
James Y Knight7281c352015-12-29 22:31:18 +00008234 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008235 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008236
James Y Knight7281c352015-12-29 22:31:18 +00008237 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008238 CXXBaseSpecifier *BaseSpec = ON.getBase();
8239 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008240 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008241
8242 // Find the layout of the class whose base we are looking into.
8243 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008244 if (!RT)
8245 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008246 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008247 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008248 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8249
8250 // Find the base class itself.
8251 CurrentType = BaseSpec->getType();
8252 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8253 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008254 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008255
8256 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008257 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008258 break;
8259 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008260 }
8261 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008262 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008263}
8264
Chris Lattnere13042c2008-07-11 19:10:17 +00008265bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008266 switch (E->getOpcode()) {
8267 default:
8268 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8269 // See C99 6.6p3.
8270 return Error(E);
8271 case UO_Extension:
8272 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8273 // If so, we could clear the diagnostic ID.
8274 return Visit(E->getSubExpr());
8275 case UO_Plus:
8276 // The result is just the value.
8277 return Visit(E->getSubExpr());
8278 case UO_Minus: {
8279 if (!Visit(E->getSubExpr()))
8280 return false;
8281 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008282 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008283 if (Value.isSigned() && Value.isMinSignedValue() &&
8284 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8285 E->getType()))
8286 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008287 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008288 }
8289 case UO_Not: {
8290 if (!Visit(E->getSubExpr()))
8291 return false;
8292 if (!Result.isInt()) return Error(E);
8293 return Success(~Result.getInt(), E);
8294 }
8295 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008296 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008297 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008298 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008299 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008300 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008301 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008302}
Mike Stump11289f42009-09-09 15:08:12 +00008303
Chris Lattner477c4be2008-07-12 01:15:53 +00008304/// HandleCast - This is used to evaluate implicit or explicit casts where the
8305/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008306bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8307 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008308 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008309 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008310
Eli Friedmanc757de22011-03-25 00:43:55 +00008311 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008312 case CK_BaseToDerived:
8313 case CK_DerivedToBase:
8314 case CK_UncheckedDerivedToBase:
8315 case CK_Dynamic:
8316 case CK_ToUnion:
8317 case CK_ArrayToPointerDecay:
8318 case CK_FunctionToPointerDecay:
8319 case CK_NullToPointer:
8320 case CK_NullToMemberPointer:
8321 case CK_BaseToDerivedMemberPointer:
8322 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008323 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008324 case CK_ConstructorConversion:
8325 case CK_IntegralToPointer:
8326 case CK_ToVoid:
8327 case CK_VectorSplat:
8328 case CK_IntegralToFloating:
8329 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008330 case CK_CPointerToObjCPointerCast:
8331 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008332 case CK_AnyPointerToBlockPointerCast:
8333 case CK_ObjCObjectLValueCast:
8334 case CK_FloatingRealToComplex:
8335 case CK_FloatingComplexToReal:
8336 case CK_FloatingComplexCast:
8337 case CK_FloatingComplexToIntegralComplex:
8338 case CK_IntegralRealToComplex:
8339 case CK_IntegralComplexCast:
8340 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008341 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008342 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008343 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008344 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008345 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008346 llvm_unreachable("invalid cast kind for integral value");
8347
Eli Friedman9faf2f92011-03-25 19:07:11 +00008348 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008349 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008350 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008351 case CK_ARCProduceObject:
8352 case CK_ARCConsumeObject:
8353 case CK_ARCReclaimReturnedObject:
8354 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008355 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008356 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008357
Richard Smith4ef685b2012-01-17 21:17:26 +00008358 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008359 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008360 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008361 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008362 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008363
8364 case CK_MemberPointerToBoolean:
8365 case CK_PointerToBoolean:
8366 case CK_IntegralToBoolean:
8367 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008368 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008369 case CK_FloatingComplexToBoolean:
8370 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008371 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008372 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008373 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008374 uint64_t IntResult = BoolResult;
8375 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8376 IntResult = (uint64_t)-1;
8377 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008378 }
8379
Eli Friedmanc757de22011-03-25 00:43:55 +00008380 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008381 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008382 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008383
Eli Friedman742421e2009-02-20 01:15:07 +00008384 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008385 // Allow casts of address-of-label differences if they are no-ops
8386 // or narrowing. (The narrowing case isn't actually guaranteed to
8387 // be constant-evaluatable except in some narrow cases which are hard
8388 // to detect here. We let it through on the assumption the user knows
8389 // what they are doing.)
8390 if (Result.isAddrLabelDiff())
8391 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008392 // Only allow casts of lvalues if they are lossless.
8393 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8394 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008395
Richard Smith911e1422012-01-30 22:27:01 +00008396 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8397 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008398 }
Mike Stump11289f42009-09-09 15:08:12 +00008399
Eli Friedmanc757de22011-03-25 00:43:55 +00008400 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8402
John McCall45d55e42010-05-07 21:00:08 +00008403 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008404 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008405 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008406
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008407 if (LV.getLValueBase()) {
8408 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008409 // FIXME: Allow a larger integer size than the pointer size, and allow
8410 // narrowing back down to pointer width in subsequent integral casts.
8411 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008412 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008413 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008414
Richard Smithcf74da72011-11-16 07:18:12 +00008415 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008416 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008417 return true;
8418 }
8419
Yaxun Liu402804b2016-12-15 08:09:08 +00008420 uint64_t V;
8421 if (LV.isNullPointer())
8422 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8423 else
8424 V = LV.getLValueOffset().getQuantity();
8425
8426 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008427 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008428 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008429
Eli Friedmanc757de22011-03-25 00:43:55 +00008430 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008431 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008432 if (!EvaluateComplex(SubExpr, C, Info))
8433 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008434 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008435 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008436
Eli Friedmanc757de22011-03-25 00:43:55 +00008437 case CK_FloatingToIntegral: {
8438 APFloat F(0.0);
8439 if (!EvaluateFloat(SubExpr, F, Info))
8440 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008441
Richard Smith357362d2011-12-13 06:39:58 +00008442 APSInt Value;
8443 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8444 return false;
8445 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008446 }
8447 }
Mike Stump11289f42009-09-09 15:08:12 +00008448
Eli Friedmanc757de22011-03-25 00:43:55 +00008449 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008450}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008451
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008452bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8453 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008454 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008455 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8456 return false;
8457 if (!LV.isComplexInt())
8458 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008459 return Success(LV.getComplexIntReal(), E);
8460 }
8461
8462 return Visit(E->getSubExpr());
8463}
8464
Eli Friedman4e7a2412009-02-27 04:45:43 +00008465bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008466 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008467 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008468 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8469 return false;
8470 if (!LV.isComplexInt())
8471 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008472 return Success(LV.getComplexIntImag(), E);
8473 }
8474
Richard Smith4a678122011-10-24 18:44:57 +00008475 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008476 return Success(0, E);
8477}
8478
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008479bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8480 return Success(E->getPackLength(), E);
8481}
8482
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008483bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8484 return Success(E->getValue(), E);
8485}
8486
Chris Lattner05706e882008-07-11 18:11:29 +00008487//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008488// Float Evaluation
8489//===----------------------------------------------------------------------===//
8490
8491namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008492class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008493 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008494 APFloat &Result;
8495public:
8496 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008497 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008498
Richard Smith2e312c82012-03-03 22:46:17 +00008499 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008500 Result = V.getFloat();
8501 return true;
8502 }
Eli Friedman24c01542008-08-22 00:06:13 +00008503
Richard Smithfddd3842011-12-30 21:15:51 +00008504 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008505 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8506 return true;
8507 }
8508
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008509 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008510
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008511 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008512 bool VisitBinaryOperator(const BinaryOperator *E);
8513 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008514 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008515
John McCallb1fb0d32010-05-07 22:08:54 +00008516 bool VisitUnaryReal(const UnaryOperator *E);
8517 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008518
Richard Smithfddd3842011-12-30 21:15:51 +00008519 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008520};
8521} // end anonymous namespace
8522
8523static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008524 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008525 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008526}
8527
Jay Foad39c79802011-01-12 09:06:06 +00008528static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008529 QualType ResultTy,
8530 const Expr *Arg,
8531 bool SNaN,
8532 llvm::APFloat &Result) {
8533 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8534 if (!S) return false;
8535
8536 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8537
8538 llvm::APInt fill;
8539
8540 // Treat empty strings as if they were zero.
8541 if (S->getString().empty())
8542 fill = llvm::APInt(32, 0);
8543 else if (S->getString().getAsInteger(0, fill))
8544 return false;
8545
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008546 if (Context.getTargetInfo().isNan2008()) {
8547 if (SNaN)
8548 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8549 else
8550 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8551 } else {
8552 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8553 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8554 // a different encoding to what became a standard in 2008, and for pre-
8555 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8556 // sNaN. This is now known as "legacy NaN" encoding.
8557 if (SNaN)
8558 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8559 else
8560 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8561 }
8562
John McCall16291492010-02-28 13:00:19 +00008563 return true;
8564}
8565
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008566bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008567 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008568 default:
8569 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8570
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008571 case Builtin::BI__builtin_huge_val:
8572 case Builtin::BI__builtin_huge_valf:
8573 case Builtin::BI__builtin_huge_vall:
8574 case Builtin::BI__builtin_inf:
8575 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008576 case Builtin::BI__builtin_infl: {
8577 const llvm::fltSemantics &Sem =
8578 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008579 Result = llvm::APFloat::getInf(Sem);
8580 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008581 }
Mike Stump11289f42009-09-09 15:08:12 +00008582
John McCall16291492010-02-28 13:00:19 +00008583 case Builtin::BI__builtin_nans:
8584 case Builtin::BI__builtin_nansf:
8585 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008586 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8587 true, Result))
8588 return Error(E);
8589 return true;
John McCall16291492010-02-28 13:00:19 +00008590
Chris Lattner0b7282e2008-10-06 06:31:58 +00008591 case Builtin::BI__builtin_nan:
8592 case Builtin::BI__builtin_nanf:
8593 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008594 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008595 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008596 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8597 false, Result))
8598 return Error(E);
8599 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008600
8601 case Builtin::BI__builtin_fabs:
8602 case Builtin::BI__builtin_fabsf:
8603 case Builtin::BI__builtin_fabsl:
8604 if (!EvaluateFloat(E->getArg(0), Result, Info))
8605 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008606
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008607 if (Result.isNegative())
8608 Result.changeSign();
8609 return true;
8610
Richard Smith8889a3d2013-06-13 06:26:32 +00008611 // FIXME: Builtin::BI__builtin_powi
8612 // FIXME: Builtin::BI__builtin_powif
8613 // FIXME: Builtin::BI__builtin_powil
8614
Mike Stump11289f42009-09-09 15:08:12 +00008615 case Builtin::BI__builtin_copysign:
8616 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008617 case Builtin::BI__builtin_copysignl: {
8618 APFloat RHS(0.);
8619 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8620 !EvaluateFloat(E->getArg(1), RHS, Info))
8621 return false;
8622 Result.copySign(RHS);
8623 return true;
8624 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008625 }
8626}
8627
John McCallb1fb0d32010-05-07 22:08:54 +00008628bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008629 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8630 ComplexValue CV;
8631 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8632 return false;
8633 Result = CV.FloatReal;
8634 return true;
8635 }
8636
8637 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008638}
8639
8640bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008641 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8642 ComplexValue CV;
8643 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8644 return false;
8645 Result = CV.FloatImag;
8646 return true;
8647 }
8648
Richard Smith4a678122011-10-24 18:44:57 +00008649 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008650 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8651 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008652 return true;
8653}
8654
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008655bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008656 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008657 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008658 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008659 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008660 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008661 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8662 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008663 Result.changeSign();
8664 return true;
8665 }
8666}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008667
Eli Friedman24c01542008-08-22 00:06:13 +00008668bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008669 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8670 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008671
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008672 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008673 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008674 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008675 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008676 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8677 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008678}
8679
8680bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8681 Result = E->getValue();
8682 return true;
8683}
8684
Peter Collingbournee9200682011-05-13 03:29:01 +00008685bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8686 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008687
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008688 switch (E->getCastKind()) {
8689 default:
Richard Smith11562c52011-10-28 17:51:58 +00008690 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008691
8692 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008693 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008694 return EvaluateInteger(SubExpr, IntResult, Info) &&
8695 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8696 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008697 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008698
8699 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008700 if (!Visit(SubExpr))
8701 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008702 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8703 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008704 }
John McCalld7646252010-11-14 08:17:51 +00008705
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008706 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008707 ComplexValue V;
8708 if (!EvaluateComplex(SubExpr, V, Info))
8709 return false;
8710 Result = V.getComplexFloatReal();
8711 return true;
8712 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008713 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008714}
8715
Eli Friedman24c01542008-08-22 00:06:13 +00008716//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008717// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008718//===----------------------------------------------------------------------===//
8719
8720namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008721class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008722 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008723 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008724
Anders Carlsson537969c2008-11-16 20:27:53 +00008725public:
John McCall93d91dc2010-05-07 17:22:02 +00008726 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008727 : ExprEvaluatorBaseTy(info), Result(Result) {}
8728
Richard Smith2e312c82012-03-03 22:46:17 +00008729 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008730 Result.setFrom(V);
8731 return true;
8732 }
Mike Stump11289f42009-09-09 15:08:12 +00008733
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008734 bool ZeroInitialization(const Expr *E);
8735
Anders Carlsson537969c2008-11-16 20:27:53 +00008736 //===--------------------------------------------------------------------===//
8737 // Visitor Methods
8738 //===--------------------------------------------------------------------===//
8739
Peter Collingbournee9200682011-05-13 03:29:01 +00008740 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008741 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008742 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008743 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008744 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008745};
8746} // end anonymous namespace
8747
John McCall93d91dc2010-05-07 17:22:02 +00008748static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8749 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008750 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008751 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008752}
8753
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008754bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008755 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008756 if (ElemTy->isRealFloatingType()) {
8757 Result.makeComplexFloat();
8758 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8759 Result.FloatReal = Zero;
8760 Result.FloatImag = Zero;
8761 } else {
8762 Result.makeComplexInt();
8763 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8764 Result.IntReal = Zero;
8765 Result.IntImag = Zero;
8766 }
8767 return true;
8768}
8769
Peter Collingbournee9200682011-05-13 03:29:01 +00008770bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8771 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008772
8773 if (SubExpr->getType()->isRealFloatingType()) {
8774 Result.makeComplexFloat();
8775 APFloat &Imag = Result.FloatImag;
8776 if (!EvaluateFloat(SubExpr, Imag, Info))
8777 return false;
8778
8779 Result.FloatReal = APFloat(Imag.getSemantics());
8780 return true;
8781 } else {
8782 assert(SubExpr->getType()->isIntegerType() &&
8783 "Unexpected imaginary literal.");
8784
8785 Result.makeComplexInt();
8786 APSInt &Imag = Result.IntImag;
8787 if (!EvaluateInteger(SubExpr, Imag, Info))
8788 return false;
8789
8790 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8791 return true;
8792 }
8793}
8794
Peter Collingbournee9200682011-05-13 03:29:01 +00008795bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008796
John McCallfcef3cf2010-12-14 17:51:41 +00008797 switch (E->getCastKind()) {
8798 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008799 case CK_BaseToDerived:
8800 case CK_DerivedToBase:
8801 case CK_UncheckedDerivedToBase:
8802 case CK_Dynamic:
8803 case CK_ToUnion:
8804 case CK_ArrayToPointerDecay:
8805 case CK_FunctionToPointerDecay:
8806 case CK_NullToPointer:
8807 case CK_NullToMemberPointer:
8808 case CK_BaseToDerivedMemberPointer:
8809 case CK_DerivedToBaseMemberPointer:
8810 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008811 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008812 case CK_ConstructorConversion:
8813 case CK_IntegralToPointer:
8814 case CK_PointerToIntegral:
8815 case CK_PointerToBoolean:
8816 case CK_ToVoid:
8817 case CK_VectorSplat:
8818 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008819 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008820 case CK_IntegralToBoolean:
8821 case CK_IntegralToFloating:
8822 case CK_FloatingToIntegral:
8823 case CK_FloatingToBoolean:
8824 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008825 case CK_CPointerToObjCPointerCast:
8826 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008827 case CK_AnyPointerToBlockPointerCast:
8828 case CK_ObjCObjectLValueCast:
8829 case CK_FloatingComplexToReal:
8830 case CK_FloatingComplexToBoolean:
8831 case CK_IntegralComplexToReal:
8832 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008833 case CK_ARCProduceObject:
8834 case CK_ARCConsumeObject:
8835 case CK_ARCReclaimReturnedObject:
8836 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008837 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008838 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008839 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008840 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008841 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008842 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00008843 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008844
John McCallfcef3cf2010-12-14 17:51:41 +00008845 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008846 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008847 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008848 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008849
8850 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008851 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008852 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008853 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008854
8855 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008856 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008857 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008858 return false;
8859
John McCallfcef3cf2010-12-14 17:51:41 +00008860 Result.makeComplexFloat();
8861 Result.FloatImag = APFloat(Real.getSemantics());
8862 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008863 }
8864
John McCallfcef3cf2010-12-14 17:51:41 +00008865 case CK_FloatingComplexCast: {
8866 if (!Visit(E->getSubExpr()))
8867 return false;
8868
8869 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8870 QualType From
8871 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8872
Richard Smith357362d2011-12-13 06:39:58 +00008873 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8874 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008875 }
8876
8877 case CK_FloatingComplexToIntegralComplex: {
8878 if (!Visit(E->getSubExpr()))
8879 return false;
8880
8881 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8882 QualType From
8883 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8884 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008885 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8886 To, Result.IntReal) &&
8887 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8888 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008889 }
8890
8891 case CK_IntegralRealToComplex: {
8892 APSInt &Real = Result.IntReal;
8893 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8894 return false;
8895
8896 Result.makeComplexInt();
8897 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8898 return true;
8899 }
8900
8901 case CK_IntegralComplexCast: {
8902 if (!Visit(E->getSubExpr()))
8903 return false;
8904
8905 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8906 QualType From
8907 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8908
Richard Smith911e1422012-01-30 22:27:01 +00008909 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8910 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008911 return true;
8912 }
8913
8914 case CK_IntegralComplexToFloatingComplex: {
8915 if (!Visit(E->getSubExpr()))
8916 return false;
8917
Ted Kremenek28831752012-08-23 20:46:57 +00008918 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008919 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008920 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008921 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008922 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8923 To, Result.FloatReal) &&
8924 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8925 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008926 }
8927 }
8928
8929 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008930}
8931
John McCall93d91dc2010-05-07 17:22:02 +00008932bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008933 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008934 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8935
Chandler Carrutha216cad2014-10-11 00:57:18 +00008936 // Track whether the LHS or RHS is real at the type system level. When this is
8937 // the case we can simplify our evaluation strategy.
8938 bool LHSReal = false, RHSReal = false;
8939
8940 bool LHSOK;
8941 if (E->getLHS()->getType()->isRealFloatingType()) {
8942 LHSReal = true;
8943 APFloat &Real = Result.FloatReal;
8944 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8945 if (LHSOK) {
8946 Result.makeComplexFloat();
8947 Result.FloatImag = APFloat(Real.getSemantics());
8948 }
8949 } else {
8950 LHSOK = Visit(E->getLHS());
8951 }
George Burgess IVa145e252016-05-25 22:38:36 +00008952 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008953 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008954
John McCall93d91dc2010-05-07 17:22:02 +00008955 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008956 if (E->getRHS()->getType()->isRealFloatingType()) {
8957 RHSReal = true;
8958 APFloat &Real = RHS.FloatReal;
8959 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8960 return false;
8961 RHS.makeComplexFloat();
8962 RHS.FloatImag = APFloat(Real.getSemantics());
8963 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008964 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008965
Chandler Carrutha216cad2014-10-11 00:57:18 +00008966 assert(!(LHSReal && RHSReal) &&
8967 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008968 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008969 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008970 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008971 if (Result.isComplexFloat()) {
8972 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8973 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008974 if (LHSReal)
8975 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8976 else if (!RHSReal)
8977 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8978 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008979 } else {
8980 Result.getComplexIntReal() += RHS.getComplexIntReal();
8981 Result.getComplexIntImag() += RHS.getComplexIntImag();
8982 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008983 break;
John McCalle3027922010-08-25 11:45:40 +00008984 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008985 if (Result.isComplexFloat()) {
8986 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8987 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008988 if (LHSReal) {
8989 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8990 Result.getComplexFloatImag().changeSign();
8991 } else if (!RHSReal) {
8992 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8993 APFloat::rmNearestTiesToEven);
8994 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008995 } else {
8996 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8997 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8998 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008999 break;
John McCalle3027922010-08-25 11:45:40 +00009000 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009001 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009002 // This is an implementation of complex multiplication according to the
9003 // constraints laid out in C11 Annex G. The implemantion uses the
9004 // following naming scheme:
9005 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009006 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009007 APFloat &A = LHS.getComplexFloatReal();
9008 APFloat &B = LHS.getComplexFloatImag();
9009 APFloat &C = RHS.getComplexFloatReal();
9010 APFloat &D = RHS.getComplexFloatImag();
9011 APFloat &ResR = Result.getComplexFloatReal();
9012 APFloat &ResI = Result.getComplexFloatImag();
9013 if (LHSReal) {
9014 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9015 ResR = A * C;
9016 ResI = A * D;
9017 } else if (RHSReal) {
9018 ResR = C * A;
9019 ResI = C * B;
9020 } else {
9021 // In the fully general case, we need to handle NaNs and infinities
9022 // robustly.
9023 APFloat AC = A * C;
9024 APFloat BD = B * D;
9025 APFloat AD = A * D;
9026 APFloat BC = B * C;
9027 ResR = AC - BD;
9028 ResI = AD + BC;
9029 if (ResR.isNaN() && ResI.isNaN()) {
9030 bool Recalc = false;
9031 if (A.isInfinity() || B.isInfinity()) {
9032 A = APFloat::copySign(
9033 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9034 B = APFloat::copySign(
9035 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9036 if (C.isNaN())
9037 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9038 if (D.isNaN())
9039 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9040 Recalc = true;
9041 }
9042 if (C.isInfinity() || D.isInfinity()) {
9043 C = APFloat::copySign(
9044 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9045 D = APFloat::copySign(
9046 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9047 if (A.isNaN())
9048 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9049 if (B.isNaN())
9050 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9051 Recalc = true;
9052 }
9053 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9054 AD.isInfinity() || BC.isInfinity())) {
9055 if (A.isNaN())
9056 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9057 if (B.isNaN())
9058 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9059 if (C.isNaN())
9060 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9061 if (D.isNaN())
9062 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9063 Recalc = true;
9064 }
9065 if (Recalc) {
9066 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9067 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9068 }
9069 }
9070 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009071 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009072 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009073 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009074 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9075 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009076 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009077 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9078 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9079 }
9080 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009081 case BO_Div:
9082 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009083 // This is an implementation of complex division according to the
9084 // constraints laid out in C11 Annex G. The implemantion uses the
9085 // following naming scheme:
9086 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009087 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009088 APFloat &A = LHS.getComplexFloatReal();
9089 APFloat &B = LHS.getComplexFloatImag();
9090 APFloat &C = RHS.getComplexFloatReal();
9091 APFloat &D = RHS.getComplexFloatImag();
9092 APFloat &ResR = Result.getComplexFloatReal();
9093 APFloat &ResI = Result.getComplexFloatImag();
9094 if (RHSReal) {
9095 ResR = A / C;
9096 ResI = B / C;
9097 } else {
9098 if (LHSReal) {
9099 // No real optimizations we can do here, stub out with zero.
9100 B = APFloat::getZero(A.getSemantics());
9101 }
9102 int DenomLogB = 0;
9103 APFloat MaxCD = maxnum(abs(C), abs(D));
9104 if (MaxCD.isFinite()) {
9105 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009106 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9107 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009108 }
9109 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009110 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9111 APFloat::rmNearestTiesToEven);
9112 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9113 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009114 if (ResR.isNaN() && ResI.isNaN()) {
9115 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9116 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9117 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9118 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9119 D.isFinite()) {
9120 A = APFloat::copySign(
9121 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9122 B = APFloat::copySign(
9123 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9124 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9125 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9126 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9127 C = APFloat::copySign(
9128 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9129 D = APFloat::copySign(
9130 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9131 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9132 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9133 }
9134 }
9135 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009136 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009137 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9138 return Error(E, diag::note_expr_divide_by_zero);
9139
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009140 ComplexValue LHS = Result;
9141 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9142 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9143 Result.getComplexIntReal() =
9144 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9145 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9146 Result.getComplexIntImag() =
9147 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9148 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9149 }
9150 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009151 }
9152
John McCall93d91dc2010-05-07 17:22:02 +00009153 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009154}
9155
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009156bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9157 // Get the operand value into 'Result'.
9158 if (!Visit(E->getSubExpr()))
9159 return false;
9160
9161 switch (E->getOpcode()) {
9162 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009163 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009164 case UO_Extension:
9165 return true;
9166 case UO_Plus:
9167 // The result is always just the subexpr.
9168 return true;
9169 case UO_Minus:
9170 if (Result.isComplexFloat()) {
9171 Result.getComplexFloatReal().changeSign();
9172 Result.getComplexFloatImag().changeSign();
9173 }
9174 else {
9175 Result.getComplexIntReal() = -Result.getComplexIntReal();
9176 Result.getComplexIntImag() = -Result.getComplexIntImag();
9177 }
9178 return true;
9179 case UO_Not:
9180 if (Result.isComplexFloat())
9181 Result.getComplexFloatImag().changeSign();
9182 else
9183 Result.getComplexIntImag() = -Result.getComplexIntImag();
9184 return true;
9185 }
9186}
9187
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009188bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9189 if (E->getNumInits() == 2) {
9190 if (E->getType()->isComplexType()) {
9191 Result.makeComplexFloat();
9192 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9193 return false;
9194 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9195 return false;
9196 } else {
9197 Result.makeComplexInt();
9198 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9199 return false;
9200 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9201 return false;
9202 }
9203 return true;
9204 }
9205 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9206}
9207
Anders Carlsson537969c2008-11-16 20:27:53 +00009208//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009209// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9210// implicit conversion.
9211//===----------------------------------------------------------------------===//
9212
9213namespace {
9214class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009215 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009216 APValue &Result;
9217public:
9218 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9219 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9220
9221 bool Success(const APValue &V, const Expr *E) {
9222 Result = V;
9223 return true;
9224 }
9225
9226 bool ZeroInitialization(const Expr *E) {
9227 ImplicitValueInitExpr VIE(
9228 E->getType()->castAs<AtomicType>()->getValueType());
9229 return Evaluate(Result, Info, &VIE);
9230 }
9231
9232 bool VisitCastExpr(const CastExpr *E) {
9233 switch (E->getCastKind()) {
9234 default:
9235 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9236 case CK_NonAtomicToAtomic:
9237 return Evaluate(Result, Info, E->getSubExpr());
9238 }
9239 }
9240};
9241} // end anonymous namespace
9242
9243static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9244 assert(E->isRValue() && E->getType()->isAtomicType());
9245 return AtomicExprEvaluator(Info, Result).Visit(E);
9246}
9247
9248//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009249// Void expression evaluation, primarily for a cast to void on the LHS of a
9250// comma operator
9251//===----------------------------------------------------------------------===//
9252
9253namespace {
9254class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009255 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009256public:
9257 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9258
Richard Smith2e312c82012-03-03 22:46:17 +00009259 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009260
9261 bool VisitCastExpr(const CastExpr *E) {
9262 switch (E->getCastKind()) {
9263 default:
9264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9265 case CK_ToVoid:
9266 VisitIgnoredValue(E->getSubExpr());
9267 return true;
9268 }
9269 }
Hal Finkela8443c32014-07-17 14:49:58 +00009270
9271 bool VisitCallExpr(const CallExpr *E) {
9272 switch (E->getBuiltinCallee()) {
9273 default:
9274 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9275 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009276 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009277 // The argument is not evaluated!
9278 return true;
9279 }
9280 }
Richard Smith42d3af92011-12-07 00:43:50 +00009281};
9282} // end anonymous namespace
9283
9284static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9285 assert(E->isRValue() && E->getType()->isVoidType());
9286 return VoidExprEvaluator(Info).Visit(E);
9287}
9288
9289//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009290// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009291//===----------------------------------------------------------------------===//
9292
Richard Smith2e312c82012-03-03 22:46:17 +00009293static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009294 // In C, function designators are not lvalues, but we evaluate them as if they
9295 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009296 QualType T = E->getType();
9297 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009298 LValue LV;
9299 if (!EvaluateLValue(E, LV, Info))
9300 return false;
9301 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009302 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009303 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009304 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009305 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009306 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009307 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009308 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009309 LValue LV;
9310 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009311 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009312 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009313 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009314 llvm::APFloat F(0.0);
9315 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009316 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009317 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009318 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009319 ComplexValue C;
9320 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009321 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009322 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009323 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009324 MemberPtr P;
9325 if (!EvaluateMemberPointer(E, P, Info))
9326 return false;
9327 P.moveInto(Result);
9328 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009329 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009330 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009331 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009332 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9333 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009334 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009335 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009336 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009337 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009338 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009339 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9340 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009341 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009342 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009343 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009344 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009345 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009346 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009347 if (!EvaluateVoid(E, Info))
9348 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009349 } else if (T->isAtomicType()) {
9350 if (!EvaluateAtomic(E, Result, Info))
9351 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009352 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009353 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009354 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009355 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009356 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009357 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009358 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009359
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009360 return true;
9361}
9362
Richard Smithb228a862012-02-15 02:18:13 +00009363/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9364/// cases, the in-place evaluation is essential, since later initializers for
9365/// an object can indirectly refer to subobjects which were initialized earlier.
9366static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009367 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009368 assert(!E->isValueDependent());
9369
Richard Smith7525ff62013-05-09 07:14:00 +00009370 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009371 return false;
9372
9373 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009374 // Evaluate arrays and record types in-place, so that later initializers can
9375 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009376 if (E->getType()->isArrayType())
9377 return EvaluateArray(E, This, Result, Info);
9378 else if (E->getType()->isRecordType())
9379 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009380 }
9381
9382 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009383 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009384}
9385
Richard Smithf57d8cb2011-12-09 22:58:01 +00009386/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9387/// lvalue-to-rvalue cast if it is an lvalue.
9388static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009389 if (E->getType().isNull())
9390 return false;
9391
Richard Smithfddd3842011-12-30 21:15:51 +00009392 if (!CheckLiteralType(Info, E))
9393 return false;
9394
Richard Smith2e312c82012-03-03 22:46:17 +00009395 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009396 return false;
9397
9398 if (E->isGLValue()) {
9399 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009400 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009401 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009402 return false;
9403 }
9404
Richard Smith2e312c82012-03-03 22:46:17 +00009405 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009406 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009407}
Richard Smith11562c52011-10-28 17:51:58 +00009408
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009409static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9410 const ASTContext &Ctx, bool &IsConst) {
9411 // Fast-path evaluations of integer literals, since we sometimes see files
9412 // containing vast quantities of these.
9413 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9414 Result.Val = APValue(APSInt(L->getValue(),
9415 L->getType()->isUnsignedIntegerType()));
9416 IsConst = true;
9417 return true;
9418 }
James Dennett0492ef02014-03-14 17:44:10 +00009419
9420 // This case should be rare, but we need to check it before we check on
9421 // the type below.
9422 if (Exp->getType().isNull()) {
9423 IsConst = false;
9424 return true;
9425 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009426
9427 // FIXME: Evaluating values of large array and record types can cause
9428 // performance problems. Only do so in C++11 for now.
9429 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9430 Exp->getType()->isRecordType()) &&
9431 !Ctx.getLangOpts().CPlusPlus11) {
9432 IsConst = false;
9433 return true;
9434 }
9435 return false;
9436}
9437
9438
Richard Smith7b553f12011-10-29 00:50:52 +00009439/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009440/// any crazy technique (that has nothing to do with language standards) that
9441/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009442/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9443/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009444bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009445 bool IsConst;
9446 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9447 return IsConst;
9448
Richard Smith6d4c6582013-11-05 22:18:15 +00009449 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009450 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009451}
9452
Jay Foad39c79802011-01-12 09:06:06 +00009453bool Expr::EvaluateAsBooleanCondition(bool &Result,
9454 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009455 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009456 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009457 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009458}
9459
Richard Smithce8eca52015-12-08 03:21:47 +00009460static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9461 Expr::SideEffectsKind SEK) {
9462 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9463 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9464}
9465
Richard Smith5fab0c92011-12-28 19:48:30 +00009466bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9467 SideEffectsKind AllowSideEffects) const {
9468 if (!getType()->isIntegralOrEnumerationType())
9469 return false;
9470
Richard Smith11562c52011-10-28 17:51:58 +00009471 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009472 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009473 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009474 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009475
Richard Smith11562c52011-10-28 17:51:58 +00009476 Result = ExprResult.Val.getInt();
9477 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009478}
9479
Richard Trieube234c32016-04-21 21:04:55 +00009480bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9481 SideEffectsKind AllowSideEffects) const {
9482 if (!getType()->isRealFloatingType())
9483 return false;
9484
9485 EvalResult ExprResult;
9486 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9487 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9488 return false;
9489
9490 Result = ExprResult.Val.getFloat();
9491 return true;
9492}
9493
Jay Foad39c79802011-01-12 09:06:06 +00009494bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009495 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009496
John McCall45d55e42010-05-07 21:00:08 +00009497 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009498 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9499 !CheckLValueConstantExpression(Info, getExprLoc(),
9500 Ctx.getLValueReferenceType(getType()), LV))
9501 return false;
9502
Richard Smith2e312c82012-03-03 22:46:17 +00009503 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009504 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009505}
9506
Richard Smithd0b4dd62011-12-19 06:19:21 +00009507bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9508 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009509 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009510 // FIXME: Evaluating initializers for large array and record types can cause
9511 // performance problems. Only do so in C++11 for now.
9512 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009513 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009514 return false;
9515
Richard Smithd0b4dd62011-12-19 06:19:21 +00009516 Expr::EvalStatus EStatus;
9517 EStatus.Diag = &Notes;
9518
Richard Smith0c6124b2015-12-03 01:36:22 +00009519 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9520 ? EvalInfo::EM_ConstantExpression
9521 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009522 InitInfo.setEvaluatingDecl(VD, Value);
9523
9524 LValue LVal;
9525 LVal.set(VD);
9526
Richard Smithfddd3842011-12-30 21:15:51 +00009527 // C++11 [basic.start.init]p2:
9528 // Variables with static storage duration or thread storage duration shall be
9529 // zero-initialized before any other initialization takes place.
9530 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009531 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009532 !VD->getType()->isReferenceType()) {
9533 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009534 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009535 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009536 return false;
9537 }
9538
Richard Smith7525ff62013-05-09 07:14:00 +00009539 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9540 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009541 EStatus.HasSideEffects)
9542 return false;
9543
9544 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9545 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009546}
9547
Richard Smith7b553f12011-10-29 00:50:52 +00009548/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9549/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009550bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009551 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009552 return EvaluateAsRValue(Result, Ctx) &&
9553 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009554}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009555
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009556APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009557 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009558 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009559 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009560 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009561 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009562 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009563 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009564
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009565 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009566}
John McCall864e3962010-05-07 05:32:02 +00009567
Richard Smithe9ff7702013-11-05 22:23:30 +00009568void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009569 bool IsConst;
9570 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009571 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009572 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009573 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9574 }
9575}
9576
Richard Smithe6c01442013-06-05 00:46:14 +00009577bool Expr::EvalResult::isGlobalLValue() const {
9578 assert(Val.isLValue());
9579 return IsGlobalLValue(Val.getLValueBase());
9580}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009581
9582
John McCall864e3962010-05-07 05:32:02 +00009583/// isIntegerConstantExpr - this recursive routine will test if an expression is
9584/// an integer constant expression.
9585
9586/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9587/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009588
9589// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009590// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9591// and a (possibly null) SourceLocation indicating the location of the problem.
9592//
John McCall864e3962010-05-07 05:32:02 +00009593// Note that to reduce code duplication, this helper does no evaluation
9594// itself; the caller checks whether the expression is evaluatable, and
9595// in the rare cases where CheckICE actually cares about the evaluated
9596// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009597
Dan Gohman28ade552010-07-26 21:25:24 +00009598namespace {
9599
Richard Smith9e575da2012-12-28 13:25:52 +00009600enum ICEKind {
9601 /// This expression is an ICE.
9602 IK_ICE,
9603 /// This expression is not an ICE, but if it isn't evaluated, it's
9604 /// a legal subexpression for an ICE. This return value is used to handle
9605 /// the comma operator in C99 mode, and non-constant subexpressions.
9606 IK_ICEIfUnevaluated,
9607 /// This expression is not an ICE, and is not a legal subexpression for one.
9608 IK_NotICE
9609};
9610
John McCall864e3962010-05-07 05:32:02 +00009611struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009612 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009613 SourceLocation Loc;
9614
Richard Smith9e575da2012-12-28 13:25:52 +00009615 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009616};
9617
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009618}
Dan Gohman28ade552010-07-26 21:25:24 +00009619
Richard Smith9e575da2012-12-28 13:25:52 +00009620static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9621
9622static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009623
Craig Toppera31a8822013-08-22 07:09:37 +00009624static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009625 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009626 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009627 !EVResult.Val.isInt())
9628 return ICEDiag(IK_NotICE, E->getLocStart());
9629
John McCall864e3962010-05-07 05:32:02 +00009630 return NoDiag();
9631}
9632
Craig Toppera31a8822013-08-22 07:09:37 +00009633static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009634 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009635 if (!E->getType()->isIntegralOrEnumerationType())
9636 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009637
9638 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009639#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009640#define STMT(Node, Base) case Expr::Node##Class:
9641#define EXPR(Node, Base)
9642#include "clang/AST/StmtNodes.inc"
9643 case Expr::PredefinedExprClass:
9644 case Expr::FloatingLiteralClass:
9645 case Expr::ImaginaryLiteralClass:
9646 case Expr::StringLiteralClass:
9647 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009648 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009649 case Expr::MemberExprClass:
9650 case Expr::CompoundAssignOperatorClass:
9651 case Expr::CompoundLiteralExprClass:
9652 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009653 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009654 case Expr::ArrayInitLoopExprClass:
9655 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009656 case Expr::NoInitExprClass:
9657 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009658 case Expr::ImplicitValueInitExprClass:
9659 case Expr::ParenListExprClass:
9660 case Expr::VAArgExprClass:
9661 case Expr::AddrLabelExprClass:
9662 case Expr::StmtExprClass:
9663 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009664 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009665 case Expr::CXXDynamicCastExprClass:
9666 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009667 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009668 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009669 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009670 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009671 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009672 case Expr::CXXThisExprClass:
9673 case Expr::CXXThrowExprClass:
9674 case Expr::CXXNewExprClass:
9675 case Expr::CXXDeleteExprClass:
9676 case Expr::CXXPseudoDestructorExprClass:
9677 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009678 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009679 case Expr::DependentScopeDeclRefExprClass:
9680 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009681 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009682 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009683 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009684 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009685 case Expr::CXXTemporaryObjectExprClass:
9686 case Expr::CXXUnresolvedConstructExprClass:
9687 case Expr::CXXDependentScopeMemberExprClass:
9688 case Expr::UnresolvedMemberExprClass:
9689 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009690 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009691 case Expr::ObjCArrayLiteralClass:
9692 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009693 case Expr::ObjCEncodeExprClass:
9694 case Expr::ObjCMessageExprClass:
9695 case Expr::ObjCSelectorExprClass:
9696 case Expr::ObjCProtocolExprClass:
9697 case Expr::ObjCIvarRefExprClass:
9698 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009699 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009700 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009701 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009702 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009703 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009704 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009705 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009706 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009707 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009708 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009709 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009710 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009711 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009712 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009713 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009714 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009715 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009716 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009717 case Expr::CoawaitExprClass:
9718 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009719 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009720
Richard Smithf137f932014-01-25 20:50:08 +00009721 case Expr::InitListExprClass: {
9722 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9723 // form "T x = { a };" is equivalent to "T x = a;".
9724 // Unless we're initializing a reference, T is a scalar as it is known to be
9725 // of integral or enumeration type.
9726 if (E->isRValue())
9727 if (cast<InitListExpr>(E)->getNumInits() == 1)
9728 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9729 return ICEDiag(IK_NotICE, E->getLocStart());
9730 }
9731
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009732 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009733 case Expr::GNUNullExprClass:
9734 // GCC considers the GNU __null value to be an integral constant expression.
9735 return NoDiag();
9736
John McCall7c454bb2011-07-15 05:09:51 +00009737 case Expr::SubstNonTypeTemplateParmExprClass:
9738 return
9739 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9740
John McCall864e3962010-05-07 05:32:02 +00009741 case Expr::ParenExprClass:
9742 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009743 case Expr::GenericSelectionExprClass:
9744 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009745 case Expr::IntegerLiteralClass:
9746 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009747 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009748 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009749 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009750 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009751 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009752 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009753 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009754 return NoDiag();
9755 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009756 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009757 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9758 // constant expressions, but they can never be ICEs because an ICE cannot
9759 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009760 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009761 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009762 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009763 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009764 }
Richard Smith6365c912012-02-24 22:12:32 +00009765 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009766 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9767 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009768 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009769 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009770 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009771 // Parameter variables are never constants. Without this check,
9772 // getAnyInitializer() can find a default argument, which leads
9773 // to chaos.
9774 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009775 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009776
9777 // C++ 7.1.5.1p2
9778 // A variable of non-volatile const-qualified integral or enumeration
9779 // type initialized by an ICE can be used in ICEs.
9780 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009781 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009782 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009783
Richard Smithd0b4dd62011-12-19 06:19:21 +00009784 const VarDecl *VD;
9785 // Look for a declaration of this variable that has an initializer, and
9786 // check whether it is an ICE.
9787 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9788 return NoDiag();
9789 else
Richard Smith9e575da2012-12-28 13:25:52 +00009790 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009791 }
9792 }
Richard Smith9e575da2012-12-28 13:25:52 +00009793 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009794 }
John McCall864e3962010-05-07 05:32:02 +00009795 case Expr::UnaryOperatorClass: {
9796 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9797 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009798 case UO_PostInc:
9799 case UO_PostDec:
9800 case UO_PreInc:
9801 case UO_PreDec:
9802 case UO_AddrOf:
9803 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009804 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009805 // C99 6.6/3 allows increment and decrement within unevaluated
9806 // subexpressions of constant expressions, but they can never be ICEs
9807 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009808 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009809 case UO_Extension:
9810 case UO_LNot:
9811 case UO_Plus:
9812 case UO_Minus:
9813 case UO_Not:
9814 case UO_Real:
9815 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009816 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009817 }
Richard Smith9e575da2012-12-28 13:25:52 +00009818
John McCall864e3962010-05-07 05:32:02 +00009819 // OffsetOf falls through here.
9820 }
9821 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009822 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9823 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9824 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9825 // compliance: we should warn earlier for offsetof expressions with
9826 // array subscripts that aren't ICEs, and if the array subscripts
9827 // are ICEs, the value of the offsetof must be an integer constant.
9828 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009829 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009830 case Expr::UnaryExprOrTypeTraitExprClass: {
9831 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9832 if ((Exp->getKind() == UETT_SizeOf) &&
9833 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009834 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009835 return NoDiag();
9836 }
9837 case Expr::BinaryOperatorClass: {
9838 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9839 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009840 case BO_PtrMemD:
9841 case BO_PtrMemI:
9842 case BO_Assign:
9843 case BO_MulAssign:
9844 case BO_DivAssign:
9845 case BO_RemAssign:
9846 case BO_AddAssign:
9847 case BO_SubAssign:
9848 case BO_ShlAssign:
9849 case BO_ShrAssign:
9850 case BO_AndAssign:
9851 case BO_XorAssign:
9852 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009853 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9854 // constant expressions, but they can never be ICEs because an ICE cannot
9855 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009856 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009857
John McCalle3027922010-08-25 11:45:40 +00009858 case BO_Mul:
9859 case BO_Div:
9860 case BO_Rem:
9861 case BO_Add:
9862 case BO_Sub:
9863 case BO_Shl:
9864 case BO_Shr:
9865 case BO_LT:
9866 case BO_GT:
9867 case BO_LE:
9868 case BO_GE:
9869 case BO_EQ:
9870 case BO_NE:
9871 case BO_And:
9872 case BO_Xor:
9873 case BO_Or:
9874 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009875 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9876 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009877 if (Exp->getOpcode() == BO_Div ||
9878 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009879 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009880 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009881 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009882 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009883 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009884 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009885 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009886 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009887 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009888 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009889 }
9890 }
9891 }
John McCalle3027922010-08-25 11:45:40 +00009892 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009893 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009894 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9895 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009896 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9897 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009898 } else {
9899 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009900 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009901 }
9902 }
Richard Smith9e575da2012-12-28 13:25:52 +00009903 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009904 }
John McCalle3027922010-08-25 11:45:40 +00009905 case BO_LAnd:
9906 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009907 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9908 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009909 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009910 // Rare case where the RHS has a comma "side-effect"; we need
9911 // to actually check the condition to see whether the side
9912 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009913 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009914 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009915 return RHSResult;
9916 return NoDiag();
9917 }
9918
Richard Smith9e575da2012-12-28 13:25:52 +00009919 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009920 }
9921 }
9922 }
9923 case Expr::ImplicitCastExprClass:
9924 case Expr::CStyleCastExprClass:
9925 case Expr::CXXFunctionalCastExprClass:
9926 case Expr::CXXStaticCastExprClass:
9927 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009928 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009929 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009930 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009931 if (isa<ExplicitCastExpr>(E)) {
9932 if (const FloatingLiteral *FL
9933 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9934 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9935 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9936 APSInt IgnoredVal(DestWidth, !DestSigned);
9937 bool Ignored;
9938 // If the value does not fit in the destination type, the behavior is
9939 // undefined, so we are not required to treat it as a constant
9940 // expression.
9941 if (FL->getValue().convertToInteger(IgnoredVal,
9942 llvm::APFloat::rmTowardZero,
9943 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009944 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009945 return NoDiag();
9946 }
9947 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009948 switch (cast<CastExpr>(E)->getCastKind()) {
9949 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009950 case CK_AtomicToNonAtomic:
9951 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009952 case CK_NoOp:
9953 case CK_IntegralToBoolean:
9954 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009955 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009956 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009957 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009958 }
John McCall864e3962010-05-07 05:32:02 +00009959 }
John McCallc07a0c72011-02-17 10:25:35 +00009960 case Expr::BinaryConditionalOperatorClass: {
9961 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9962 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009963 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009964 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009965 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9966 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9967 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009968 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009969 return FalseResult;
9970 }
John McCall864e3962010-05-07 05:32:02 +00009971 case Expr::ConditionalOperatorClass: {
9972 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9973 // If the condition (ignoring parens) is a __builtin_constant_p call,
9974 // then only the true side is actually considered in an integer constant
9975 // expression, and it is fully evaluated. This is an important GNU
9976 // extension. See GCC PR38377 for discussion.
9977 if (const CallExpr *CallCE
9978 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009979 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009980 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009981 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009982 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009983 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009984
Richard Smithf57d8cb2011-12-09 22:58:01 +00009985 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9986 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009987
Richard Smith9e575da2012-12-28 13:25:52 +00009988 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009989 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009990 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009991 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009992 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009993 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009994 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009995 return NoDiag();
9996 // Rare case where the diagnostics depend on which side is evaluated
9997 // Note that if we get here, CondResult is 0, and at least one of
9998 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009999 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010000 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010001 return TrueResult;
10002 }
10003 case Expr::CXXDefaultArgExprClass:
10004 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010005 case Expr::CXXDefaultInitExprClass:
10006 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010007 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010008 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010009 }
10010 }
10011
David Blaikiee4d798f2012-01-20 21:50:17 +000010012 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010013}
10014
Richard Smithf57d8cb2011-12-09 22:58:01 +000010015/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010016static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010017 const Expr *E,
10018 llvm::APSInt *Value,
10019 SourceLocation *Loc) {
10020 if (!E->getType()->isIntegralOrEnumerationType()) {
10021 if (Loc) *Loc = E->getExprLoc();
10022 return false;
10023 }
10024
Richard Smith66e05fe2012-01-18 05:21:49 +000010025 APValue Result;
10026 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010027 return false;
10028
Richard Smith98710fc2014-11-13 23:03:19 +000010029 if (!Result.isInt()) {
10030 if (Loc) *Loc = E->getExprLoc();
10031 return false;
10032 }
10033
Richard Smith66e05fe2012-01-18 05:21:49 +000010034 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010035 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010036}
10037
Craig Toppera31a8822013-08-22 07:09:37 +000010038bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10039 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010040 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010041 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010042
Richard Smith9e575da2012-12-28 13:25:52 +000010043 ICEDiag D = CheckICE(this, Ctx);
10044 if (D.Kind != IK_ICE) {
10045 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010046 return false;
10047 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010048 return true;
10049}
10050
Craig Toppera31a8822013-08-22 07:09:37 +000010051bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010052 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010053 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010054 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10055
10056 if (!isIntegerConstantExpr(Ctx, Loc))
10057 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010058 // The only possible side-effects here are due to UB discovered in the
10059 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10060 // required to treat the expression as an ICE, so we produce the folded
10061 // value.
10062 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010063 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010064 return true;
10065}
Richard Smith66e05fe2012-01-18 05:21:49 +000010066
Craig Toppera31a8822013-08-22 07:09:37 +000010067bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010068 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010069}
10070
Craig Toppera31a8822013-08-22 07:09:37 +000010071bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010072 SourceLocation *Loc) const {
10073 // We support this checking in C++98 mode in order to diagnose compatibility
10074 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010075 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010076
Richard Smith98a0a492012-02-14 21:38:30 +000010077 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010078 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010079 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010080 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010081 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010082
10083 APValue Scratch;
10084 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10085
10086 if (!Diags.empty()) {
10087 IsConstExpr = false;
10088 if (Loc) *Loc = Diags[0].first;
10089 } else if (!IsConstExpr) {
10090 // FIXME: This shouldn't happen.
10091 if (Loc) *Loc = getExprLoc();
10092 }
10093
10094 return IsConstExpr;
10095}
Richard Smith253c2a32012-01-27 01:14:48 +000010096
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010097bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10098 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010099 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010100 Expr::EvalStatus Status;
10101 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10102
10103 ArgVector ArgValues(Args.size());
10104 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10105 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010106 if ((*I)->isValueDependent() ||
10107 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010108 // If evaluation fails, throw away the argument entirely.
10109 ArgValues[I - Args.begin()] = APValue();
10110 if (Info.EvalStatus.HasSideEffects)
10111 return false;
10112 }
10113
10114 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010115 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010116 ArgValues.data());
10117 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10118}
10119
Richard Smith253c2a32012-01-27 01:14:48 +000010120bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010121 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010122 PartialDiagnosticAt> &Diags) {
10123 // FIXME: It would be useful to check constexpr function templates, but at the
10124 // moment the constant expression evaluator cannot cope with the non-rigorous
10125 // ASTs which we build for dependent expressions.
10126 if (FD->isDependentContext())
10127 return true;
10128
10129 Expr::EvalStatus Status;
10130 Status.Diag = &Diags;
10131
Richard Smith6d4c6582013-11-05 22:18:15 +000010132 EvalInfo Info(FD->getASTContext(), Status,
10133 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010134
10135 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010136 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010137
Richard Smith7525ff62013-05-09 07:14:00 +000010138 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010139 // is a temporary being used as the 'this' pointer.
10140 LValue This;
10141 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010142 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010143
Richard Smith253c2a32012-01-27 01:14:48 +000010144 ArrayRef<const Expr*> Args;
10145
Richard Smith2e312c82012-03-03 22:46:17 +000010146 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010147 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10148 // Evaluate the call as a constant initializer, to allow the construction
10149 // of objects of non-literal types.
10150 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010151 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10152 } else {
10153 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010154 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010155 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010156 }
Richard Smith253c2a32012-01-27 01:14:48 +000010157
10158 return Diags.empty();
10159}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010160
10161bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10162 const FunctionDecl *FD,
10163 SmallVectorImpl<
10164 PartialDiagnosticAt> &Diags) {
10165 Expr::EvalStatus Status;
10166 Status.Diag = &Diags;
10167
10168 EvalInfo Info(FD->getASTContext(), Status,
10169 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10170
10171 // Fabricate a call stack frame to give the arguments a plausible cover story.
10172 ArrayRef<const Expr*> Args;
10173 ArgVector ArgValues(0);
10174 bool Success = EvaluateArgs(Args, ArgValues, Info);
10175 (void)Success;
10176 assert(Success &&
10177 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010178 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010179
10180 APValue ResultScratch;
10181 Evaluate(ResultScratch, Info, E);
10182 return Diags.empty();
10183}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010184
10185bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10186 unsigned Type) const {
10187 if (!getType()->isPointerType())
10188 return false;
10189
10190 Expr::EvalStatus Status;
10191 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010192 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010193}