blob: 6c8a650967e19fbc426b24f182a97738ad0dd09d [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"
Mike Stumpb807c9c2009-05-30 14:43:18 +000047#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000048#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000049#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000050#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000051
Anders Carlsson7a241ba2008-07-03 04:20:39 +000052using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000053using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000054using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055
Richard Smithb228a862012-02-15 02:18:13 +000056static bool IsGlobalLValue(APValue::LValueBase B);
57
John McCall93d91dc2010-05-07 17:22:02 +000058namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000059 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000060 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000061 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000062
Richard Smithb228a862012-02-15 02:18:13 +000063 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000064 if (!B) return QualType();
65 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
66 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000067
68 const Expr *Base = B.get<const Expr*>();
69
70 // For a materialized temporary, the type of the temporary we materialized
71 // may not be the type of the expression.
72 if (const MaterializeTemporaryExpr *MTE =
73 dyn_cast<MaterializeTemporaryExpr>(Base)) {
74 SmallVector<const Expr *, 2> CommaLHSs;
75 SmallVector<SubobjectAdjustment, 2> Adjustments;
76 const Expr *Temp = MTE->GetTemporaryExpr();
77 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 Adjustments);
79 // Keep any cv-qualifiers from the reference if we generated a temporary
80 // for it.
81 if (Inner != Temp)
82 return Inner->getType();
83 }
84
85 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000086 }
87
Richard Smithd62306a2011-11-10 06:34:14 +000088 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000089 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000092 APValue::BaseOrMemberType Value;
93 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000094 return Value;
95 }
96
97 /// Get an LValue path entry, which is known to not be an array index, as a
98 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000099 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000100 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000101 }
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000104 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000105 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000106 }
107 /// Determine whether this LValue path entry for a base class names a virtual
108 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000109 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000110 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000111 }
112
Richard Smitha8105bc2012-01-06 16:39:00 +0000113 /// Find the path length and type of the most-derived subobject in the given
114 /// path, and find the size of the containing array, if any.
115 static
116 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
117 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000118 uint64_t &ArraySize, QualType &Type,
119 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 unsigned MostDerivedLength = 0;
121 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000122 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 if (Type->isArrayType()) {
124 const ConstantArrayType *CAT =
125 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
126 Type = CAT->getElementType();
127 ArraySize = CAT->getSize().getZExtValue();
128 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000129 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000130 } else if (Type->isAnyComplexType()) {
131 const ComplexType *CT = Type->castAs<ComplexType>();
132 Type = CT->getElementType();
133 ArraySize = 2;
134 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000135 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000136 } else if (const FieldDecl *FD = getAsField(Path[I])) {
137 Type = FD->getType();
138 ArraySize = 0;
139 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000140 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 } else {
Richard Smith80815602011-11-07 05:07:52 +0000142 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000143 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000144 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000145 }
Richard Smith80815602011-11-07 05:07:52 +0000146 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000147 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000148 }
149
Richard Smitha8105bc2012-01-06 16:39:00 +0000150 // The order of this enum is important for diagnostics.
151 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000152 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000153 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000154 };
155
Richard Smith96e0c102011-11-04 02:25:55 +0000156 /// A path from a glvalue to a subobject of that glvalue.
157 struct SubobjectDesignator {
158 /// True if the subobject was named in a manner not supported by C++11. Such
159 /// lvalues can still be folded, but they are not core constant expressions
160 /// and we cannot perform lvalue-to-rvalue conversions on them.
161 bool Invalid : 1;
162
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 /// Is this a pointer one past the end of an object?
164 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000165
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 /// Indicator of whether the most-derived object is an array element.
167 bool MostDerivedIsArrayElement : 1;
168
Richard Smitha8105bc2012-01-06 16:39:00 +0000169 /// The length of the path to the most-derived object of which this is a
170 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000171 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000172
George Burgess IVa51c4072015-10-16 01:49:01 +0000173 /// The size of the array of which the most-derived object is an element.
174 /// This will always be 0 if the most-derived object is not an array
175 /// element. 0 is not an indicator of whether or not the most-derived object
176 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000177 uint64_t MostDerivedArraySize;
178
179 /// The type of the most derived object referred to by this address.
180 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000181
Richard Smith80815602011-11-07 05:07:52 +0000182 typedef APValue::LValuePathEntry PathEntry;
183
Richard Smith96e0c102011-11-04 02:25:55 +0000184 /// The entries on the path from the glvalue to the designated subobject.
185 SmallVector<PathEntry, 8> Entries;
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000188
Richard Smitha8105bc2012-01-06 16:39:00 +0000189 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000190 : Invalid(false), IsOnePastTheEnd(false),
191 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
192 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000193
194 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000195 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
196 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
197 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000198 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000200 ArrayRef<PathEntry> VEntries = V.getLValuePath();
201 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 if (V.getLValueBase()) {
203 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000204 MostDerivedPathLength =
205 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
206 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 MostDerivedType, IsArray);
208 MostDerivedIsArrayElement = IsArray;
209 }
Richard Smith80815602011-11-07 05:07:52 +0000210 }
211 }
212
Richard Smith96e0c102011-11-04 02:25:55 +0000213 void setInvalid() {
214 Invalid = true;
215 Entries.clear();
216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217
218 /// Determine whether this is a one-past-the-end pointer.
219 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000220 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 if (IsOnePastTheEnd)
222 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
225 return true;
226 return false;
227 }
228
229 /// Check that this refers to a valid subobject.
230 bool isValidSubobject() const {
231 if (Invalid)
232 return false;
233 return !isOnePastTheEnd();
234 }
235 /// Check that this refers to a valid subobject, and if not, produce a
236 /// relevant diagnostic and set the designator as invalid.
237 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
238
239 /// Update this designator to refer to the first element within this array.
240 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000241 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000243 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000244
245 // This is a most-derived object.
246 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 MostDerivedArraySize = CAT->getSize().getZExtValue();
249 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000250 }
251 /// Update this designator to refer to the given base or member of this
252 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000254 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000255 APValue::BaseOrMemberType Value(D, Virtual);
256 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000257 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000258
259 // If this isn't a base class, it's a new most-derived object.
260 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
261 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000262 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 MostDerivedArraySize = 0;
264 MostDerivedPathLength = Entries.size();
265 }
Richard Smith96e0c102011-11-04 02:25:55 +0000266 }
Richard Smith66c96992012-02-18 22:04:06 +0000267 /// Update this designator to refer to the given complex component.
268 void addComplexUnchecked(QualType EltTy, bool Imag) {
269 PathEntry Entry;
270 Entry.ArrayIndex = Imag;
271 Entries.push_back(Entry);
272
273 // This is technically a most-derived object, though in practice this
274 // is unlikely to matter.
275 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000276 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000277 MostDerivedArraySize = 2;
278 MostDerivedPathLength = Entries.size();
279 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000280 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000283 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000284 if (MostDerivedPathLength == Entries.size() &&
285 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000286 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000287 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
288 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
289 setInvalid();
290 }
Richard Smith96e0c102011-11-04 02:25:55 +0000291 return;
292 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000293 // [expr.add]p4: For the purposes of these operators, a pointer to a
294 // nonarray object behaves the same as a pointer to the first element of
295 // an array of length one with the type of the object as its element type.
296 if (IsOnePastTheEnd && N == (uint64_t)-1)
297 IsOnePastTheEnd = false;
298 else if (!IsOnePastTheEnd && N == 1)
299 IsOnePastTheEnd = true;
300 else if (N != 0) {
301 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000302 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 }
Richard Smith96e0c102011-11-04 02:25:55 +0000304 }
305 };
306
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// A stack frame in the constexpr call stack.
308 struct CallStackFrame {
309 EvalInfo &Info;
310
311 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000313
Richard Smithf6f003a2011-12-16 19:06:07 +0000314 /// CallLoc - The location of the call expression for this call.
315 SourceLocation CallLoc;
316
317 /// Callee - The function which was called.
318 const FunctionDecl *Callee;
319
Richard Smithb228a862012-02-15 02:18:13 +0000320 /// Index - The call index of this call.
321 unsigned Index;
322
Richard Smithd62306a2011-11-10 06:34:14 +0000323 /// This - The binding for the this pointer in this call, if any.
324 const LValue *This;
325
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000326 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000327 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000328 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000329
Eli Friedman4830ec82012-06-25 21:21:08 +0000330 // Note that we intentionally use std::map here so that references to
331 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000332 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333 typedef MapTy::const_iterator temp_iterator;
334 /// Temporaries - Temporary lvalues materialized within this stack frame.
335 MapTy Temporaries;
336
Richard Smithf6f003a2011-12-16 19:06:07 +0000337 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
338 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000339 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000340 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000341
342 APValue *getTemporary(const void *Key) {
343 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000344 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000345 }
346 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000347 };
348
Richard Smith852c9db2013-04-20 22:23:05 +0000349 /// Temporarily override 'this'.
350 class ThisOverrideRAII {
351 public:
352 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
353 : Frame(Frame), OldThis(Frame.This) {
354 if (Enable)
355 Frame.This = NewThis;
356 }
357 ~ThisOverrideRAII() {
358 Frame.This = OldThis;
359 }
360 private:
361 CallStackFrame &Frame;
362 const LValue *OldThis;
363 };
364
Richard Smith92b1ce02011-12-12 09:28:41 +0000365 /// A partial diagnostic which we might know in advance that we are not going
366 /// to emit.
367 class OptionalDiagnostic {
368 PartialDiagnostic *Diag;
369
370 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000371 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
372 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000373
374 template<typename T>
375 OptionalDiagnostic &operator<<(const T &v) {
376 if (Diag)
377 *Diag << v;
378 return *this;
379 }
Richard Smithfe800032012-01-31 04:08:20 +0000380
381 OptionalDiagnostic &operator<<(const APSInt &I) {
382 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000383 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000384 I.toString(Buffer);
385 *Diag << StringRef(Buffer.data(), Buffer.size());
386 }
387 return *this;
388 }
389
390 OptionalDiagnostic &operator<<(const APFloat &F) {
391 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000392 // FIXME: Force the precision of the source value down so we don't
393 // print digits which are usually useless (we don't really care here if
394 // we truncate a digit by accident in edge cases). Ideally,
395 // APFloat::toString would automatically print the shortest
396 // representation which rounds to the correct value, but it's a bit
397 // tricky to implement.
398 unsigned precision =
399 llvm::APFloat::semanticsPrecision(F.getSemantics());
400 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000401 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000402 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000403 *Diag << StringRef(Buffer.data(), Buffer.size());
404 }
405 return *this;
406 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000407 };
408
Richard Smith08d6a2c2013-07-24 07:11:57 +0000409 /// A cleanup, and a flag indicating whether it is lifetime-extended.
410 class Cleanup {
411 llvm::PointerIntPair<APValue*, 1, bool> Value;
412
413 public:
414 Cleanup(APValue *Val, bool IsLifetimeExtended)
415 : Value(Val, IsLifetimeExtended) {}
416
417 bool isLifetimeExtended() const { return Value.getInt(); }
418 void endLifetime() {
419 *Value.getPointer() = APValue();
420 }
421 };
422
Richard Smithb228a862012-02-15 02:18:13 +0000423 /// EvalInfo - This is a private struct used by the evaluator to capture
424 /// information about a subexpression as it is folded. It retains information
425 /// about the AST context, but also maintains information about the folded
426 /// expression.
427 ///
428 /// If an expression could be evaluated, it is still possible it is not a C
429 /// "integer constant expression" or constant expression. If not, this struct
430 /// captures information about how and why not.
431 ///
432 /// One bit of information passed *into* the request for constant folding
433 /// indicates whether the subexpression is "evaluated" or not according to C
434 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
435 /// evaluate the expression regardless of what the RHS is, but C only allows
436 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000438 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000439
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000440 /// EvalStatus - Contains information about the evaluation.
441 Expr::EvalStatus &EvalStatus;
442
443 /// CurrentCall - The top of the constexpr call stack.
444 CallStackFrame *CurrentCall;
445
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000446 /// CallStackDepth - The number of calls in the call stack right now.
447 unsigned CallStackDepth;
448
Richard Smithb228a862012-02-15 02:18:13 +0000449 /// NextCallIndex - The next call index to assign.
450 unsigned NextCallIndex;
451
Richard Smitha3d3bd22013-05-08 02:12:03 +0000452 /// StepsLeft - The remaining number of evaluation steps we're permitted
453 /// to perform. This is essentially a limit for the number of statements
454 /// we will evaluate.
455 unsigned StepsLeft;
456
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000457 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000458 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000459 CallStackFrame BottomFrame;
460
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461 /// A stack of values whose lifetimes end at the end of some surrounding
462 /// evaluation frame.
463 llvm::SmallVector<Cleanup, 16> CleanupStack;
464
Richard Smithd62306a2011-11-10 06:34:14 +0000465 /// EvaluatingDecl - This is the declaration whose initializer is being
466 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000467 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000468
469 /// EvaluatingDeclValue - This is the value being constructed for the
470 /// declaration whose initializer is being evaluated, if any.
471 APValue *EvaluatingDeclValue;
472
Richard Smith357362d2011-12-13 06:39:58 +0000473 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
474 /// notes attached to it will also be stored, otherwise they will not be.
475 bool HasActiveDiagnostic;
476
Richard Smith0c6124b2015-12-03 01:36:22 +0000477 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
478 /// fold (not just why it's not strictly a constant expression)?
479 bool HasFoldFailureDiagnostic;
480
Richard Smith6d4c6582013-11-05 22:18:15 +0000481 enum EvaluationMode {
482 /// Evaluate as a constant expression. Stop if we find that the expression
483 /// is not a constant expression.
484 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000485
Richard Smith6d4c6582013-11-05 22:18:15 +0000486 /// Evaluate as a potential constant expression. Keep going if we hit a
487 /// construct that we can't evaluate yet (because we don't yet know the
488 /// value of something) but stop if we hit something that could never be
489 /// a constant expression.
490 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000491
Richard Smith6d4c6582013-11-05 22:18:15 +0000492 /// Fold the expression to a constant. Stop if we hit a side-effect that
493 /// we can't model.
494 EM_ConstantFold,
495
496 /// Evaluate the expression looking for integer overflow and similar
497 /// issues. Don't worry about side-effects, and try to visit all
498 /// subexpressions.
499 EM_EvaluateForOverflow,
500
501 /// Evaluate in any way we know how. Don't worry about side-effects that
502 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000503 EM_IgnoreSideEffects,
504
505 /// Evaluate as a constant expression. Stop if we find that the expression
506 /// is not a constant expression. Some expressions can be retried in the
507 /// optimizer if we don't constant fold them here, but in an unevaluated
508 /// context we try to fold them immediately since the optimizer never
509 /// gets a chance to look at it.
510 EM_ConstantExpressionUnevaluated,
511
512 /// Evaluate as a potential constant expression. Keep going if we hit a
513 /// construct that we can't evaluate yet (because we don't yet know the
514 /// value of something) but stop if we hit something that could never be
515 /// a constant expression. Some expressions can be retried in the
516 /// optimizer if we don't constant fold them here, but in an unevaluated
517 /// context we try to fold them immediately since the optimizer never
518 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000519 EM_PotentialConstantExpressionUnevaluated,
520
521 /// Evaluate as a constant expression. Continue evaluating if we find a
522 /// MemberExpr with a base that can't be evaluated.
523 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000524 } EvalMode;
525
526 /// Are we checking whether the expression is a potential constant
527 /// expression?
528 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000529 return EvalMode == EM_PotentialConstantExpression ||
530 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000531 }
532
533 /// Are we checking an expression for overflow?
534 // FIXME: We should check for any kind of undefined or suspicious behavior
535 // in such constructs, not just overflow.
536 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
537
538 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000539 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000540 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000541 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000542 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
543 EvaluatingDecl((const ValueDecl *)nullptr),
544 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith0c6124b2015-12-03 01:36:22 +0000545 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000546
Richard Smith7525ff62013-05-09 07:14:00 +0000547 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
548 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000549 EvaluatingDeclValue = &Value;
550 }
551
David Blaikiebbafb8a2012-03-11 07:00:24 +0000552 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000553
Richard Smith357362d2011-12-13 06:39:58 +0000554 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000555 // Don't perform any constexpr calls (other than the call we're checking)
556 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000557 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000558 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000559 if (NextCallIndex == 0) {
560 // NextCallIndex has wrapped around.
561 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
562 return false;
563 }
Richard Smith357362d2011-12-13 06:39:58 +0000564 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
565 return true;
566 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
567 << getLangOpts().ConstexprCallDepth;
568 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000569 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000570
Richard Smithb228a862012-02-15 02:18:13 +0000571 CallStackFrame *getCallFrame(unsigned CallIndex) {
572 assert(CallIndex && "no call index in getCallFrame");
573 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
574 // be null in this loop.
575 CallStackFrame *Frame = CurrentCall;
576 while (Frame->Index > CallIndex)
577 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000578 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000579 }
580
Richard Smitha3d3bd22013-05-08 02:12:03 +0000581 bool nextStep(const Stmt *S) {
582 if (!StepsLeft) {
583 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
584 return false;
585 }
586 --StepsLeft;
587 return true;
588 }
589
Richard Smith357362d2011-12-13 06:39:58 +0000590 private:
591 /// Add a diagnostic to the diagnostics list.
592 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
593 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
594 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
595 return EvalStatus.Diag->back().second;
596 }
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598 /// Add notes containing a call stack to the current point of evaluation.
599 void addCallStack(unsigned Limit);
600
Richard Smith357362d2011-12-13 06:39:58 +0000601 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000602 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000603 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
604 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000605 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000606 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000607 // If we have a prior diagnostic, it will be noting that the expression
608 // isn't a constant expression. This diagnostic is more important,
609 // unless we require this evaluation to produce a constant expression.
610 //
611 // FIXME: We might want to show both diagnostics to the user in
612 // EM_ConstantFold mode.
613 if (!EvalStatus.Diag->empty()) {
614 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000615 case EM_ConstantFold:
616 case EM_IgnoreSideEffects:
617 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000618 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000619 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000620 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000621 case EM_ConstantExpression:
622 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000623 case EM_ConstantExpressionUnevaluated:
624 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000625 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000626 HasActiveDiagnostic = false;
627 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000628 }
629 }
630
Richard Smithf6f003a2011-12-16 19:06:07 +0000631 unsigned CallStackNotes = CallStackDepth - 1;
632 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
633 if (Limit)
634 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000635 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000636 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000637
Richard Smith357362d2011-12-13 06:39:58 +0000638 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000639 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000640 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000641 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
642 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000643 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000644 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000645 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 }
Richard Smith357362d2011-12-13 06:39:58 +0000647 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000648 return OptionalDiagnostic();
649 }
650
Richard Smithce1ec5e2012-03-15 04:53:45 +0000651 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
652 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000653 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000654 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000655 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000656 HasActiveDiagnostic = false;
657 return OptionalDiagnostic();
658 }
659
Richard Smith92b1ce02011-12-12 09:28:41 +0000660 /// Diagnose that the evaluation does not produce a C++11 core constant
661 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000662 ///
663 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
664 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000665 template<typename LocArg>
666 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000667 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000668 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000669 // Don't override a previous diagnostic. Don't bother collecting
670 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000671 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000672 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000673 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000674 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000675 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000676 }
677
678 /// Add a note to a prior diagnostic.
679 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
680 if (!HasActiveDiagnostic)
681 return OptionalDiagnostic();
682 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000683 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000684
685 /// Add a stack of notes to a prior diagnostic.
686 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
687 if (HasActiveDiagnostic) {
688 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
689 Diags.begin(), Diags.end());
690 }
691 }
Richard Smith253c2a32012-01-27 01:14:48 +0000692
Richard Smith6d4c6582013-11-05 22:18:15 +0000693 /// Should we continue evaluation after encountering a side-effect that we
694 /// couldn't model?
695 bool keepEvaluatingAfterSideEffect() {
696 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000697 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000698 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 case EM_EvaluateForOverflow:
700 case EM_IgnoreSideEffects:
701 return true;
702
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000704 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000705 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000706 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 return false;
708 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000709 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000710 }
711
712 /// Note that we have had a side-effect, and determine whether we should
713 /// keep evaluating.
714 bool noteSideEffect() {
715 EvalStatus.HasSideEffects = true;
716 return keepEvaluatingAfterSideEffect();
717 }
718
Richard Smithce8eca52015-12-08 03:21:47 +0000719 /// Should we continue evaluation after encountering undefined behavior?
720 bool keepEvaluatingAfterUndefinedBehavior() {
721 switch (EvalMode) {
722 case EM_EvaluateForOverflow:
723 case EM_IgnoreSideEffects:
724 case EM_ConstantFold:
725 case EM_DesignatorFold:
726 return true;
727
728 case EM_PotentialConstantExpression:
729 case EM_PotentialConstantExpressionUnevaluated:
730 case EM_ConstantExpression:
731 case EM_ConstantExpressionUnevaluated:
732 return false;
733 }
734 llvm_unreachable("Missed EvalMode case");
735 }
736
737 /// Note that we hit something that was technically undefined behavior, but
738 /// that we can evaluate past it (such as signed overflow or floating-point
739 /// division by zero.)
740 bool noteUndefinedBehavior() {
741 EvalStatus.HasUndefinedBehavior = true;
742 return keepEvaluatingAfterUndefinedBehavior();
743 }
744
Richard Smith253c2a32012-01-27 01:14:48 +0000745 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000746 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000747 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000748 if (!StepsLeft)
749 return false;
750
751 switch (EvalMode) {
752 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000753 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000754 case EM_EvaluateForOverflow:
755 return true;
756
757 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000758 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000759 case EM_ConstantFold:
760 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000761 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 return false;
763 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000764 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000765 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000766
767 bool allowInvalidBaseExpr() const {
768 return EvalMode == EM_DesignatorFold;
769 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000770 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000771
772 /// Object used to treat all foldable expressions as constant expressions.
773 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000774 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000775 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 bool HadNoPriorDiags;
777 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000778
Richard Smith6d4c6582013-11-05 22:18:15 +0000779 explicit FoldConstant(EvalInfo &Info, bool Enabled)
780 : Info(Info),
781 Enabled(Enabled),
782 HadNoPriorDiags(Info.EvalStatus.Diag &&
783 Info.EvalStatus.Diag->empty() &&
784 !Info.EvalStatus.HasSideEffects),
785 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000786 if (Enabled &&
787 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
788 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000789 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000790 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000791 void keepDiagnostics() { Enabled = false; }
792 ~FoldConstant() {
793 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000794 !Info.EvalStatus.HasSideEffects)
795 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000797 }
798 };
Richard Smith17100ba2012-02-16 02:46:34 +0000799
George Burgess IV3a03fab2015-09-04 21:28:13 +0000800 /// RAII object used to treat the current evaluation as the correct pointer
801 /// offset fold for the current EvalMode
802 struct FoldOffsetRAII {
803 EvalInfo &Info;
804 EvalInfo::EvaluationMode OldMode;
805 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
806 : Info(Info), OldMode(Info.EvalMode) {
807 if (!Info.checkingPotentialConstantExpression())
808 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
809 : EvalInfo::EM_ConstantFold;
810 }
811
812 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
813 };
814
Richard Smith17100ba2012-02-16 02:46:34 +0000815 /// RAII object used to suppress diagnostics and side-effects from a
816 /// speculative evaluation.
817 class SpeculativeEvaluationRAII {
818 EvalInfo &Info;
819 Expr::EvalStatus Old;
820
821 public:
822 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000823 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000824 : Info(Info), Old(Info.EvalStatus) {
825 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000826 // If we're speculatively evaluating, we may have skipped over some
827 // evaluations and missed out a side effect.
828 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000829 }
830 ~SpeculativeEvaluationRAII() {
831 Info.EvalStatus = Old;
832 }
833 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000834
835 /// RAII object wrapping a full-expression or block scope, and handling
836 /// the ending of the lifetime of temporaries created within it.
837 template<bool IsFullExpression>
838 class ScopeRAII {
839 EvalInfo &Info;
840 unsigned OldStackSize;
841 public:
842 ScopeRAII(EvalInfo &Info)
843 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
844 ~ScopeRAII() {
845 // Body moved to a static method to encourage the compiler to inline away
846 // instances of this class.
847 cleanup(Info, OldStackSize);
848 }
849 private:
850 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
851 unsigned NewEnd = OldStackSize;
852 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
853 I != N; ++I) {
854 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
855 // Full-expression cleanup of a lifetime-extended temporary: nothing
856 // to do, just move this cleanup to the right place in the stack.
857 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
858 ++NewEnd;
859 } else {
860 // End the lifetime of the object.
861 Info.CleanupStack[I].endLifetime();
862 }
863 }
864 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
865 Info.CleanupStack.end());
866 }
867 };
868 typedef ScopeRAII<false> BlockScopeRAII;
869 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000870}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000871
Richard Smitha8105bc2012-01-06 16:39:00 +0000872bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
873 CheckSubobjectKind CSK) {
874 if (Invalid)
875 return false;
876 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000877 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000878 << CSK;
879 setInvalid();
880 return false;
881 }
882 return true;
883}
884
885void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
886 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000887 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000888 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000889 << static_cast<int>(N) << /*array*/ 0
890 << static_cast<unsigned>(MostDerivedArraySize);
891 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000892 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000893 << static_cast<int>(N) << /*non-array*/ 1;
894 setInvalid();
895}
896
Richard Smithf6f003a2011-12-16 19:06:07 +0000897CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
898 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000899 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000900 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000901 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000902 Info.CurrentCall = this;
903 ++Info.CallStackDepth;
904}
905
906CallStackFrame::~CallStackFrame() {
907 assert(Info.CurrentCall == this && "calls retired out of order");
908 --Info.CallStackDepth;
909 Info.CurrentCall = Caller;
910}
911
Richard Smith08d6a2c2013-07-24 07:11:57 +0000912APValue &CallStackFrame::createTemporary(const void *Key,
913 bool IsLifetimeExtended) {
914 APValue &Result = Temporaries[Key];
915 assert(Result.isUninit() && "temporary created multiple times");
916 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
917 return Result;
918}
919
Richard Smith84401042013-06-03 05:03:02 +0000920static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000921
922void EvalInfo::addCallStack(unsigned Limit) {
923 // Determine which calls to skip, if any.
924 unsigned ActiveCalls = CallStackDepth - 1;
925 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
926 if (Limit && Limit < ActiveCalls) {
927 SkipStart = Limit / 2 + Limit % 2;
928 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000929 }
930
Richard Smithf6f003a2011-12-16 19:06:07 +0000931 // Walk the call stack and add the diagnostics.
932 unsigned CallIdx = 0;
933 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
934 Frame = Frame->Caller, ++CallIdx) {
935 // Skip this call?
936 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
937 if (CallIdx == SkipStart) {
938 // Note that we're skipping calls.
939 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
940 << unsigned(ActiveCalls - Limit);
941 }
942 continue;
943 }
944
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000945 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000946 llvm::raw_svector_ostream Out(Buffer);
947 describeCall(Frame, Out);
948 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
949 }
950}
951
952namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000953 struct ComplexValue {
954 private:
955 bool IsInt;
956
957 public:
958 APSInt IntReal, IntImag;
959 APFloat FloatReal, FloatImag;
960
961 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
962
963 void makeComplexFloat() { IsInt = false; }
964 bool isComplexFloat() const { return !IsInt; }
965 APFloat &getComplexFloatReal() { return FloatReal; }
966 APFloat &getComplexFloatImag() { return FloatImag; }
967
968 void makeComplexInt() { IsInt = true; }
969 bool isComplexInt() const { return IsInt; }
970 APSInt &getComplexIntReal() { return IntReal; }
971 APSInt &getComplexIntImag() { return IntImag; }
972
Richard Smith2e312c82012-03-03 22:46:17 +0000973 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000974 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000975 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000976 else
Richard Smith2e312c82012-03-03 22:46:17 +0000977 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000978 }
Richard Smith2e312c82012-03-03 22:46:17 +0000979 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000980 assert(v.isComplexFloat() || v.isComplexInt());
981 if (v.isComplexFloat()) {
982 makeComplexFloat();
983 FloatReal = v.getComplexFloatReal();
984 FloatImag = v.getComplexFloatImag();
985 } else {
986 makeComplexInt();
987 IntReal = v.getComplexIntReal();
988 IntImag = v.getComplexIntImag();
989 }
990 }
John McCall93d91dc2010-05-07 17:22:02 +0000991 };
John McCall45d55e42010-05-07 21:00:08 +0000992
993 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000994 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000995 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000996 bool InvalidBase : 1;
997 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000998 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000999
Richard Smithce40ad62011-11-12 22:28:03 +00001000 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001001 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001002 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001003 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001004 SubobjectDesignator &getLValueDesignator() { return Designator; }
1005 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001006
Richard Smith2e312c82012-03-03 22:46:17 +00001007 void moveInto(APValue &V) const {
1008 if (Designator.Invalid)
1009 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1010 else
1011 V = APValue(Base, Offset, Designator.Entries,
1012 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001013 }
Richard Smith2e312c82012-03-03 22:46:17 +00001014 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001015 assert(V.isLValue());
1016 Base = V.getLValueBase();
1017 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001018 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001019 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001020 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001021 }
1022
George Burgess IV3a03fab2015-09-04 21:28:13 +00001023 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001024 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001025 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001026 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001027 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001028 Designator = SubobjectDesignator(getType(B));
1029 }
1030
George Burgess IV3a03fab2015-09-04 21:28:13 +00001031 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1032 set(B, I, true);
1033 }
1034
Richard Smitha8105bc2012-01-06 16:39:00 +00001035 // Check that this LValue is not based on a null pointer. If it is, produce
1036 // a diagnostic and mark the designator as invalid.
1037 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1038 CheckSubobjectKind CSK) {
1039 if (Designator.Invalid)
1040 return false;
1041 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001042 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001043 << CSK;
1044 Designator.setInvalid();
1045 return false;
1046 }
1047 return true;
1048 }
1049
1050 // Check this LValue refers to an object. If not, set the designator to be
1051 // invalid and emit a diagnostic.
1052 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001053 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001054 Designator.checkSubobject(Info, E, CSK);
1055 }
1056
1057 void addDecl(EvalInfo &Info, const Expr *E,
1058 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001059 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1060 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001061 }
1062 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001063 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1064 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001065 }
Richard Smith66c96992012-02-18 22:04:06 +00001066 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001067 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1068 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001069 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001070 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001071 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001072 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001073 }
John McCall45d55e42010-05-07 21:00:08 +00001074 };
Richard Smith027bf112011-11-17 22:56:20 +00001075
1076 struct MemberPtr {
1077 MemberPtr() {}
1078 explicit MemberPtr(const ValueDecl *Decl) :
1079 DeclAndIsDerivedMember(Decl, false), Path() {}
1080
1081 /// The member or (direct or indirect) field referred to by this member
1082 /// pointer, or 0 if this is a null member pointer.
1083 const ValueDecl *getDecl() const {
1084 return DeclAndIsDerivedMember.getPointer();
1085 }
1086 /// Is this actually a member of some type derived from the relevant class?
1087 bool isDerivedMember() const {
1088 return DeclAndIsDerivedMember.getInt();
1089 }
1090 /// Get the class which the declaration actually lives in.
1091 const CXXRecordDecl *getContainingRecord() const {
1092 return cast<CXXRecordDecl>(
1093 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1094 }
1095
Richard Smith2e312c82012-03-03 22:46:17 +00001096 void moveInto(APValue &V) const {
1097 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001098 }
Richard Smith2e312c82012-03-03 22:46:17 +00001099 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001100 assert(V.isMemberPointer());
1101 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1102 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1103 Path.clear();
1104 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1105 Path.insert(Path.end(), P.begin(), P.end());
1106 }
1107
1108 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1109 /// whether the member is a member of some class derived from the class type
1110 /// of the member pointer.
1111 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1112 /// Path - The path of base/derived classes from the member declaration's
1113 /// class (exclusive) to the class type of the member pointer (inclusive).
1114 SmallVector<const CXXRecordDecl*, 4> Path;
1115
1116 /// Perform a cast towards the class of the Decl (either up or down the
1117 /// hierarchy).
1118 bool castBack(const CXXRecordDecl *Class) {
1119 assert(!Path.empty());
1120 const CXXRecordDecl *Expected;
1121 if (Path.size() >= 2)
1122 Expected = Path[Path.size() - 2];
1123 else
1124 Expected = getContainingRecord();
1125 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1126 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1127 // if B does not contain the original member and is not a base or
1128 // derived class of the class containing the original member, the result
1129 // of the cast is undefined.
1130 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1131 // (D::*). We consider that to be a language defect.
1132 return false;
1133 }
1134 Path.pop_back();
1135 return true;
1136 }
1137 /// Perform a base-to-derived member pointer cast.
1138 bool castToDerived(const CXXRecordDecl *Derived) {
1139 if (!getDecl())
1140 return true;
1141 if (!isDerivedMember()) {
1142 Path.push_back(Derived);
1143 return true;
1144 }
1145 if (!castBack(Derived))
1146 return false;
1147 if (Path.empty())
1148 DeclAndIsDerivedMember.setInt(false);
1149 return true;
1150 }
1151 /// Perform a derived-to-base member pointer cast.
1152 bool castToBase(const CXXRecordDecl *Base) {
1153 if (!getDecl())
1154 return true;
1155 if (Path.empty())
1156 DeclAndIsDerivedMember.setInt(true);
1157 if (isDerivedMember()) {
1158 Path.push_back(Base);
1159 return true;
1160 }
1161 return castBack(Base);
1162 }
1163 };
Richard Smith357362d2011-12-13 06:39:58 +00001164
Richard Smith7bb00672012-02-01 01:42:44 +00001165 /// Compare two member pointers, which are assumed to be of the same type.
1166 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1167 if (!LHS.getDecl() || !RHS.getDecl())
1168 return !LHS.getDecl() && !RHS.getDecl();
1169 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1170 return false;
1171 return LHS.Path == RHS.Path;
1172 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001173}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001174
Richard Smith2e312c82012-03-03 22:46:17 +00001175static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001176static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1177 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001178 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001179static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1180static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001181static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1182 EvalInfo &Info);
1183static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001184static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001185static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001186 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001187static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001188static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001189static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001190static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001191
1192//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001193// Misc utilities
1194//===----------------------------------------------------------------------===//
1195
Richard Smith84401042013-06-03 05:03:02 +00001196/// Produce a string describing the given constexpr call.
1197static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1198 unsigned ArgIndex = 0;
1199 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1200 !isa<CXXConstructorDecl>(Frame->Callee) &&
1201 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1202
1203 if (!IsMemberCall)
1204 Out << *Frame->Callee << '(';
1205
1206 if (Frame->This && IsMemberCall) {
1207 APValue Val;
1208 Frame->This->moveInto(Val);
1209 Val.printPretty(Out, Frame->Info.Ctx,
1210 Frame->This->Designator.MostDerivedType);
1211 // FIXME: Add parens around Val if needed.
1212 Out << "->" << *Frame->Callee << '(';
1213 IsMemberCall = false;
1214 }
1215
1216 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1217 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1218 if (ArgIndex > (unsigned)IsMemberCall)
1219 Out << ", ";
1220
1221 const ParmVarDecl *Param = *I;
1222 const APValue &Arg = Frame->Arguments[ArgIndex];
1223 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1224
1225 if (ArgIndex == 0 && IsMemberCall)
1226 Out << "->" << *Frame->Callee << '(';
1227 }
1228
1229 Out << ')';
1230}
1231
Richard Smithd9f663b2013-04-22 15:31:51 +00001232/// Evaluate an expression to see if it had side-effects, and discard its
1233/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001234/// \return \c true if the caller should keep evaluating.
1235static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001236 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001237 if (!Evaluate(Scratch, Info, E))
1238 // We don't need the value, but we might have skipped a side effect here.
1239 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001240 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001241}
1242
Richard Smith861b5b52013-05-07 23:34:45 +00001243/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1244/// return its existing value.
1245static int64_t getExtValue(const APSInt &Value) {
1246 return Value.isSigned() ? Value.getSExtValue()
1247 : static_cast<int64_t>(Value.getZExtValue());
1248}
1249
Richard Smithd62306a2011-11-10 06:34:14 +00001250/// Should this call expression be treated as a string literal?
1251static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001252 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001253 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1254 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1255}
1256
Richard Smithce40ad62011-11-12 22:28:03 +00001257static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001258 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1259 // constant expression of pointer type that evaluates to...
1260
1261 // ... a null pointer value, or a prvalue core constant expression of type
1262 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001263 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001264
Richard Smithce40ad62011-11-12 22:28:03 +00001265 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1266 // ... the address of an object with static storage duration,
1267 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1268 return VD->hasGlobalStorage();
1269 // ... the address of a function,
1270 return isa<FunctionDecl>(D);
1271 }
1272
1273 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001274 switch (E->getStmtClass()) {
1275 default:
1276 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001277 case Expr::CompoundLiteralExprClass: {
1278 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1279 return CLE->isFileScope() && CLE->isLValue();
1280 }
Richard Smithe6c01442013-06-05 00:46:14 +00001281 case Expr::MaterializeTemporaryExprClass:
1282 // A materialized temporary might have been lifetime-extended to static
1283 // storage duration.
1284 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001285 // A string literal has static storage duration.
1286 case Expr::StringLiteralClass:
1287 case Expr::PredefinedExprClass:
1288 case Expr::ObjCStringLiteralClass:
1289 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001290 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001291 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001292 return true;
1293 case Expr::CallExprClass:
1294 return IsStringLiteralCall(cast<CallExpr>(E));
1295 // For GCC compatibility, &&label has static storage duration.
1296 case Expr::AddrLabelExprClass:
1297 return true;
1298 // A Block literal expression may be used as the initialization value for
1299 // Block variables at global or local static scope.
1300 case Expr::BlockExprClass:
1301 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001302 case Expr::ImplicitValueInitExprClass:
1303 // FIXME:
1304 // We can never form an lvalue with an implicit value initialization as its
1305 // base through expression evaluation, so these only appear in one case: the
1306 // implicit variable declaration we invent when checking whether a constexpr
1307 // constructor can produce a constant expression. We must assume that such
1308 // an expression might be a global lvalue.
1309 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001310 }
John McCall95007602010-05-10 23:27:23 +00001311}
1312
Richard Smithb228a862012-02-15 02:18:13 +00001313static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1314 assert(Base && "no location for a null lvalue");
1315 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1316 if (VD)
1317 Info.Note(VD->getLocation(), diag::note_declared_at);
1318 else
Ted Kremenek28831752012-08-23 20:46:57 +00001319 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001320 diag::note_constexpr_temporary_here);
1321}
1322
Richard Smith80815602011-11-07 05:07:52 +00001323/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001324/// value for an address or reference constant expression. Return true if we
1325/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001326static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1327 QualType Type, const LValue &LVal) {
1328 bool IsReferenceType = Type->isReferenceType();
1329
Richard Smith357362d2011-12-13 06:39:58 +00001330 APValue::LValueBase Base = LVal.getLValueBase();
1331 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1332
Richard Smith0dea49e2012-02-18 04:58:18 +00001333 // Check that the object is a global. Note that the fake 'this' object we
1334 // manufacture when checking potential constant expressions is conservatively
1335 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001336 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001338 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001339 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1340 << IsReferenceType << !Designator.Entries.empty()
1341 << !!VD << VD;
1342 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001343 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001344 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001345 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001346 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001347 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001348 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001349 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001350 LVal.getLValueCallIndex() == 0) &&
1351 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001352
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001353 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1354 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001355 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001356 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001357 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001358
Hans Wennborg82dd8772014-06-25 22:19:48 +00001359 // A dllimport variable never acts like a constant.
1360 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001361 return false;
1362 }
1363 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1364 // __declspec(dllimport) must be handled very carefully:
1365 // We must never initialize an expression with the thunk in C++.
1366 // Doing otherwise would allow the same id-expression to yield
1367 // different addresses for the same function in different translation
1368 // units. However, this means that we must dynamically initialize the
1369 // expression with the contents of the import address table at runtime.
1370 //
1371 // The C language has no notion of ODR; furthermore, it has no notion of
1372 // dynamic initialization. This means that we are permitted to
1373 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001374 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001375 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001376 }
1377 }
1378
Richard Smitha8105bc2012-01-06 16:39:00 +00001379 // Allow address constant expressions to be past-the-end pointers. This is
1380 // an extension: the standard requires them to point to an object.
1381 if (!IsReferenceType)
1382 return true;
1383
1384 // A reference constant expression must refer to an object.
1385 if (!Base) {
1386 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001387 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001388 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001389 }
1390
Richard Smith357362d2011-12-13 06:39:58 +00001391 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001392 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001393 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001394 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001395 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001396 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001397 }
1398
Richard Smith80815602011-11-07 05:07:52 +00001399 return true;
1400}
1401
Richard Smithfddd3842011-12-30 21:15:51 +00001402/// Check that this core constant expression is of literal type, and if not,
1403/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001404static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001405 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001406 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001407 return true;
1408
Richard Smith7525ff62013-05-09 07:14:00 +00001409 // C++1y: A constant initializer for an object o [...] may also invoke
1410 // constexpr constructors for o and its subobjects even if those objects
1411 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001412 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001413 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001414 return true;
1415
Richard Smithfddd3842011-12-30 21:15:51 +00001416 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001417 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001418 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001419 << E->getType();
1420 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001421 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001422 return false;
1423}
1424
Richard Smith0b0a0b62011-10-29 20:57:55 +00001425/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001426/// constant expression. If not, report an appropriate diagnostic. Does not
1427/// check that the expression is of literal type.
1428static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1429 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001430 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001431 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1432 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001433 return false;
1434 }
1435
Richard Smith77be48a2014-07-31 06:31:19 +00001436 // We allow _Atomic(T) to be initialized from anything that T can be
1437 // initialized from.
1438 if (const AtomicType *AT = Type->getAs<AtomicType>())
1439 Type = AT->getValueType();
1440
Richard Smithb228a862012-02-15 02:18:13 +00001441 // Core issue 1454: For a literal constant expression of array or class type,
1442 // each subobject of its value shall have been initialized by a constant
1443 // expression.
1444 if (Value.isArray()) {
1445 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1446 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1447 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1448 Value.getArrayInitializedElt(I)))
1449 return false;
1450 }
1451 if (!Value.hasArrayFiller())
1452 return true;
1453 return CheckConstantExpression(Info, DiagLoc, EltTy,
1454 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001455 }
Richard Smithb228a862012-02-15 02:18:13 +00001456 if (Value.isUnion() && Value.getUnionField()) {
1457 return CheckConstantExpression(Info, DiagLoc,
1458 Value.getUnionField()->getType(),
1459 Value.getUnionValue());
1460 }
1461 if (Value.isStruct()) {
1462 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1463 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1464 unsigned BaseIndex = 0;
1465 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1466 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1467 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1468 Value.getStructBase(BaseIndex)))
1469 return false;
1470 }
1471 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001472 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001473 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1474 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001475 return false;
1476 }
1477 }
1478
1479 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001480 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001481 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001482 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1483 }
1484
1485 // Everything else is fine.
1486 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001487}
1488
Benjamin Kramer8407df72015-03-09 16:47:52 +00001489static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001490 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001491}
1492
1493static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001494 if (Value.CallIndex)
1495 return false;
1496 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1497 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001498}
1499
Richard Smithcecf1842011-11-01 21:06:14 +00001500static bool IsWeakLValue(const LValue &Value) {
1501 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001502 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001503}
1504
David Majnemerb5116032014-12-09 23:32:34 +00001505static bool isZeroSized(const LValue &Value) {
1506 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001507 if (Decl && isa<VarDecl>(Decl)) {
1508 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001509 if (Ty->isArrayType())
1510 return Ty->isIncompleteType() ||
1511 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001512 }
1513 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001514}
1515
Richard Smith2e312c82012-03-03 22:46:17 +00001516static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001517 // A null base expression indicates a null pointer. These are always
1518 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001519 if (!Value.getLValueBase()) {
1520 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001521 return true;
1522 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001523
Richard Smith027bf112011-11-17 22:56:20 +00001524 // We have a non-null base. These are generally known to be true, but if it's
1525 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001526 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001527 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001528 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001529}
1530
Richard Smith2e312c82012-03-03 22:46:17 +00001531static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001532 switch (Val.getKind()) {
1533 case APValue::Uninitialized:
1534 return false;
1535 case APValue::Int:
1536 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001537 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001538 case APValue::Float:
1539 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001540 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001541 case APValue::ComplexInt:
1542 Result = Val.getComplexIntReal().getBoolValue() ||
1543 Val.getComplexIntImag().getBoolValue();
1544 return true;
1545 case APValue::ComplexFloat:
1546 Result = !Val.getComplexFloatReal().isZero() ||
1547 !Val.getComplexFloatImag().isZero();
1548 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001549 case APValue::LValue:
1550 return EvalPointerValueAsBool(Val, Result);
1551 case APValue::MemberPointer:
1552 Result = Val.getMemberPointerDecl();
1553 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001554 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001555 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001556 case APValue::Struct:
1557 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001558 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001559 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001560 }
1561
Richard Smith11562c52011-10-28 17:51:58 +00001562 llvm_unreachable("unknown APValue kind");
1563}
1564
1565static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1566 EvalInfo &Info) {
1567 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001568 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001569 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001570 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001571 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001572}
1573
Richard Smith357362d2011-12-13 06:39:58 +00001574template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001575static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001576 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001577 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001578 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001579 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001580}
1581
1582static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1583 QualType SrcType, const APFloat &Value,
1584 QualType DestType, APSInt &Result) {
1585 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001586 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001587 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001588
Richard Smith357362d2011-12-13 06:39:58 +00001589 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001590 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001591 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1592 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001593 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001594 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001595}
1596
Richard Smith357362d2011-12-13 06:39:58 +00001597static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1598 QualType SrcType, QualType DestType,
1599 APFloat &Result) {
1600 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001601 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001602 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1603 APFloat::rmNearestTiesToEven, &ignored)
1604 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001605 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001606 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001607}
1608
Richard Smith911e1422012-01-30 22:27:01 +00001609static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1610 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001611 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001612 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001613 APSInt Result = Value;
1614 // Figure out if this is a truncate, extend or noop cast.
1615 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001616 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001617 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001618 return Result;
1619}
1620
Richard Smith357362d2011-12-13 06:39:58 +00001621static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1622 QualType SrcType, const APSInt &Value,
1623 QualType DestType, APFloat &Result) {
1624 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1625 if (Result.convertFromAPInt(Value, Value.isSigned(),
1626 APFloat::rmNearestTiesToEven)
1627 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001628 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001629 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001630}
1631
Richard Smith49ca8aa2013-08-06 07:09:20 +00001632static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1633 APValue &Value, const FieldDecl *FD) {
1634 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1635
1636 if (!Value.isInt()) {
1637 // Trying to store a pointer-cast-to-integer into a bitfield.
1638 // FIXME: In this case, we should provide the diagnostic for casting
1639 // a pointer to an integer.
1640 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1641 Info.Diag(E);
1642 return false;
1643 }
1644
1645 APSInt &Int = Value.getInt();
1646 unsigned OldBitWidth = Int.getBitWidth();
1647 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1648 if (NewBitWidth < OldBitWidth)
1649 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1650 return true;
1651}
1652
Eli Friedman803acb32011-12-22 03:51:45 +00001653static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1654 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001655 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001656 if (!Evaluate(SVal, Info, E))
1657 return false;
1658 if (SVal.isInt()) {
1659 Res = SVal.getInt();
1660 return true;
1661 }
1662 if (SVal.isFloat()) {
1663 Res = SVal.getFloat().bitcastToAPInt();
1664 return true;
1665 }
1666 if (SVal.isVector()) {
1667 QualType VecTy = E->getType();
1668 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1669 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1670 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1671 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1672 Res = llvm::APInt::getNullValue(VecSize);
1673 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1674 APValue &Elt = SVal.getVectorElt(i);
1675 llvm::APInt EltAsInt;
1676 if (Elt.isInt()) {
1677 EltAsInt = Elt.getInt();
1678 } else if (Elt.isFloat()) {
1679 EltAsInt = Elt.getFloat().bitcastToAPInt();
1680 } else {
1681 // Don't try to handle vectors of anything other than int or float
1682 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001683 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001684 return false;
1685 }
1686 unsigned BaseEltSize = EltAsInt.getBitWidth();
1687 if (BigEndian)
1688 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1689 else
1690 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1691 }
1692 return true;
1693 }
1694 // Give up if the input isn't an int, float, or vector. For example, we
1695 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001696 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001697 return false;
1698}
1699
Richard Smith43e77732013-05-07 04:50:00 +00001700/// Perform the given integer operation, which is known to need at most BitWidth
1701/// bits, and check for overflow in the original type (if that type was not an
1702/// unsigned type).
1703template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001704static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1705 const APSInt &LHS, const APSInt &RHS,
1706 unsigned BitWidth, Operation Op,
1707 APSInt &Result) {
1708 if (LHS.isUnsigned()) {
1709 Result = Op(LHS, RHS);
1710 return true;
1711 }
Richard Smith43e77732013-05-07 04:50:00 +00001712
1713 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001714 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001715 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001716 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001717 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001718 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001719 << Result.toString(10) << E->getType();
1720 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001721 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001722 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001723 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001724}
1725
1726/// Perform the given binary integer operation.
1727static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1728 BinaryOperatorKind Opcode, APSInt RHS,
1729 APSInt &Result) {
1730 switch (Opcode) {
1731 default:
1732 Info.Diag(E);
1733 return false;
1734 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001735 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1736 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001737 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001738 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1739 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001740 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001741 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1742 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001743 case BO_And: Result = LHS & RHS; return true;
1744 case BO_Xor: Result = LHS ^ RHS; return true;
1745 case BO_Or: Result = LHS | RHS; return true;
1746 case BO_Div:
1747 case BO_Rem:
1748 if (RHS == 0) {
1749 Info.Diag(E, diag::note_expr_divide_by_zero);
1750 return false;
1751 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001752 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1753 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1754 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001755 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1756 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001757 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1758 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001759 return true;
1760 case BO_Shl: {
1761 if (Info.getLangOpts().OpenCL)
1762 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1763 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1764 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1765 RHS.isUnsigned());
1766 else if (RHS.isSigned() && RHS.isNegative()) {
1767 // During constant-folding, a negative shift is an opposite shift. Such
1768 // a shift is not a constant expression.
1769 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1770 RHS = -RHS;
1771 goto shift_right;
1772 }
1773 shift_left:
1774 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1775 // the shifted type.
1776 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1777 if (SA != RHS) {
1778 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1779 << RHS << E->getType() << LHS.getBitWidth();
1780 } else if (LHS.isSigned()) {
1781 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1782 // operand, and must not overflow the corresponding unsigned type.
1783 if (LHS.isNegative())
1784 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1785 else if (LHS.countLeadingZeros() < SA)
1786 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1787 }
1788 Result = LHS << SA;
1789 return true;
1790 }
1791 case BO_Shr: {
1792 if (Info.getLangOpts().OpenCL)
1793 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1794 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1795 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1796 RHS.isUnsigned());
1797 else if (RHS.isSigned() && RHS.isNegative()) {
1798 // During constant-folding, a negative shift is an opposite shift. Such a
1799 // shift is not a constant expression.
1800 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1801 RHS = -RHS;
1802 goto shift_left;
1803 }
1804 shift_right:
1805 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1806 // shifted type.
1807 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1808 if (SA != RHS)
1809 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1810 << RHS << E->getType() << LHS.getBitWidth();
1811 Result = LHS >> SA;
1812 return true;
1813 }
1814
1815 case BO_LT: Result = LHS < RHS; return true;
1816 case BO_GT: Result = LHS > RHS; return true;
1817 case BO_LE: Result = LHS <= RHS; return true;
1818 case BO_GE: Result = LHS >= RHS; return true;
1819 case BO_EQ: Result = LHS == RHS; return true;
1820 case BO_NE: Result = LHS != RHS; return true;
1821 }
1822}
1823
Richard Smith861b5b52013-05-07 23:34:45 +00001824/// Perform the given binary floating-point operation, in-place, on LHS.
1825static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1826 APFloat &LHS, BinaryOperatorKind Opcode,
1827 const APFloat &RHS) {
1828 switch (Opcode) {
1829 default:
1830 Info.Diag(E);
1831 return false;
1832 case BO_Mul:
1833 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1834 break;
1835 case BO_Add:
1836 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1837 break;
1838 case BO_Sub:
1839 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1840 break;
1841 case BO_Div:
1842 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1843 break;
1844 }
1845
Richard Smith0c6124b2015-12-03 01:36:22 +00001846 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001847 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001848 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001849 }
Richard Smith861b5b52013-05-07 23:34:45 +00001850 return true;
1851}
1852
Richard Smitha8105bc2012-01-06 16:39:00 +00001853/// Cast an lvalue referring to a base subobject to a derived class, by
1854/// truncating the lvalue's path to the given length.
1855static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1856 const RecordDecl *TruncatedType,
1857 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001858 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001859
1860 // Check we actually point to a derived class object.
1861 if (TruncatedElements == D.Entries.size())
1862 return true;
1863 assert(TruncatedElements >= D.MostDerivedPathLength &&
1864 "not casting to a derived class");
1865 if (!Result.checkSubobject(Info, E, CSK_Derived))
1866 return false;
1867
1868 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001869 const RecordDecl *RD = TruncatedType;
1870 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001871 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001872 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1873 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001874 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001875 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001876 else
Richard Smithd62306a2011-11-10 06:34:14 +00001877 Result.Offset -= Layout.getBaseClassOffset(Base);
1878 RD = Base;
1879 }
Richard Smith027bf112011-11-17 22:56:20 +00001880 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001881 return true;
1882}
1883
John McCalld7bca762012-05-01 00:38:49 +00001884static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001885 const CXXRecordDecl *Derived,
1886 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001887 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001888 if (!RL) {
1889 if (Derived->isInvalidDecl()) return false;
1890 RL = &Info.Ctx.getASTRecordLayout(Derived);
1891 }
1892
Richard Smithd62306a2011-11-10 06:34:14 +00001893 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001894 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001895 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001896}
1897
Richard Smitha8105bc2012-01-06 16:39:00 +00001898static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001899 const CXXRecordDecl *DerivedDecl,
1900 const CXXBaseSpecifier *Base) {
1901 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1902
John McCalld7bca762012-05-01 00:38:49 +00001903 if (!Base->isVirtual())
1904 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001905
Richard Smitha8105bc2012-01-06 16:39:00 +00001906 SubobjectDesignator &D = Obj.Designator;
1907 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001908 return false;
1909
Richard Smitha8105bc2012-01-06 16:39:00 +00001910 // Extract most-derived object and corresponding type.
1911 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1912 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1913 return false;
1914
1915 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001916 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001917 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1918 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001919 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001920 return true;
1921}
1922
Richard Smith84401042013-06-03 05:03:02 +00001923static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1924 QualType Type, LValue &Result) {
1925 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1926 PathE = E->path_end();
1927 PathI != PathE; ++PathI) {
1928 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1929 *PathI))
1930 return false;
1931 Type = (*PathI)->getType();
1932 }
1933 return true;
1934}
1935
Richard Smithd62306a2011-11-10 06:34:14 +00001936/// Update LVal to refer to the given field, which must be a member of the type
1937/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001938static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001939 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001940 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001941 if (!RL) {
1942 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001943 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001944 }
Richard Smithd62306a2011-11-10 06:34:14 +00001945
1946 unsigned I = FD->getFieldIndex();
1947 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001948 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001949 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001950}
1951
Richard Smith1b78b3d2012-01-25 22:15:11 +00001952/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001953static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001954 LValue &LVal,
1955 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001956 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001957 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001958 return false;
1959 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001960}
1961
Richard Smithd62306a2011-11-10 06:34:14 +00001962/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001963static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1964 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001965 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1966 // extension.
1967 if (Type->isVoidType() || Type->isFunctionType()) {
1968 Size = CharUnits::One();
1969 return true;
1970 }
1971
1972 if (!Type->isConstantSizeType()) {
1973 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001974 // FIXME: Better diagnostic.
1975 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001976 return false;
1977 }
1978
1979 Size = Info.Ctx.getTypeSizeInChars(Type);
1980 return true;
1981}
1982
1983/// Update a pointer value to model pointer arithmetic.
1984/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001985/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001986/// \param LVal - The pointer value to be updated.
1987/// \param EltTy - The pointee type represented by LVal.
1988/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001989static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1990 LValue &LVal, QualType EltTy,
1991 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001992 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001993 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001994 return false;
1995
1996 // Compute the new offset in the appropriate width.
1997 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001998 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001999 return true;
2000}
2001
Richard Smith66c96992012-02-18 22:04:06 +00002002/// Update an lvalue to refer to a component of a complex number.
2003/// \param Info - Information about the ongoing evaluation.
2004/// \param LVal - The lvalue to be updated.
2005/// \param EltTy - The complex number's component type.
2006/// \param Imag - False for the real component, true for the imaginary.
2007static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2008 LValue &LVal, QualType EltTy,
2009 bool Imag) {
2010 if (Imag) {
2011 CharUnits SizeOfComponent;
2012 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2013 return false;
2014 LVal.Offset += SizeOfComponent;
2015 }
2016 LVal.addComplex(Info, E, EltTy, Imag);
2017 return true;
2018}
2019
Richard Smith27908702011-10-24 17:54:18 +00002020/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002021///
2022/// \param Info Information about the ongoing evaluation.
2023/// \param E An expression to be used when printing diagnostics.
2024/// \param VD The variable whose initializer should be obtained.
2025/// \param Frame The frame in which the variable was created. Must be null
2026/// if this variable is not local to the evaluation.
2027/// \param Result Filled in with a pointer to the value of the variable.
2028static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2029 const VarDecl *VD, CallStackFrame *Frame,
2030 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002031 // If this is a parameter to an active constexpr function call, perform
2032 // argument substitution.
2033 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002034 // Assume arguments of a potential constant expression are unknown
2035 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002036 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002037 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002038 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002039 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002040 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002041 }
Richard Smith3229b742013-05-05 21:17:10 +00002042 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002043 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002044 }
Richard Smith27908702011-10-24 17:54:18 +00002045
Richard Smithd9f663b2013-04-22 15:31:51 +00002046 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002047 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002048 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002049 if (!Result) {
2050 // Assume variables referenced within a lambda's call operator that were
2051 // not declared within the call operator are captures and during checking
2052 // of a potential constant expression, assume they are unknown constant
2053 // expressions.
2054 assert(isLambdaCallOperator(Frame->Callee) &&
2055 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2056 "missing value for local variable");
2057 if (Info.checkingPotentialConstantExpression())
2058 return false;
2059 // FIXME: implement capture evaluation during constant expr evaluation.
2060 Info.Diag(E->getLocStart(),
2061 diag::note_unimplemented_constexpr_lambda_feature_ast)
2062 << "captures not currently allowed";
2063 return false;
2064 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002065 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002066 }
2067
Richard Smithd0b4dd62011-12-19 06:19:21 +00002068 // Dig out the initializer, and use the declaration which it's attached to.
2069 const Expr *Init = VD->getAnyInitializer(VD);
2070 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002071 // If we're checking a potential constant expression, the variable could be
2072 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002073 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002074 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002075 return false;
2076 }
2077
Richard Smithd62306a2011-11-10 06:34:14 +00002078 // If we're currently evaluating the initializer of this declaration, use that
2079 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002080 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002081 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002082 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002083 }
2084
Richard Smithcecf1842011-11-01 21:06:14 +00002085 // Never evaluate the initializer of a weak variable. We can't be sure that
2086 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002088 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002089 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 }
Richard Smithcecf1842011-11-01 21:06:14 +00002091
Richard Smithd0b4dd62011-12-19 06:19:21 +00002092 // Check that we can fold the initializer. In C++, we will have already done
2093 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002094 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002095 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002096 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002097 Notes.size() + 1) << VD;
2098 Info.Note(VD->getLocation(), diag::note_declared_at);
2099 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002100 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002101 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002102 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002103 Notes.size() + 1) << VD;
2104 Info.Note(VD->getLocation(), diag::note_declared_at);
2105 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002106 }
Richard Smith27908702011-10-24 17:54:18 +00002107
Richard Smith3229b742013-05-05 21:17:10 +00002108 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002109 return true;
Richard Smith27908702011-10-24 17:54:18 +00002110}
2111
Richard Smith11562c52011-10-28 17:51:58 +00002112static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002113 Qualifiers Quals = T.getQualifiers();
2114 return Quals.hasConst() && !Quals.hasVolatile();
2115}
2116
Richard Smithe97cbd72011-11-11 04:05:33 +00002117/// Get the base index of the given base class within an APValue representing
2118/// the given derived class.
2119static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2120 const CXXRecordDecl *Base) {
2121 Base = Base->getCanonicalDecl();
2122 unsigned Index = 0;
2123 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2124 E = Derived->bases_end(); I != E; ++I, ++Index) {
2125 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2126 return Index;
2127 }
2128
2129 llvm_unreachable("base class missing from derived class's bases list");
2130}
2131
Richard Smith3da88fa2013-04-26 14:36:30 +00002132/// Extract the value of a character from a string literal.
2133static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2134 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002135 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2136 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2137 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002138 const StringLiteral *S = cast<StringLiteral>(Lit);
2139 const ConstantArrayType *CAT =
2140 Info.Ctx.getAsConstantArrayType(S->getType());
2141 assert(CAT && "string literal isn't an array");
2142 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002143 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002144
2145 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002146 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002147 if (Index < S->getLength())
2148 Value = S->getCodeUnit(Index);
2149 return Value;
2150}
2151
Richard Smith3da88fa2013-04-26 14:36:30 +00002152// Expand a string literal into an array of characters.
2153static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2154 APValue &Result) {
2155 const StringLiteral *S = cast<StringLiteral>(Lit);
2156 const ConstantArrayType *CAT =
2157 Info.Ctx.getAsConstantArrayType(S->getType());
2158 assert(CAT && "string literal isn't an array");
2159 QualType CharType = CAT->getElementType();
2160 assert(CharType->isIntegerType() && "unexpected character type");
2161
2162 unsigned Elts = CAT->getSize().getZExtValue();
2163 Result = APValue(APValue::UninitArray(),
2164 std::min(S->getLength(), Elts), Elts);
2165 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2166 CharType->isUnsignedIntegerType());
2167 if (Result.hasArrayFiller())
2168 Result.getArrayFiller() = APValue(Value);
2169 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2170 Value = S->getCodeUnit(I);
2171 Result.getArrayInitializedElt(I) = APValue(Value);
2172 }
2173}
2174
2175// Expand an array so that it has more than Index filled elements.
2176static void expandArray(APValue &Array, unsigned Index) {
2177 unsigned Size = Array.getArraySize();
2178 assert(Index < Size);
2179
2180 // Always at least double the number of elements for which we store a value.
2181 unsigned OldElts = Array.getArrayInitializedElts();
2182 unsigned NewElts = std::max(Index+1, OldElts * 2);
2183 NewElts = std::min(Size, std::max(NewElts, 8u));
2184
2185 // Copy the data across.
2186 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2187 for (unsigned I = 0; I != OldElts; ++I)
2188 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2189 for (unsigned I = OldElts; I != NewElts; ++I)
2190 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2191 if (NewValue.hasArrayFiller())
2192 NewValue.getArrayFiller() = Array.getArrayFiller();
2193 Array.swap(NewValue);
2194}
2195
Richard Smithb01fe402014-09-16 01:24:02 +00002196/// Determine whether a type would actually be read by an lvalue-to-rvalue
2197/// conversion. If it's of class type, we may assume that the copy operation
2198/// is trivial. Note that this is never true for a union type with fields
2199/// (because the copy always "reads" the active member) and always true for
2200/// a non-class type.
2201static bool isReadByLvalueToRvalueConversion(QualType T) {
2202 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2203 if (!RD || (RD->isUnion() && !RD->field_empty()))
2204 return true;
2205 if (RD->isEmpty())
2206 return false;
2207
2208 for (auto *Field : RD->fields())
2209 if (isReadByLvalueToRvalueConversion(Field->getType()))
2210 return true;
2211
2212 for (auto &BaseSpec : RD->bases())
2213 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2214 return true;
2215
2216 return false;
2217}
2218
2219/// Diagnose an attempt to read from any unreadable field within the specified
2220/// type, which might be a class type.
2221static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2222 QualType T) {
2223 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2224 if (!RD)
2225 return false;
2226
2227 if (!RD->hasMutableFields())
2228 return false;
2229
2230 for (auto *Field : RD->fields()) {
2231 // If we're actually going to read this field in some way, then it can't
2232 // be mutable. If we're in a union, then assigning to a mutable field
2233 // (even an empty one) can change the active member, so that's not OK.
2234 // FIXME: Add core issue number for the union case.
2235 if (Field->isMutable() &&
2236 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2237 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2238 Info.Note(Field->getLocation(), diag::note_declared_at);
2239 return true;
2240 }
2241
2242 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2243 return true;
2244 }
2245
2246 for (auto &BaseSpec : RD->bases())
2247 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2248 return true;
2249
2250 // All mutable fields were empty, and thus not actually read.
2251 return false;
2252}
2253
Richard Smith861b5b52013-05-07 23:34:45 +00002254/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002255enum AccessKinds {
2256 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002257 AK_Assign,
2258 AK_Increment,
2259 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002260};
2261
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002262namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002263/// A handle to a complete object (an object that is not a subobject of
2264/// another object).
2265struct CompleteObject {
2266 /// The value of the complete object.
2267 APValue *Value;
2268 /// The type of the complete object.
2269 QualType Type;
2270
Craig Topper36250ad2014-05-12 05:36:57 +00002271 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002272 CompleteObject(APValue *Value, QualType Type)
2273 : Value(Value), Type(Type) {
2274 assert(Value && "missing value for complete object");
2275 }
2276
Aaron Ballman67347662015-02-15 22:00:28 +00002277 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002278};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002279} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002280
Richard Smith3da88fa2013-04-26 14:36:30 +00002281/// Find the designated sub-object of an rvalue.
2282template<typename SubobjectHandler>
2283typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002284findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002285 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002286 if (Sub.Invalid)
2287 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002288 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002289 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002290 if (Info.getLangOpts().CPlusPlus11)
2291 Info.Diag(E, diag::note_constexpr_access_past_end)
2292 << handler.AccessKind;
2293 else
2294 Info.Diag(E);
2295 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002296 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002297
Richard Smith3229b742013-05-05 21:17:10 +00002298 APValue *O = Obj.Value;
2299 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002300 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002301
Richard Smithd62306a2011-11-10 06:34:14 +00002302 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002303 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2304 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002305 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002306 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2307 return handler.failed();
2308 }
2309
Richard Smith49ca8aa2013-08-06 07:09:20 +00002310 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002311 // If we are reading an object of class type, there may still be more
2312 // things we need to check: if there are any mutable subobjects, we
2313 // cannot perform this read. (This only happens when performing a trivial
2314 // copy or assignment.)
2315 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2316 diagnoseUnreadableFields(Info, E, ObjType))
2317 return handler.failed();
2318
Richard Smith49ca8aa2013-08-06 07:09:20 +00002319 if (!handler.found(*O, ObjType))
2320 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002321
Richard Smith49ca8aa2013-08-06 07:09:20 +00002322 // If we modified a bit-field, truncate it to the right width.
2323 if (handler.AccessKind != AK_Read &&
2324 LastField && LastField->isBitField() &&
2325 !truncateBitfieldValue(Info, E, *O, LastField))
2326 return false;
2327
2328 return true;
2329 }
2330
Craig Topper36250ad2014-05-12 05:36:57 +00002331 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002332 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002333 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002334 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002335 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002336 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002337 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002338 // Note, it should not be possible to form a pointer with a valid
2339 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002340 if (Info.getLangOpts().CPlusPlus11)
2341 Info.Diag(E, diag::note_constexpr_access_past_end)
2342 << handler.AccessKind;
2343 else
2344 Info.Diag(E);
2345 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002346 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002347
2348 ObjType = CAT->getElementType();
2349
Richard Smith14a94132012-02-17 03:35:37 +00002350 // An array object is represented as either an Array APValue or as an
2351 // LValue which refers to a string literal.
2352 if (O->isLValue()) {
2353 assert(I == N - 1 && "extracting subobject of character?");
2354 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002355 if (handler.AccessKind != AK_Read)
2356 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2357 *O);
2358 else
2359 return handler.foundString(*O, ObjType, Index);
2360 }
2361
2362 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002363 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002364 else if (handler.AccessKind != AK_Read) {
2365 expandArray(*O, Index);
2366 O = &O->getArrayInitializedElt(Index);
2367 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002368 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002369 } else if (ObjType->isAnyComplexType()) {
2370 // Next subobject is a complex number.
2371 uint64_t Index = Sub.Entries[I].ArrayIndex;
2372 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002373 if (Info.getLangOpts().CPlusPlus11)
2374 Info.Diag(E, diag::note_constexpr_access_past_end)
2375 << handler.AccessKind;
2376 else
2377 Info.Diag(E);
2378 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002379 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002380
2381 bool WasConstQualified = ObjType.isConstQualified();
2382 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2383 if (WasConstQualified)
2384 ObjType.addConst();
2385
Richard Smith66c96992012-02-18 22:04:06 +00002386 assert(I == N - 1 && "extracting subobject of scalar?");
2387 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002388 return handler.found(Index ? O->getComplexIntImag()
2389 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002390 } else {
2391 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002392 return handler.found(Index ? O->getComplexFloatImag()
2393 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002394 }
Richard Smithd62306a2011-11-10 06:34:14 +00002395 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002396 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002397 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002398 << Field;
2399 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002400 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002401 }
2402
Richard Smithd62306a2011-11-10 06:34:14 +00002403 // Next subobject is a class, struct or union field.
2404 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2405 if (RD->isUnion()) {
2406 const FieldDecl *UnionField = O->getUnionField();
2407 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002408 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002409 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2410 << handler.AccessKind << Field << !UnionField << UnionField;
2411 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002412 }
Richard Smithd62306a2011-11-10 06:34:14 +00002413 O = &O->getUnionValue();
2414 } else
2415 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002416
2417 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002418 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002419 if (WasConstQualified && !Field->isMutable())
2420 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002421
2422 if (ObjType.isVolatileQualified()) {
2423 if (Info.getLangOpts().CPlusPlus) {
2424 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002425 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2426 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002427 Info.Note(Field->getLocation(), diag::note_declared_at);
2428 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002429 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002430 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002431 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002432 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002433
2434 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002435 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002436 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002437 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2438 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2439 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002440
2441 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002442 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002443 if (WasConstQualified)
2444 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002445 }
2446 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002447}
2448
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002449namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002450struct ExtractSubobjectHandler {
2451 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002452 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002453
2454 static const AccessKinds AccessKind = AK_Read;
2455
2456 typedef bool result_type;
2457 bool failed() { return false; }
2458 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002459 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002460 return true;
2461 }
2462 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002463 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002464 return true;
2465 }
2466 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002467 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002468 return true;
2469 }
2470 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002471 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002472 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2473 return true;
2474 }
2475};
Richard Smith3229b742013-05-05 21:17:10 +00002476} // end anonymous namespace
2477
Richard Smith3da88fa2013-04-26 14:36:30 +00002478const AccessKinds ExtractSubobjectHandler::AccessKind;
2479
2480/// Extract the designated sub-object of an rvalue.
2481static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002482 const CompleteObject &Obj,
2483 const SubobjectDesignator &Sub,
2484 APValue &Result) {
2485 ExtractSubobjectHandler Handler = { Info, Result };
2486 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002487}
2488
Richard Smith3229b742013-05-05 21:17:10 +00002489namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002490struct ModifySubobjectHandler {
2491 EvalInfo &Info;
2492 APValue &NewVal;
2493 const Expr *E;
2494
2495 typedef bool result_type;
2496 static const AccessKinds AccessKind = AK_Assign;
2497
2498 bool checkConst(QualType QT) {
2499 // Assigning to a const object has undefined behavior.
2500 if (QT.isConstQualified()) {
2501 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2502 return false;
2503 }
2504 return true;
2505 }
2506
2507 bool failed() { return false; }
2508 bool found(APValue &Subobj, QualType SubobjType) {
2509 if (!checkConst(SubobjType))
2510 return false;
2511 // We've been given ownership of NewVal, so just swap it in.
2512 Subobj.swap(NewVal);
2513 return true;
2514 }
2515 bool found(APSInt &Value, QualType SubobjType) {
2516 if (!checkConst(SubobjType))
2517 return false;
2518 if (!NewVal.isInt()) {
2519 // Maybe trying to write a cast pointer value into a complex?
2520 Info.Diag(E);
2521 return false;
2522 }
2523 Value = NewVal.getInt();
2524 return true;
2525 }
2526 bool found(APFloat &Value, QualType SubobjType) {
2527 if (!checkConst(SubobjType))
2528 return false;
2529 Value = NewVal.getFloat();
2530 return true;
2531 }
2532 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2533 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2534 }
2535};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002536} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002537
Richard Smith3229b742013-05-05 21:17:10 +00002538const AccessKinds ModifySubobjectHandler::AccessKind;
2539
Richard Smith3da88fa2013-04-26 14:36:30 +00002540/// Update the designated sub-object of an rvalue to the given value.
2541static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002542 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002543 const SubobjectDesignator &Sub,
2544 APValue &NewVal) {
2545 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002546 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002547}
2548
Richard Smith84f6dcf2012-02-02 01:16:57 +00002549/// Find the position where two subobject designators diverge, or equivalently
2550/// the length of the common initial subsequence.
2551static unsigned FindDesignatorMismatch(QualType ObjType,
2552 const SubobjectDesignator &A,
2553 const SubobjectDesignator &B,
2554 bool &WasArrayIndex) {
2555 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2556 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002557 if (!ObjType.isNull() &&
2558 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002559 // Next subobject is an array element.
2560 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2561 WasArrayIndex = true;
2562 return I;
2563 }
Richard Smith66c96992012-02-18 22:04:06 +00002564 if (ObjType->isAnyComplexType())
2565 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2566 else
2567 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002568 } else {
2569 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2570 WasArrayIndex = false;
2571 return I;
2572 }
2573 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2574 // Next subobject is a field.
2575 ObjType = FD->getType();
2576 else
2577 // Next subobject is a base class.
2578 ObjType = QualType();
2579 }
2580 }
2581 WasArrayIndex = false;
2582 return I;
2583}
2584
2585/// Determine whether the given subobject designators refer to elements of the
2586/// same array object.
2587static bool AreElementsOfSameArray(QualType ObjType,
2588 const SubobjectDesignator &A,
2589 const SubobjectDesignator &B) {
2590 if (A.Entries.size() != B.Entries.size())
2591 return false;
2592
George Burgess IVa51c4072015-10-16 01:49:01 +00002593 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002594 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2595 // A is a subobject of the array element.
2596 return false;
2597
2598 // If A (and B) designates an array element, the last entry will be the array
2599 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2600 // of length 1' case, and the entire path must match.
2601 bool WasArrayIndex;
2602 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2603 return CommonLength >= A.Entries.size() - IsArray;
2604}
2605
Richard Smith3229b742013-05-05 21:17:10 +00002606/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002607static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2608 AccessKinds AK, const LValue &LVal,
2609 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002610 if (!LVal.Base) {
2611 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2612 return CompleteObject();
2613 }
2614
Craig Topper36250ad2014-05-12 05:36:57 +00002615 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002616 if (LVal.CallIndex) {
2617 Frame = Info.getCallFrame(LVal.CallIndex);
2618 if (!Frame) {
2619 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2620 << AK << LVal.Base.is<const ValueDecl*>();
2621 NoteLValueLocation(Info, LVal.Base);
2622 return CompleteObject();
2623 }
Richard Smith3229b742013-05-05 21:17:10 +00002624 }
2625
2626 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2627 // is not a constant expression (even if the object is non-volatile). We also
2628 // apply this rule to C++98, in order to conform to the expected 'volatile'
2629 // semantics.
2630 if (LValType.isVolatileQualified()) {
2631 if (Info.getLangOpts().CPlusPlus)
2632 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2633 << AK << LValType;
2634 else
2635 Info.Diag(E);
2636 return CompleteObject();
2637 }
2638
2639 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002640 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002641 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002642
2643 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2644 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2645 // In C++11, constexpr, non-volatile variables initialized with constant
2646 // expressions are constant expressions too. Inside constexpr functions,
2647 // parameters are constant expressions even if they're non-const.
2648 // In C++1y, objects local to a constant expression (those with a Frame) are
2649 // both readable and writable inside constant expressions.
2650 // In C, such things can also be folded, although they are not ICEs.
2651 const VarDecl *VD = dyn_cast<VarDecl>(D);
2652 if (VD) {
2653 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2654 VD = VDef;
2655 }
2656 if (!VD || VD->isInvalidDecl()) {
2657 Info.Diag(E);
2658 return CompleteObject();
2659 }
2660
2661 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002662 if (BaseType.isVolatileQualified()) {
2663 if (Info.getLangOpts().CPlusPlus) {
2664 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2665 << AK << 1 << VD;
2666 Info.Note(VD->getLocation(), diag::note_declared_at);
2667 } else {
2668 Info.Diag(E);
2669 }
2670 return CompleteObject();
2671 }
2672
2673 // Unless we're looking at a local variable or argument in a constexpr call,
2674 // the variable we're reading must be const.
2675 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002676 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002677 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2678 // OK, we can read and modify an object if we're in the process of
2679 // evaluating its initializer, because its lifetime began in this
2680 // evaluation.
2681 } else if (AK != AK_Read) {
2682 // All the remaining cases only permit reading.
2683 Info.Diag(E, diag::note_constexpr_modify_global);
2684 return CompleteObject();
2685 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002686 // OK, we can read this variable.
2687 } else if (BaseType->isIntegralOrEnumerationType()) {
2688 if (!BaseType.isConstQualified()) {
2689 if (Info.getLangOpts().CPlusPlus) {
2690 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2691 Info.Note(VD->getLocation(), diag::note_declared_at);
2692 } else {
2693 Info.Diag(E);
2694 }
2695 return CompleteObject();
2696 }
2697 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2698 // We support folding of const floating-point types, in order to make
2699 // static const data members of such types (supported as an extension)
2700 // more useful.
2701 if (Info.getLangOpts().CPlusPlus11) {
2702 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2703 Info.Note(VD->getLocation(), diag::note_declared_at);
2704 } else {
2705 Info.CCEDiag(E);
2706 }
2707 } else {
2708 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002709 if (Info.checkingPotentialConstantExpression() &&
2710 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2711 // The definition of this variable could be constexpr. We can't
2712 // access it right now, but may be able to in future.
2713 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith3229b742013-05-05 21:17:10 +00002714 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2715 Info.Note(VD->getLocation(), diag::note_declared_at);
2716 } else {
2717 Info.Diag(E);
2718 }
2719 return CompleteObject();
2720 }
2721 }
2722
2723 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2724 return CompleteObject();
2725 } else {
2726 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2727
2728 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002729 if (const MaterializeTemporaryExpr *MTE =
2730 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2731 assert(MTE->getStorageDuration() == SD_Static &&
2732 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002733
Richard Smithe6c01442013-06-05 00:46:14 +00002734 // Per C++1y [expr.const]p2:
2735 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2736 // - a [...] glvalue of integral or enumeration type that refers to
2737 // a non-volatile const object [...]
2738 // [...]
2739 // - a [...] glvalue of literal type that refers to a non-volatile
2740 // object whose lifetime began within the evaluation of e.
2741 //
2742 // C++11 misses the 'began within the evaluation of e' check and
2743 // instead allows all temporaries, including things like:
2744 // int &&r = 1;
2745 // int x = ++r;
2746 // constexpr int k = r;
2747 // Therefore we use the C++1y rules in C++11 too.
2748 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2749 const ValueDecl *ED = MTE->getExtendingDecl();
2750 if (!(BaseType.isConstQualified() &&
2751 BaseType->isIntegralOrEnumerationType()) &&
2752 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2753 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2754 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2755 return CompleteObject();
2756 }
2757
2758 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2759 assert(BaseVal && "got reference to unevaluated temporary");
2760 } else {
2761 Info.Diag(E);
2762 return CompleteObject();
2763 }
2764 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002765 BaseVal = Frame->getTemporary(Base);
2766 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002767 }
Richard Smith3229b742013-05-05 21:17:10 +00002768
2769 // Volatile temporary objects cannot be accessed in constant expressions.
2770 if (BaseType.isVolatileQualified()) {
2771 if (Info.getLangOpts().CPlusPlus) {
2772 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2773 << AK << 0;
2774 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2775 } else {
2776 Info.Diag(E);
2777 }
2778 return CompleteObject();
2779 }
2780 }
2781
Richard Smith7525ff62013-05-09 07:14:00 +00002782 // During the construction of an object, it is not yet 'const'.
2783 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2784 // and this doesn't do quite the right thing for const subobjects of the
2785 // object under construction.
2786 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2787 BaseType = Info.Ctx.getCanonicalType(BaseType);
2788 BaseType.removeLocalConst();
2789 }
2790
Richard Smith6d4c6582013-11-05 22:18:15 +00002791 // In C++1y, we can't safely access any mutable state when we might be
2792 // evaluating after an unmodeled side effect or an evaluation failure.
2793 //
2794 // FIXME: Not all local state is mutable. Allow local constant subobjects
2795 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002796 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002797 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002798 return CompleteObject();
2799
2800 return CompleteObject(BaseVal, BaseType);
2801}
2802
Richard Smith243ef902013-05-05 23:31:59 +00002803/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2804/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2805/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002806///
2807/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002808/// \param Conv - The expression for which we are performing the conversion.
2809/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002810/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2811/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002812/// \param LVal - The glvalue on which we are attempting to perform this action.
2813/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002814static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002815 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002816 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002817 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002818 return false;
2819
Richard Smith3229b742013-05-05 21:17:10 +00002820 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002821 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002822 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002823 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2824 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2825 // initializer until now for such expressions. Such an expression can't be
2826 // an ICE in C, so this only matters for fold.
2827 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2828 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002829 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002830 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002831 }
Richard Smith3229b742013-05-05 21:17:10 +00002832 APValue Lit;
2833 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2834 return false;
2835 CompleteObject LitObj(&Lit, Base->getType());
2836 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002837 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002838 // We represent a string literal array as an lvalue pointing at the
2839 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002840 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002841 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2842 CompleteObject StrObj(&Str, Base->getType());
2843 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002844 }
Richard Smith11562c52011-10-28 17:51:58 +00002845 }
2846
Richard Smith3229b742013-05-05 21:17:10 +00002847 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2848 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002849}
2850
2851/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002852static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002853 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002854 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002855 return false;
2856
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002857 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002858 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002859 return false;
2860 }
2861
Richard Smith3229b742013-05-05 21:17:10 +00002862 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2863 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002864}
2865
Richard Smith243ef902013-05-05 23:31:59 +00002866static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2867 return T->isSignedIntegerType() &&
2868 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2869}
2870
2871namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002872struct CompoundAssignSubobjectHandler {
2873 EvalInfo &Info;
2874 const Expr *E;
2875 QualType PromotedLHSType;
2876 BinaryOperatorKind Opcode;
2877 const APValue &RHS;
2878
2879 static const AccessKinds AccessKind = AK_Assign;
2880
2881 typedef bool result_type;
2882
2883 bool checkConst(QualType QT) {
2884 // Assigning to a const object has undefined behavior.
2885 if (QT.isConstQualified()) {
2886 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2887 return false;
2888 }
2889 return true;
2890 }
2891
2892 bool failed() { return false; }
2893 bool found(APValue &Subobj, QualType SubobjType) {
2894 switch (Subobj.getKind()) {
2895 case APValue::Int:
2896 return found(Subobj.getInt(), SubobjType);
2897 case APValue::Float:
2898 return found(Subobj.getFloat(), SubobjType);
2899 case APValue::ComplexInt:
2900 case APValue::ComplexFloat:
2901 // FIXME: Implement complex compound assignment.
2902 Info.Diag(E);
2903 return false;
2904 case APValue::LValue:
2905 return foundPointer(Subobj, SubobjType);
2906 default:
2907 // FIXME: can this happen?
2908 Info.Diag(E);
2909 return false;
2910 }
2911 }
2912 bool found(APSInt &Value, QualType SubobjType) {
2913 if (!checkConst(SubobjType))
2914 return false;
2915
2916 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2917 // We don't support compound assignment on integer-cast-to-pointer
2918 // values.
2919 Info.Diag(E);
2920 return false;
2921 }
2922
2923 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2924 SubobjType, Value);
2925 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2926 return false;
2927 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2928 return true;
2929 }
2930 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002931 return checkConst(SubobjType) &&
2932 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2933 Value) &&
2934 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2935 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002936 }
2937 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2938 if (!checkConst(SubobjType))
2939 return false;
2940
2941 QualType PointeeType;
2942 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2943 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002944
2945 if (PointeeType.isNull() || !RHS.isInt() ||
2946 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002947 Info.Diag(E);
2948 return false;
2949 }
2950
Richard Smith861b5b52013-05-07 23:34:45 +00002951 int64_t Offset = getExtValue(RHS.getInt());
2952 if (Opcode == BO_Sub)
2953 Offset = -Offset;
2954
2955 LValue LVal;
2956 LVal.setFrom(Info.Ctx, Subobj);
2957 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2958 return false;
2959 LVal.moveInto(Subobj);
2960 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002961 }
2962 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2963 llvm_unreachable("shouldn't encounter string elements here");
2964 }
2965};
2966} // end anonymous namespace
2967
2968const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2969
2970/// Perform a compound assignment of LVal <op>= RVal.
2971static bool handleCompoundAssignment(
2972 EvalInfo &Info, const Expr *E,
2973 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2974 BinaryOperatorKind Opcode, const APValue &RVal) {
2975 if (LVal.Designator.Invalid)
2976 return false;
2977
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002978 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002979 Info.Diag(E);
2980 return false;
2981 }
2982
2983 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2984 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2985 RVal };
2986 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2987}
2988
2989namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002990struct IncDecSubobjectHandler {
2991 EvalInfo &Info;
2992 const Expr *E;
2993 AccessKinds AccessKind;
2994 APValue *Old;
2995
2996 typedef bool result_type;
2997
2998 bool checkConst(QualType QT) {
2999 // Assigning to a const object has undefined behavior.
3000 if (QT.isConstQualified()) {
3001 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
3002 return false;
3003 }
3004 return true;
3005 }
3006
3007 bool failed() { return false; }
3008 bool found(APValue &Subobj, QualType SubobjType) {
3009 // Stash the old value. Also clear Old, so we don't clobber it later
3010 // if we're post-incrementing a complex.
3011 if (Old) {
3012 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003013 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003014 }
3015
3016 switch (Subobj.getKind()) {
3017 case APValue::Int:
3018 return found(Subobj.getInt(), SubobjType);
3019 case APValue::Float:
3020 return found(Subobj.getFloat(), SubobjType);
3021 case APValue::ComplexInt:
3022 return found(Subobj.getComplexIntReal(),
3023 SubobjType->castAs<ComplexType>()->getElementType()
3024 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3025 case APValue::ComplexFloat:
3026 return found(Subobj.getComplexFloatReal(),
3027 SubobjType->castAs<ComplexType>()->getElementType()
3028 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3029 case APValue::LValue:
3030 return foundPointer(Subobj, SubobjType);
3031 default:
3032 // FIXME: can this happen?
3033 Info.Diag(E);
3034 return false;
3035 }
3036 }
3037 bool found(APSInt &Value, QualType SubobjType) {
3038 if (!checkConst(SubobjType))
3039 return false;
3040
3041 if (!SubobjType->isIntegerType()) {
3042 // We don't support increment / decrement on integer-cast-to-pointer
3043 // values.
3044 Info.Diag(E);
3045 return false;
3046 }
3047
3048 if (Old) *Old = APValue(Value);
3049
3050 // bool arithmetic promotes to int, and the conversion back to bool
3051 // doesn't reduce mod 2^n, so special-case it.
3052 if (SubobjType->isBooleanType()) {
3053 if (AccessKind == AK_Increment)
3054 Value = 1;
3055 else
3056 Value = !Value;
3057 return true;
3058 }
3059
3060 bool WasNegative = Value.isNegative();
3061 if (AccessKind == AK_Increment) {
3062 ++Value;
3063
3064 if (!WasNegative && Value.isNegative() &&
3065 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3066 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003067 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003068 }
3069 } else {
3070 --Value;
3071
3072 if (WasNegative && !Value.isNegative() &&
3073 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3074 unsigned BitWidth = Value.getBitWidth();
3075 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3076 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003077 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003078 }
3079 }
3080 return true;
3081 }
3082 bool found(APFloat &Value, QualType SubobjType) {
3083 if (!checkConst(SubobjType))
3084 return false;
3085
3086 if (Old) *Old = APValue(Value);
3087
3088 APFloat One(Value.getSemantics(), 1);
3089 if (AccessKind == AK_Increment)
3090 Value.add(One, APFloat::rmNearestTiesToEven);
3091 else
3092 Value.subtract(One, APFloat::rmNearestTiesToEven);
3093 return true;
3094 }
3095 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3096 if (!checkConst(SubobjType))
3097 return false;
3098
3099 QualType PointeeType;
3100 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3101 PointeeType = PT->getPointeeType();
3102 else {
3103 Info.Diag(E);
3104 return false;
3105 }
3106
3107 LValue LVal;
3108 LVal.setFrom(Info.Ctx, Subobj);
3109 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3110 AccessKind == AK_Increment ? 1 : -1))
3111 return false;
3112 LVal.moveInto(Subobj);
3113 return true;
3114 }
3115 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3116 llvm_unreachable("shouldn't encounter string elements here");
3117 }
3118};
3119} // end anonymous namespace
3120
3121/// Perform an increment or decrement on LVal.
3122static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3123 QualType LValType, bool IsIncrement, APValue *Old) {
3124 if (LVal.Designator.Invalid)
3125 return false;
3126
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003127 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003128 Info.Diag(E);
3129 return false;
3130 }
3131
3132 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3133 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3134 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3135 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3136}
3137
Richard Smithe97cbd72011-11-11 04:05:33 +00003138/// Build an lvalue for the object argument of a member function call.
3139static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3140 LValue &This) {
3141 if (Object->getType()->isPointerType())
3142 return EvaluatePointer(Object, This, Info);
3143
3144 if (Object->isGLValue())
3145 return EvaluateLValue(Object, This, Info);
3146
Richard Smithd9f663b2013-04-22 15:31:51 +00003147 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003148 return EvaluateTemporary(Object, This, Info);
3149
Richard Smith3e79a572014-06-11 19:53:12 +00003150 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003151 return false;
3152}
3153
3154/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3155/// lvalue referring to the result.
3156///
3157/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003158/// \param LV - An lvalue referring to the base of the member pointer.
3159/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003160/// \param IncludeMember - Specifies whether the member itself is included in
3161/// the resulting LValue subobject designator. This is not possible when
3162/// creating a bound member function.
3163/// \return The field or method declaration to which the member pointer refers,
3164/// or 0 if evaluation fails.
3165static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003166 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003167 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003168 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003169 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003170 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003171 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003172 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003173
3174 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3175 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003176 if (!MemPtr.getDecl()) {
3177 // FIXME: Specific diagnostic.
3178 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003179 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003180 }
Richard Smith253c2a32012-01-27 01:14:48 +00003181
Richard Smith027bf112011-11-17 22:56:20 +00003182 if (MemPtr.isDerivedMember()) {
3183 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003184 // The end of the derived-to-base path for the base object must match the
3185 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003186 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003187 LV.Designator.Entries.size()) {
3188 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003189 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003190 }
Richard Smith027bf112011-11-17 22:56:20 +00003191 unsigned PathLengthToMember =
3192 LV.Designator.Entries.size() - MemPtr.Path.size();
3193 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3194 const CXXRecordDecl *LVDecl = getAsBaseClass(
3195 LV.Designator.Entries[PathLengthToMember + I]);
3196 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003197 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3198 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003199 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003200 }
Richard Smith027bf112011-11-17 22:56:20 +00003201 }
3202
3203 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003204 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003205 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003206 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003207 } else if (!MemPtr.Path.empty()) {
3208 // Extend the LValue path with the member pointer's path.
3209 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3210 MemPtr.Path.size() + IncludeMember);
3211
3212 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003213 if (const PointerType *PT = LVType->getAs<PointerType>())
3214 LVType = PT->getPointeeType();
3215 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3216 assert(RD && "member pointer access on non-class-type expression");
3217 // The first class in the path is that of the lvalue.
3218 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3219 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003220 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003221 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003222 RD = Base;
3223 }
3224 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003225 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3226 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003227 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003228 }
3229
3230 // Add the member. Note that we cannot build bound member functions here.
3231 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003232 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003233 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003234 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003235 } else if (const IndirectFieldDecl *IFD =
3236 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003237 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003238 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003239 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003240 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003241 }
Richard Smith027bf112011-11-17 22:56:20 +00003242 }
3243
3244 return MemPtr.getDecl();
3245}
3246
Richard Smith84401042013-06-03 05:03:02 +00003247static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3248 const BinaryOperator *BO,
3249 LValue &LV,
3250 bool IncludeMember = true) {
3251 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3252
3253 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3254 if (Info.keepEvaluatingAfterFailure()) {
3255 MemberPtr MemPtr;
3256 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3257 }
Craig Topper36250ad2014-05-12 05:36:57 +00003258 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003259 }
3260
3261 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3262 BO->getRHS(), IncludeMember);
3263}
3264
Richard Smith027bf112011-11-17 22:56:20 +00003265/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3266/// the provided lvalue, which currently refers to the base object.
3267static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3268 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003269 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003270 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003271 return false;
3272
Richard Smitha8105bc2012-01-06 16:39:00 +00003273 QualType TargetQT = E->getType();
3274 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3275 TargetQT = PT->getPointeeType();
3276
3277 // Check this cast lands within the final derived-to-base subobject path.
3278 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003279 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003280 << D.MostDerivedType << TargetQT;
3281 return false;
3282 }
3283
Richard Smith027bf112011-11-17 22:56:20 +00003284 // Check the type of the final cast. We don't need to check the path,
3285 // since a cast can only be formed if the path is unique.
3286 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003287 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3288 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003289 if (NewEntriesSize == D.MostDerivedPathLength)
3290 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3291 else
Richard Smith027bf112011-11-17 22:56:20 +00003292 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003293 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003294 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003295 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003296 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003297 }
Richard Smith027bf112011-11-17 22:56:20 +00003298
3299 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003300 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003301}
3302
Mike Stump876387b2009-10-27 22:09:17 +00003303namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003304enum EvalStmtResult {
3305 /// Evaluation failed.
3306 ESR_Failed,
3307 /// Hit a 'return' statement.
3308 ESR_Returned,
3309 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003310 ESR_Succeeded,
3311 /// Hit a 'continue' statement.
3312 ESR_Continue,
3313 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003314 ESR_Break,
3315 /// Still scanning for 'case' or 'default' statement.
3316 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003317};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003318}
Richard Smith254a73d2011-10-28 22:34:42 +00003319
Richard Smithd9f663b2013-04-22 15:31:51 +00003320static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3321 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3322 // We don't need to evaluate the initializer for a static local.
3323 if (!VD->hasLocalStorage())
3324 return true;
3325
3326 LValue Result;
3327 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003328 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003329
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003330 const Expr *InitE = VD->getInit();
3331 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003332 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3333 << false << VD->getType();
3334 Val = APValue();
3335 return false;
3336 }
3337
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003338 if (InitE->isValueDependent())
3339 return false;
3340
3341 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003342 // Wipe out any partially-computed value, to allow tracking that this
3343 // evaluation failed.
3344 Val = APValue();
3345 return false;
3346 }
3347 }
3348
3349 return true;
3350}
3351
Richard Smith4e18ca52013-05-06 05:56:11 +00003352/// Evaluate a condition (either a variable declaration or an expression).
3353static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3354 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003355 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003356 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3357 return false;
3358 return EvaluateAsBooleanCondition(Cond, Result, Info);
3359}
3360
Richard Smith89210072016-04-04 23:29:43 +00003361namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003362/// \brief A location where the result (returned value) of evaluating a
3363/// statement should be stored.
3364struct StmtResult {
3365 /// The APValue that should be filled in with the returned value.
3366 APValue &Value;
3367 /// The location containing the result, if any (used to support RVO).
3368 const LValue *Slot;
3369};
Richard Smith89210072016-04-04 23:29:43 +00003370}
Richard Smith52a980a2015-08-28 02:43:42 +00003371
3372static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003373 const Stmt *S,
3374 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003375
3376/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003377static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003378 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003379 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003380 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003381 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003382 case ESR_Break:
3383 return ESR_Succeeded;
3384 case ESR_Succeeded:
3385 case ESR_Continue:
3386 return ESR_Continue;
3387 case ESR_Failed:
3388 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003389 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003390 return ESR;
3391 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003392 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003393}
3394
Richard Smith496ddcf2013-05-12 17:32:42 +00003395/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003396static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003397 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003398 BlockScopeRAII Scope(Info);
3399
Richard Smith496ddcf2013-05-12 17:32:42 +00003400 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003401 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003402 {
3403 FullExpressionRAII Scope(Info);
3404 if (SS->getConditionVariable() &&
3405 !EvaluateDecl(Info, SS->getConditionVariable()))
3406 return ESR_Failed;
3407 if (!EvaluateInteger(SS->getCond(), Value, Info))
3408 return ESR_Failed;
3409 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003410
3411 // Find the switch case corresponding to the value of the condition.
3412 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003413 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003414 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3415 SC = SC->getNextSwitchCase()) {
3416 if (isa<DefaultStmt>(SC)) {
3417 Found = SC;
3418 continue;
3419 }
3420
3421 const CaseStmt *CS = cast<CaseStmt>(SC);
3422 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3423 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3424 : LHS;
3425 if (LHS <= Value && Value <= RHS) {
3426 Found = SC;
3427 break;
3428 }
3429 }
3430
3431 if (!Found)
3432 return ESR_Succeeded;
3433
3434 // Search the switch body for the switch case and evaluate it from there.
3435 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3436 case ESR_Break:
3437 return ESR_Succeeded;
3438 case ESR_Succeeded:
3439 case ESR_Continue:
3440 case ESR_Failed:
3441 case ESR_Returned:
3442 return ESR;
3443 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003444 // This can only happen if the switch case is nested within a statement
3445 // expression. We have no intention of supporting that.
3446 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3447 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003448 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003449 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003450}
3451
Richard Smith254a73d2011-10-28 22:34:42 +00003452// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003453static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003454 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003455 if (!Info.nextStep(S))
3456 return ESR_Failed;
3457
Richard Smith496ddcf2013-05-12 17:32:42 +00003458 // If we're hunting down a 'case' or 'default' label, recurse through
3459 // substatements until we hit the label.
3460 if (Case) {
3461 // FIXME: We don't start the lifetime of objects whose initialization we
3462 // jump over. However, such objects must be of class type with a trivial
3463 // default constructor that initialize all subobjects, so must be empty,
3464 // so this almost never matters.
3465 switch (S->getStmtClass()) {
3466 case Stmt::CompoundStmtClass:
3467 // FIXME: Precompute which substatement of a compound statement we
3468 // would jump to, and go straight there rather than performing a
3469 // linear scan each time.
3470 case Stmt::LabelStmtClass:
3471 case Stmt::AttributedStmtClass:
3472 case Stmt::DoStmtClass:
3473 break;
3474
3475 case Stmt::CaseStmtClass:
3476 case Stmt::DefaultStmtClass:
3477 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003478 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003479 break;
3480
3481 case Stmt::IfStmtClass: {
3482 // FIXME: Precompute which side of an 'if' we would jump to, and go
3483 // straight there rather than scanning both sides.
3484 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003485
3486 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3487 // preceded by our switch label.
3488 BlockScopeRAII Scope(Info);
3489
Richard Smith496ddcf2013-05-12 17:32:42 +00003490 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3491 if (ESR != ESR_CaseNotFound || !IS->getElse())
3492 return ESR;
3493 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3494 }
3495
3496 case Stmt::WhileStmtClass: {
3497 EvalStmtResult ESR =
3498 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3499 if (ESR != ESR_Continue)
3500 return ESR;
3501 break;
3502 }
3503
3504 case Stmt::ForStmtClass: {
3505 const ForStmt *FS = cast<ForStmt>(S);
3506 EvalStmtResult ESR =
3507 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3508 if (ESR != ESR_Continue)
3509 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003510 if (FS->getInc()) {
3511 FullExpressionRAII IncScope(Info);
3512 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3513 return ESR_Failed;
3514 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003515 break;
3516 }
3517
3518 case Stmt::DeclStmtClass:
3519 // FIXME: If the variable has initialization that can't be jumped over,
3520 // bail out of any immediately-surrounding compound-statement too.
3521 default:
3522 return ESR_CaseNotFound;
3523 }
3524 }
3525
Richard Smith254a73d2011-10-28 22:34:42 +00003526 switch (S->getStmtClass()) {
3527 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003528 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003529 // Don't bother evaluating beyond an expression-statement which couldn't
3530 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003531 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003532 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003533 return ESR_Failed;
3534 return ESR_Succeeded;
3535 }
3536
3537 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003538 return ESR_Failed;
3539
3540 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003541 return ESR_Succeeded;
3542
Richard Smithd9f663b2013-04-22 15:31:51 +00003543 case Stmt::DeclStmtClass: {
3544 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003545 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003546 // Each declaration initialization is its own full-expression.
3547 // FIXME: This isn't quite right; if we're performing aggregate
3548 // initialization, each braced subexpression is its own full-expression.
3549 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003550 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003551 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003552 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003553 return ESR_Succeeded;
3554 }
3555
Richard Smith357362d2011-12-13 06:39:58 +00003556 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003557 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003558 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003559 if (RetExpr &&
3560 !(Result.Slot
3561 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3562 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003563 return ESR_Failed;
3564 return ESR_Returned;
3565 }
Richard Smith254a73d2011-10-28 22:34:42 +00003566
3567 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003568 BlockScopeRAII Scope(Info);
3569
Richard Smith254a73d2011-10-28 22:34:42 +00003570 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003571 for (const auto *BI : CS->body()) {
3572 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003573 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003574 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003575 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003576 return ESR;
3577 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003578 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003579 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003580
3581 case Stmt::IfStmtClass: {
3582 const IfStmt *IS = cast<IfStmt>(S);
3583
3584 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003585 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003586 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003587 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003588 return ESR_Failed;
3589
3590 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3591 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3592 if (ESR != ESR_Succeeded)
3593 return ESR;
3594 }
3595 return ESR_Succeeded;
3596 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003597
3598 case Stmt::WhileStmtClass: {
3599 const WhileStmt *WS = cast<WhileStmt>(S);
3600 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003601 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003602 bool Continue;
3603 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3604 Continue))
3605 return ESR_Failed;
3606 if (!Continue)
3607 break;
3608
3609 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3610 if (ESR != ESR_Continue)
3611 return ESR;
3612 }
3613 return ESR_Succeeded;
3614 }
3615
3616 case Stmt::DoStmtClass: {
3617 const DoStmt *DS = cast<DoStmt>(S);
3618 bool Continue;
3619 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003620 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003621 if (ESR != ESR_Continue)
3622 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003623 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003624
Richard Smith08d6a2c2013-07-24 07:11:57 +00003625 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003626 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3627 return ESR_Failed;
3628 } while (Continue);
3629 return ESR_Succeeded;
3630 }
3631
3632 case Stmt::ForStmtClass: {
3633 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003634 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003635 if (FS->getInit()) {
3636 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3637 if (ESR != ESR_Succeeded)
3638 return ESR;
3639 }
3640 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003641 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003642 bool Continue = true;
3643 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3644 FS->getCond(), Continue))
3645 return ESR_Failed;
3646 if (!Continue)
3647 break;
3648
3649 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3650 if (ESR != ESR_Continue)
3651 return ESR;
3652
Richard Smith08d6a2c2013-07-24 07:11:57 +00003653 if (FS->getInc()) {
3654 FullExpressionRAII IncScope(Info);
3655 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3656 return ESR_Failed;
3657 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003658 }
3659 return ESR_Succeeded;
3660 }
3661
Richard Smith896e0d72013-05-06 06:51:17 +00003662 case Stmt::CXXForRangeStmtClass: {
3663 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003664 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003665
3666 // Initialize the __range variable.
3667 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3668 if (ESR != ESR_Succeeded)
3669 return ESR;
3670
3671 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003672 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3673 if (ESR != ESR_Succeeded)
3674 return ESR;
3675 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003676 if (ESR != ESR_Succeeded)
3677 return ESR;
3678
3679 while (true) {
3680 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003681 {
3682 bool Continue = true;
3683 FullExpressionRAII CondExpr(Info);
3684 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3685 return ESR_Failed;
3686 if (!Continue)
3687 break;
3688 }
Richard Smith896e0d72013-05-06 06:51:17 +00003689
3690 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003691 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003692 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3693 if (ESR != ESR_Succeeded)
3694 return ESR;
3695
3696 // Loop body.
3697 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3698 if (ESR != ESR_Continue)
3699 return ESR;
3700
3701 // Increment: ++__begin
3702 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3703 return ESR_Failed;
3704 }
3705
3706 return ESR_Succeeded;
3707 }
3708
Richard Smith496ddcf2013-05-12 17:32:42 +00003709 case Stmt::SwitchStmtClass:
3710 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3711
Richard Smith4e18ca52013-05-06 05:56:11 +00003712 case Stmt::ContinueStmtClass:
3713 return ESR_Continue;
3714
3715 case Stmt::BreakStmtClass:
3716 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003717
3718 case Stmt::LabelStmtClass:
3719 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3720
3721 case Stmt::AttributedStmtClass:
3722 // As a general principle, C++11 attributes can be ignored without
3723 // any semantic impact.
3724 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3725 Case);
3726
3727 case Stmt::CaseStmtClass:
3728 case Stmt::DefaultStmtClass:
3729 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003730 }
3731}
3732
Richard Smithcc36f692011-12-22 02:22:31 +00003733/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3734/// default constructor. If so, we'll fold it whether or not it's marked as
3735/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3736/// so we need special handling.
3737static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003738 const CXXConstructorDecl *CD,
3739 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003740 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3741 return false;
3742
Richard Smith66e05fe2012-01-18 05:21:49 +00003743 // Value-initialization does not call a trivial default constructor, so such a
3744 // call is a core constant expression whether or not the constructor is
3745 // constexpr.
3746 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003747 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003748 // FIXME: If DiagDecl is an implicitly-declared special member function,
3749 // we should be much more explicit about why it's not constexpr.
3750 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3751 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3752 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003753 } else {
3754 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3755 }
3756 }
3757 return true;
3758}
3759
Richard Smith357362d2011-12-13 06:39:58 +00003760/// CheckConstexprFunction - Check that a function can be called in a constant
3761/// expression.
3762static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3763 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003764 const FunctionDecl *Definition,
3765 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003766 // Potential constant expressions can contain calls to declared, but not yet
3767 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003768 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003769 Declaration->isConstexpr())
3770 return false;
3771
Richard Smith0838f3a2013-05-14 05:18:44 +00003772 // Bail out with no diagnostic if the function declaration itself is invalid.
3773 // We will have produced a relevant diagnostic while parsing it.
3774 if (Declaration->isInvalidDecl())
3775 return false;
3776
Richard Smith357362d2011-12-13 06:39:58 +00003777 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003778 if (Definition && Definition->isConstexpr() &&
3779 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003780 return true;
3781
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003782 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003783 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003784 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3785 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003786 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3787 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3788 << DiagDecl;
3789 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3790 } else {
3791 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3792 }
3793 return false;
3794}
3795
Richard Smithbe6dd812014-11-19 21:27:17 +00003796/// Determine if a class has any fields that might need to be copied by a
3797/// trivial copy or move operation.
3798static bool hasFields(const CXXRecordDecl *RD) {
3799 if (!RD || RD->isEmpty())
3800 return false;
3801 for (auto *FD : RD->fields()) {
3802 if (FD->isUnnamedBitfield())
3803 continue;
3804 return true;
3805 }
3806 for (auto &Base : RD->bases())
3807 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3808 return true;
3809 return false;
3810}
3811
Richard Smithd62306a2011-11-10 06:34:14 +00003812namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003813typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003814}
3815
3816/// EvaluateArgs - Evaluate the arguments to a function call.
3817static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3818 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003819 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003820 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003821 I != E; ++I) {
3822 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3823 // If we're checking for a potential constant expression, evaluate all
3824 // initializers even if some of them fail.
3825 if (!Info.keepEvaluatingAfterFailure())
3826 return false;
3827 Success = false;
3828 }
3829 }
3830 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003831}
3832
Richard Smith254a73d2011-10-28 22:34:42 +00003833/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003834static bool HandleFunctionCall(SourceLocation CallLoc,
3835 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003836 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003837 EvalInfo &Info, APValue &Result,
3838 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003839 ArgVector ArgValues(Args.size());
3840 if (!EvaluateArgs(Args, ArgValues, Info))
3841 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003842
Richard Smith253c2a32012-01-27 01:14:48 +00003843 if (!Info.CheckCallLimit(CallLoc))
3844 return false;
3845
3846 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003847
3848 // For a trivial copy or move assignment, perform an APValue copy. This is
3849 // essential for unions, where the operations performed by the assignment
3850 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003851 //
3852 // Skip this for non-union classes with no fields; in that case, the defaulted
3853 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003854 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003855 if (MD && MD->isDefaulted() &&
3856 (MD->getParent()->isUnion() ||
3857 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003858 assert(This &&
3859 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3860 LValue RHS;
3861 RHS.setFrom(Info.Ctx, ArgValues[0]);
3862 APValue RHSValue;
3863 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3864 RHS, RHSValue))
3865 return false;
3866 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3867 RHSValue))
3868 return false;
3869 This->moveInto(Result);
3870 return true;
3871 }
3872
Richard Smith52a980a2015-08-28 02:43:42 +00003873 StmtResult Ret = {Result, ResultSlot};
3874 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003875 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003876 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003877 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003878 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003879 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003880 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003881}
3882
Richard Smithd62306a2011-11-10 06:34:14 +00003883/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003884static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003885 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003886 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003887 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003888 ArgVector ArgValues(Args.size());
3889 if (!EvaluateArgs(Args, ArgValues, Info))
3890 return false;
3891
Richard Smith253c2a32012-01-27 01:14:48 +00003892 if (!Info.CheckCallLimit(CallLoc))
3893 return false;
3894
Richard Smith3607ffe2012-02-13 03:54:03 +00003895 const CXXRecordDecl *RD = Definition->getParent();
3896 if (RD->getNumVBases()) {
3897 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3898 return false;
3899 }
3900
Richard Smith253c2a32012-01-27 01:14:48 +00003901 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003902
Richard Smith52a980a2015-08-28 02:43:42 +00003903 // FIXME: Creating an APValue just to hold a nonexistent return value is
3904 // wasteful.
3905 APValue RetVal;
3906 StmtResult Ret = {RetVal, nullptr};
3907
Richard Smithd62306a2011-11-10 06:34:14 +00003908 // If it's a delegating constructor, just delegate.
3909 if (Definition->isDelegatingConstructor()) {
3910 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003911 {
3912 FullExpressionRAII InitScope(Info);
3913 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3914 return false;
3915 }
Richard Smith52a980a2015-08-28 02:43:42 +00003916 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003917 }
3918
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003919 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003920 // essential for unions (or classes with anonymous union members), where the
3921 // operations performed by the constructor cannot be represented by
3922 // ctor-initializers.
3923 //
3924 // Skip this for empty non-union classes; we should not perform an
3925 // lvalue-to-rvalue conversion on them because their copy constructor does not
3926 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003927 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003928 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003929 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003930 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003931 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003932 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003933 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003934 }
3935
3936 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003937 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003938 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003939 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003940
John McCalld7bca762012-05-01 00:38:49 +00003941 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003942 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3943
Richard Smith08d6a2c2013-07-24 07:11:57 +00003944 // A scope for temporaries lifetime-extended by reference members.
3945 BlockScopeRAII LifetimeExtendedScope(Info);
3946
Richard Smith253c2a32012-01-27 01:14:48 +00003947 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003948 unsigned BasesSeen = 0;
3949#ifndef NDEBUG
3950 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3951#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003952 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003953 LValue Subobject = This;
3954 APValue *Value = &Result;
3955
3956 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003957 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003958 if (I->isBaseInitializer()) {
3959 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003960#ifndef NDEBUG
3961 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003962 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003963 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3964 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3965 "base class initializers not in expected order");
3966 ++BaseIt;
3967#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003968 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003969 BaseType->getAsCXXRecordDecl(), &Layout))
3970 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003971 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003972 } else if ((FD = I->getMember())) {
3973 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003974 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003975 if (RD->isUnion()) {
3976 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003977 Value = &Result.getUnionValue();
3978 } else {
3979 Value = &Result.getStructField(FD->getFieldIndex());
3980 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003981 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003982 // Walk the indirect field decl's chain to find the object to initialize,
3983 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003984 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003985 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003986 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3987 // Switch the union field if it differs. This happens if we had
3988 // preceding zero-initialization, and we're now initializing a union
3989 // subobject other than the first.
3990 // FIXME: In this case, the values of the other subobjects are
3991 // specified, since zero-initialization sets all padding bits to zero.
3992 if (Value->isUninit() ||
3993 (Value->isUnion() && Value->getUnionField() != FD)) {
3994 if (CD->isUnion())
3995 *Value = APValue(FD);
3996 else
3997 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003998 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003999 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004000 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004001 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004002 if (CD->isUnion())
4003 Value = &Value->getUnionValue();
4004 else
4005 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004006 }
Richard Smithd62306a2011-11-10 06:34:14 +00004007 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004008 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004009 }
Richard Smith253c2a32012-01-27 01:14:48 +00004010
Richard Smith08d6a2c2013-07-24 07:11:57 +00004011 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004012 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4013 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004014 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004015 // If we're checking for a potential constant expression, evaluate all
4016 // initializers even if some of them fail.
4017 if (!Info.keepEvaluatingAfterFailure())
4018 return false;
4019 Success = false;
4020 }
Richard Smithd62306a2011-11-10 06:34:14 +00004021 }
4022
Richard Smithd9f663b2013-04-22 15:31:51 +00004023 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004024 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004025}
4026
Eli Friedman9a156e52008-11-12 09:44:48 +00004027//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004028// Generic Evaluation
4029//===----------------------------------------------------------------------===//
4030namespace {
4031
Aaron Ballman68af21c2014-01-03 19:26:43 +00004032template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004033class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004034 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004035private:
Richard Smith52a980a2015-08-28 02:43:42 +00004036 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004037 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004038 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004039 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004040 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004041 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004042 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004043
Richard Smith17100ba2012-02-16 02:46:34 +00004044 // Check whether a conditional operator with a non-constant condition is a
4045 // potential constant expression. If neither arm is a potential constant
4046 // expression, then the conditional operator is not either.
4047 template<typename ConditionalOperator>
4048 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004049 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004050
4051 // Speculatively evaluate both arms.
4052 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004053 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004054 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4055
4056 StmtVisitorTy::Visit(E->getFalseExpr());
4057 if (Diag.empty())
4058 return;
4059
4060 Diag.clear();
4061 StmtVisitorTy::Visit(E->getTrueExpr());
4062 if (Diag.empty())
4063 return;
4064 }
4065
4066 Error(E, diag::note_constexpr_conditional_never_const);
4067 }
4068
4069
4070 template<typename ConditionalOperator>
4071 bool HandleConditionalOperator(const ConditionalOperator *E) {
4072 bool BoolResult;
4073 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004074 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00004075 CheckPotentialConstantConditional(E);
4076 return false;
4077 }
4078
4079 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4080 return StmtVisitorTy::Visit(EvalExpr);
4081 }
4082
Peter Collingbournee9200682011-05-13 03:29:01 +00004083protected:
4084 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004085 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004086 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4087
Richard Smith92b1ce02011-12-12 09:28:41 +00004088 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004089 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004090 }
4091
Aaron Ballman68af21c2014-01-03 19:26:43 +00004092 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004093
4094public:
4095 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4096
4097 EvalInfo &getEvalInfo() { return Info; }
4098
Richard Smithf57d8cb2011-12-09 22:58:01 +00004099 /// Report an evaluation error. This should only be called when an error is
4100 /// first discovered. When propagating an error, just return false.
4101 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004102 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004103 return false;
4104 }
4105 bool Error(const Expr *E) {
4106 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4107 }
4108
Aaron Ballman68af21c2014-01-03 19:26:43 +00004109 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004110 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004111 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004112 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004113 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004114 }
4115
Aaron Ballman68af21c2014-01-03 19:26:43 +00004116 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004117 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004118 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004119 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004120 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004121 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004122 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004123 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004124 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004125 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004126 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004127 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004128 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004129 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004130 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004131 // The initializer may not have been parsed yet, or might be erroneous.
4132 if (!E->getExpr())
4133 return Error(E);
4134 return StmtVisitorTy::Visit(E->getExpr());
4135 }
Richard Smith5894a912011-12-19 22:12:41 +00004136 // We cannot create any objects for which cleanups are required, so there is
4137 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004138 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004139 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004140
Aaron Ballman68af21c2014-01-03 19:26:43 +00004141 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004142 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4143 return static_cast<Derived*>(this)->VisitCastExpr(E);
4144 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004145 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004146 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4147 return static_cast<Derived*>(this)->VisitCastExpr(E);
4148 }
4149
Aaron Ballman68af21c2014-01-03 19:26:43 +00004150 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004151 switch (E->getOpcode()) {
4152 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004153 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004154
4155 case BO_Comma:
4156 VisitIgnoredValue(E->getLHS());
4157 return StmtVisitorTy::Visit(E->getRHS());
4158
4159 case BO_PtrMemD:
4160 case BO_PtrMemI: {
4161 LValue Obj;
4162 if (!HandleMemberPointerAccess(Info, E, Obj))
4163 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004164 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004165 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004166 return false;
4167 return DerivedSuccess(Result, E);
4168 }
4169 }
4170 }
4171
Aaron Ballman68af21c2014-01-03 19:26:43 +00004172 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004173 // Evaluate and cache the common expression. We treat it as a temporary,
4174 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004175 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004176 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004177 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004178
Richard Smith17100ba2012-02-16 02:46:34 +00004179 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004180 }
4181
Aaron Ballman68af21c2014-01-03 19:26:43 +00004182 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004183 bool IsBcpCall = false;
4184 // If the condition (ignoring parens) is a __builtin_constant_p call,
4185 // the result is a constant expression if it can be folded without
4186 // side-effects. This is an important GNU extension. See GCC PR38377
4187 // for discussion.
4188 if (const CallExpr *CallCE =
4189 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004190 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004191 IsBcpCall = true;
4192
4193 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4194 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004195 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004196 return false;
4197
Richard Smith6d4c6582013-11-05 22:18:15 +00004198 FoldConstant Fold(Info, IsBcpCall);
4199 if (!HandleConditionalOperator(E)) {
4200 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004201 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004202 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004203
4204 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004205 }
4206
Aaron Ballman68af21c2014-01-03 19:26:43 +00004207 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004208 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4209 return DerivedSuccess(*Value, E);
4210
4211 const Expr *Source = E->getSourceExpr();
4212 if (!Source)
4213 return Error(E);
4214 if (Source == E) { // sanity checking.
4215 assert(0 && "OpaqueValueExpr recursively refers to itself");
4216 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004217 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004218 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004219 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004220
Aaron Ballman68af21c2014-01-03 19:26:43 +00004221 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004222 APValue Result;
4223 if (!handleCallExpr(E, Result, nullptr))
4224 return false;
4225 return DerivedSuccess(Result, E);
4226 }
4227
4228 bool handleCallExpr(const CallExpr *E, APValue &Result,
4229 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004230 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004231 QualType CalleeType = Callee->getType();
4232
Craig Topper36250ad2014-05-12 05:36:57 +00004233 const FunctionDecl *FD = nullptr;
4234 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004235 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004236 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004237
Richard Smithe97cbd72011-11-11 04:05:33 +00004238 // Extract function decl and 'this' pointer from the callee.
4239 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004240 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004241 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4242 // Explicit bound member calls, such as x.f() or p->g();
4243 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004244 return false;
4245 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004246 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004247 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004248 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4249 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004250 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4251 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004252 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004253 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004254 return Error(Callee);
4255
4256 FD = dyn_cast<FunctionDecl>(Member);
4257 if (!FD)
4258 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004259 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004260 LValue Call;
4261 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004262 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004263
Richard Smitha8105bc2012-01-06 16:39:00 +00004264 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004265 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004266 FD = dyn_cast_or_null<FunctionDecl>(
4267 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004268 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004270
4271 // Overloaded operator calls to member functions are represented as normal
4272 // calls with '*this' as the first argument.
4273 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4274 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004275 // FIXME: When selecting an implicit conversion for an overloaded
4276 // operator delete, we sometimes try to evaluate calls to conversion
4277 // operators without a 'this' parameter!
4278 if (Args.empty())
4279 return Error(E);
4280
Richard Smithe97cbd72011-11-11 04:05:33 +00004281 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4282 return false;
4283 This = &ThisVal;
4284 Args = Args.slice(1);
4285 }
4286
4287 // Don't call function pointers which have been cast to some other type.
4288 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004289 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004290 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004291 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004292
Richard Smith47b34932012-02-01 02:39:43 +00004293 if (This && !This->checkSubobject(Info, E, CSK_This))
4294 return false;
4295
Richard Smith3607ffe2012-02-13 03:54:03 +00004296 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4297 // calls to such functions in constant expressions.
4298 if (This && !HasQualifier &&
4299 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4300 return Error(E, diag::note_constexpr_virtual_call);
4301
Craig Topper36250ad2014-05-12 05:36:57 +00004302 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004303 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004304
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004305 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004306 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4307 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004308 return false;
4309
Richard Smith52a980a2015-08-28 02:43:42 +00004310 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004311 }
4312
Aaron Ballman68af21c2014-01-03 19:26:43 +00004313 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004314 return StmtVisitorTy::Visit(E->getInitializer());
4315 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004316 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004317 if (E->getNumInits() == 0)
4318 return DerivedZeroInitialization(E);
4319 if (E->getNumInits() == 1)
4320 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004321 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004322 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004323 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004324 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004325 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004326 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004327 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004328 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004329 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004330 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004331 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004332
Richard Smithd62306a2011-11-10 06:34:14 +00004333 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004334 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004335 assert(!E->isArrow() && "missing call to bound member function?");
4336
Richard Smith2e312c82012-03-03 22:46:17 +00004337 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004338 if (!Evaluate(Val, Info, E->getBase()))
4339 return false;
4340
4341 QualType BaseTy = E->getBase()->getType();
4342
4343 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004344 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004345 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004346 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004347 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4348
Richard Smith3229b742013-05-05 21:17:10 +00004349 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004350 SubobjectDesignator Designator(BaseTy);
4351 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004352
Richard Smith3229b742013-05-05 21:17:10 +00004353 APValue Result;
4354 return extractSubobject(Info, E, Obj, Designator, Result) &&
4355 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004356 }
4357
Aaron Ballman68af21c2014-01-03 19:26:43 +00004358 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004359 switch (E->getCastKind()) {
4360 default:
4361 break;
4362
Richard Smitha23ab512013-05-23 00:30:41 +00004363 case CK_AtomicToNonAtomic: {
4364 APValue AtomicVal;
4365 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4366 return false;
4367 return DerivedSuccess(AtomicVal, E);
4368 }
4369
Richard Smith11562c52011-10-28 17:51:58 +00004370 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004371 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004372 return StmtVisitorTy::Visit(E->getSubExpr());
4373
4374 case CK_LValueToRValue: {
4375 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004376 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4377 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004378 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004379 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004380 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004381 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004382 return false;
4383 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004384 }
4385 }
4386
Richard Smithf57d8cb2011-12-09 22:58:01 +00004387 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004388 }
4389
Aaron Ballman68af21c2014-01-03 19:26:43 +00004390 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004391 return VisitUnaryPostIncDec(UO);
4392 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004393 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004394 return VisitUnaryPostIncDec(UO);
4395 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004396 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004397 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004398 return Error(UO);
4399
4400 LValue LVal;
4401 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4402 return false;
4403 APValue RVal;
4404 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4405 UO->isIncrementOp(), &RVal))
4406 return false;
4407 return DerivedSuccess(RVal, UO);
4408 }
4409
Aaron Ballman68af21c2014-01-03 19:26:43 +00004410 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004411 // We will have checked the full-expressions inside the statement expression
4412 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004413 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004414 return Error(E);
4415
Richard Smith08d6a2c2013-07-24 07:11:57 +00004416 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004417 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004418 if (CS->body_empty())
4419 return true;
4420
Richard Smith51f03172013-06-20 03:00:05 +00004421 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4422 BE = CS->body_end();
4423 /**/; ++BI) {
4424 if (BI + 1 == BE) {
4425 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4426 if (!FinalExpr) {
4427 Info.Diag((*BI)->getLocStart(),
4428 diag::note_constexpr_stmt_expr_unsupported);
4429 return false;
4430 }
4431 return this->Visit(FinalExpr);
4432 }
4433
4434 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004435 StmtResult Result = { ReturnValue, nullptr };
4436 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004437 if (ESR != ESR_Succeeded) {
4438 // FIXME: If the statement-expression terminated due to 'return',
4439 // 'break', or 'continue', it would be nice to propagate that to
4440 // the outer statement evaluation rather than bailing out.
4441 if (ESR != ESR_Failed)
4442 Info.Diag((*BI)->getLocStart(),
4443 diag::note_constexpr_stmt_expr_unsupported);
4444 return false;
4445 }
4446 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004447
4448 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004449 }
4450
Richard Smith4a678122011-10-24 18:44:57 +00004451 /// Visit a value which is evaluated, but whose value is ignored.
4452 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004453 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004454 }
David Majnemere9807b22016-02-26 04:23:19 +00004455
4456 /// Potentially visit a MemberExpr's base expression.
4457 void VisitIgnoredBaseExpression(const Expr *E) {
4458 // While MSVC doesn't evaluate the base expression, it does diagnose the
4459 // presence of side-effecting behavior.
4460 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4461 return;
4462 VisitIgnoredValue(E);
4463 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004464};
4465
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004466}
Peter Collingbournee9200682011-05-13 03:29:01 +00004467
4468//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004469// Common base class for lvalue and temporary evaluation.
4470//===----------------------------------------------------------------------===//
4471namespace {
4472template<class Derived>
4473class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004475protected:
4476 LValue &Result;
4477 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004478 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004479
4480 bool Success(APValue::LValueBase B) {
4481 Result.set(B);
4482 return true;
4483 }
4484
4485public:
4486 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4487 ExprEvaluatorBaseTy(Info), Result(Result) {}
4488
Richard Smith2e312c82012-03-03 22:46:17 +00004489 bool Success(const APValue &V, const Expr *E) {
4490 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004491 return true;
4492 }
Richard Smith027bf112011-11-17 22:56:20 +00004493
Richard Smith027bf112011-11-17 22:56:20 +00004494 bool VisitMemberExpr(const MemberExpr *E) {
4495 // Handle non-static data members.
4496 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004497 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004498 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004499 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004500 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004501 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004502 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004503 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004504 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004505 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004506 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004507 BaseTy = E->getBase()->getType();
4508 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004509 if (!EvalOK) {
4510 if (!this->Info.allowInvalidBaseExpr())
4511 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004512 Result.setInvalid(E);
4513 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004514 }
Richard Smith027bf112011-11-17 22:56:20 +00004515
Richard Smith1b78b3d2012-01-25 22:15:11 +00004516 const ValueDecl *MD = E->getMemberDecl();
4517 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4518 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4519 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4520 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004521 if (!HandleLValueMember(this->Info, E, Result, FD))
4522 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004523 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004524 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4525 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004526 } else
4527 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004528
Richard Smith1b78b3d2012-01-25 22:15:11 +00004529 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004530 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004531 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004532 RefValue))
4533 return false;
4534 return Success(RefValue, E);
4535 }
4536 return true;
4537 }
4538
4539 bool VisitBinaryOperator(const BinaryOperator *E) {
4540 switch (E->getOpcode()) {
4541 default:
4542 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4543
4544 case BO_PtrMemD:
4545 case BO_PtrMemI:
4546 return HandleMemberPointerAccess(this->Info, E, Result);
4547 }
4548 }
4549
4550 bool VisitCastExpr(const CastExpr *E) {
4551 switch (E->getCastKind()) {
4552 default:
4553 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4554
4555 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004556 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004557 if (!this->Visit(E->getSubExpr()))
4558 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004559
4560 // Now figure out the necessary offset to add to the base LV to get from
4561 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004562 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4563 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004564 }
4565 }
4566};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004567}
Richard Smith027bf112011-11-17 22:56:20 +00004568
4569//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004570// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004571//
4572// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4573// function designators (in C), decl references to void objects (in C), and
4574// temporaries (if building with -Wno-address-of-temporary).
4575//
4576// LValue evaluation produces values comprising a base expression of one of the
4577// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004578// - Declarations
4579// * VarDecl
4580// * FunctionDecl
4581// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004582// * CompoundLiteralExpr in C
4583// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004584// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004585// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004586// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004587// * ObjCEncodeExpr
4588// * AddrLabelExpr
4589// * BlockExpr
4590// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004591// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004592// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004593// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004594// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4595// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004596// * A MaterializeTemporaryExpr that has static storage duration, with no
4597// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004598// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004599//===----------------------------------------------------------------------===//
4600namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004601class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004602 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004603public:
Richard Smith027bf112011-11-17 22:56:20 +00004604 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4605 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004606
Richard Smith11562c52011-10-28 17:51:58 +00004607 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004608 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004609
Peter Collingbournee9200682011-05-13 03:29:01 +00004610 bool VisitDeclRefExpr(const DeclRefExpr *E);
4611 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004612 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004613 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4614 bool VisitMemberExpr(const MemberExpr *E);
4615 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4616 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004617 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004618 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004619 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4620 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004621 bool VisitUnaryReal(const UnaryOperator *E);
4622 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004623 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4624 return VisitUnaryPreIncDec(UO);
4625 }
4626 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4627 return VisitUnaryPreIncDec(UO);
4628 }
Richard Smith3229b742013-05-05 21:17:10 +00004629 bool VisitBinAssign(const BinaryOperator *BO);
4630 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004631
Peter Collingbournee9200682011-05-13 03:29:01 +00004632 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004633 switch (E->getCastKind()) {
4634 default:
Richard Smith027bf112011-11-17 22:56:20 +00004635 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004636
Eli Friedmance3e02a2011-10-11 00:13:24 +00004637 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004638 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004639 if (!Visit(E->getSubExpr()))
4640 return false;
4641 Result.Designator.setInvalid();
4642 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004643
Richard Smith027bf112011-11-17 22:56:20 +00004644 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004645 if (!Visit(E->getSubExpr()))
4646 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004647 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004648 }
4649 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004650};
4651} // end anonymous namespace
4652
Richard Smith11562c52011-10-28 17:51:58 +00004653/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004654/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004655/// * function designators in C, and
4656/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004657/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004658static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4659 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004660 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004661 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004662}
4663
Peter Collingbournee9200682011-05-13 03:29:01 +00004664bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004665 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004666 return Success(FD);
4667 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004668 return VisitVarDecl(E, VD);
4669 return Error(E);
4670}
Richard Smith733237d2011-10-24 23:14:33 +00004671
Richard Smith11562c52011-10-28 17:51:58 +00004672bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004673 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004674 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4675 Frame = Info.CurrentCall;
4676
Richard Smithfec09922011-11-01 16:57:24 +00004677 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004678 if (Frame) {
4679 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004680 return true;
4681 }
Richard Smithce40ad62011-11-12 22:28:03 +00004682 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004683 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004684
Richard Smith3229b742013-05-05 21:17:10 +00004685 APValue *V;
4686 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004687 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004688 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004689 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004690 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4691 return false;
4692 }
Richard Smith3229b742013-05-05 21:17:10 +00004693 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004694}
4695
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004696bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4697 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004698 // Walk through the expression to find the materialized temporary itself.
4699 SmallVector<const Expr *, 2> CommaLHSs;
4700 SmallVector<SubobjectAdjustment, 2> Adjustments;
4701 const Expr *Inner = E->GetTemporaryExpr()->
4702 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004703
Richard Smith84401042013-06-03 05:03:02 +00004704 // If we passed any comma operators, evaluate their LHSs.
4705 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4706 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4707 return false;
4708
Richard Smithe6c01442013-06-05 00:46:14 +00004709 // A materialized temporary with static storage duration can appear within the
4710 // result of a constant expression evaluation, so we need to preserve its
4711 // value for use outside this evaluation.
4712 APValue *Value;
4713 if (E->getStorageDuration() == SD_Static) {
4714 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004715 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004716 Result.set(E);
4717 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004718 Value = &Info.CurrentCall->
4719 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004720 Result.set(E, Info.CurrentCall->Index);
4721 }
4722
Richard Smithea4ad5d2013-06-06 08:19:16 +00004723 QualType Type = Inner->getType();
4724
Richard Smith84401042013-06-03 05:03:02 +00004725 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004726 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4727 (E->getStorageDuration() == SD_Static &&
4728 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4729 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004730 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004731 }
Richard Smith84401042013-06-03 05:03:02 +00004732
4733 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004734 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4735 --I;
4736 switch (Adjustments[I].Kind) {
4737 case SubobjectAdjustment::DerivedToBaseAdjustment:
4738 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4739 Type, Result))
4740 return false;
4741 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4742 break;
4743
4744 case SubobjectAdjustment::FieldAdjustment:
4745 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4746 return false;
4747 Type = Adjustments[I].Field->getType();
4748 break;
4749
4750 case SubobjectAdjustment::MemberPointerAdjustment:
4751 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4752 Adjustments[I].Ptr.RHS))
4753 return false;
4754 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4755 break;
4756 }
4757 }
4758
4759 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004760}
4761
Peter Collingbournee9200682011-05-13 03:29:01 +00004762bool
4763LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004764 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4765 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4766 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004767 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004768}
4769
Richard Smith6e525142011-12-27 12:18:28 +00004770bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004771 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004772 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004773
4774 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4775 << E->getExprOperand()->getType()
4776 << E->getExprOperand()->getSourceRange();
4777 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004778}
4779
Francois Pichet0066db92012-04-16 04:08:35 +00004780bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4781 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004782}
Francois Pichet0066db92012-04-16 04:08:35 +00004783
Peter Collingbournee9200682011-05-13 03:29:01 +00004784bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004785 // Handle static data members.
4786 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004787 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004788 return VisitVarDecl(E, VD);
4789 }
4790
Richard Smith254a73d2011-10-28 22:34:42 +00004791 // Handle static member functions.
4792 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4793 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004794 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004795 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004796 }
4797 }
4798
Richard Smithd62306a2011-11-10 06:34:14 +00004799 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004800 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004801}
4802
Peter Collingbournee9200682011-05-13 03:29:01 +00004803bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004804 // FIXME: Deal with vectors as array subscript bases.
4805 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004806 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004807
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004808 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004809 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004810
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004811 APSInt Index;
4812 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004813 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004814
Richard Smith861b5b52013-05-07 23:34:45 +00004815 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4816 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004817}
Eli Friedman9a156e52008-11-12 09:44:48 +00004818
Peter Collingbournee9200682011-05-13 03:29:01 +00004819bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004820 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004821}
4822
Richard Smith66c96992012-02-18 22:04:06 +00004823bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4824 if (!Visit(E->getSubExpr()))
4825 return false;
4826 // __real is a no-op on scalar lvalues.
4827 if (E->getSubExpr()->getType()->isAnyComplexType())
4828 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4829 return true;
4830}
4831
4832bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4833 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4834 "lvalue __imag__ on scalar?");
4835 if (!Visit(E->getSubExpr()))
4836 return false;
4837 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4838 return true;
4839}
4840
Richard Smith243ef902013-05-05 23:31:59 +00004841bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004842 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004843 return Error(UO);
4844
4845 if (!this->Visit(UO->getSubExpr()))
4846 return false;
4847
Richard Smith243ef902013-05-05 23:31:59 +00004848 return handleIncDec(
4849 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004850 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004851}
4852
4853bool LValueExprEvaluator::VisitCompoundAssignOperator(
4854 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004855 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004856 return Error(CAO);
4857
Richard Smith3229b742013-05-05 21:17:10 +00004858 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004859
4860 // The overall lvalue result is the result of evaluating the LHS.
4861 if (!this->Visit(CAO->getLHS())) {
4862 if (Info.keepEvaluatingAfterFailure())
4863 Evaluate(RHS, this->Info, CAO->getRHS());
4864 return false;
4865 }
4866
Richard Smith3229b742013-05-05 21:17:10 +00004867 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4868 return false;
4869
Richard Smith43e77732013-05-07 04:50:00 +00004870 return handleCompoundAssignment(
4871 this->Info, CAO,
4872 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4873 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004874}
4875
4876bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004877 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004878 return Error(E);
4879
Richard Smith3229b742013-05-05 21:17:10 +00004880 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004881
4882 if (!this->Visit(E->getLHS())) {
4883 if (Info.keepEvaluatingAfterFailure())
4884 Evaluate(NewVal, this->Info, E->getRHS());
4885 return false;
4886 }
4887
Richard Smith3229b742013-05-05 21:17:10 +00004888 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4889 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004890
4891 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004892 NewVal);
4893}
4894
Eli Friedman9a156e52008-11-12 09:44:48 +00004895//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004896// Pointer Evaluation
4897//===----------------------------------------------------------------------===//
4898
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004899namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004900class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004901 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004902 LValue &Result;
4903
Peter Collingbournee9200682011-05-13 03:29:01 +00004904 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004905 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004906 return true;
4907 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004908public:
Mike Stump11289f42009-09-09 15:08:12 +00004909
John McCall45d55e42010-05-07 21:00:08 +00004910 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004911 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004912
Richard Smith2e312c82012-03-03 22:46:17 +00004913 bool Success(const APValue &V, const Expr *E) {
4914 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004915 return true;
4916 }
Richard Smithfddd3842011-12-30 21:15:51 +00004917 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004918 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004919 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004920
John McCall45d55e42010-05-07 21:00:08 +00004921 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004922 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004923 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004924 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004925 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004926 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004927 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004928 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004929 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004930 bool VisitCallExpr(const CallExpr *E);
4931 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004932 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004933 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004934 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004935 }
Richard Smithd62306a2011-11-10 06:34:14 +00004936 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004937 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004938 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004939 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004940 if (!Info.CurrentCall->This) {
4941 if (Info.getLangOpts().CPlusPlus11)
4942 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4943 else
4944 Info.Diag(E);
4945 return false;
4946 }
Richard Smithd62306a2011-11-10 06:34:14 +00004947 Result = *Info.CurrentCall->This;
4948 return true;
4949 }
John McCallc07a0c72011-02-17 10:25:35 +00004950
Eli Friedman449fe542009-03-23 04:56:01 +00004951 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004952};
Chris Lattner05706e882008-07-11 18:11:29 +00004953} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004954
John McCall45d55e42010-05-07 21:00:08 +00004955static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004956 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004957 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004958}
4959
John McCall45d55e42010-05-07 21:00:08 +00004960bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004961 if (E->getOpcode() != BO_Add &&
4962 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004963 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004964
Chris Lattner05706e882008-07-11 18:11:29 +00004965 const Expr *PExp = E->getLHS();
4966 const Expr *IExp = E->getRHS();
4967 if (IExp->getType()->isPointerType())
4968 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004969
Richard Smith253c2a32012-01-27 01:14:48 +00004970 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4971 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004972 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004973
John McCall45d55e42010-05-07 21:00:08 +00004974 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004975 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004976 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004977
4978 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004979 if (E->getOpcode() == BO_Sub)
4980 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004981
Ted Kremenek28831752012-08-23 20:46:57 +00004982 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004983 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4984 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004985}
Eli Friedman9a156e52008-11-12 09:44:48 +00004986
John McCall45d55e42010-05-07 21:00:08 +00004987bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4988 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004989}
Mike Stump11289f42009-09-09 15:08:12 +00004990
Peter Collingbournee9200682011-05-13 03:29:01 +00004991bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4992 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004993
Eli Friedman847a2bc2009-12-27 05:43:15 +00004994 switch (E->getCastKind()) {
4995 default:
4996 break;
4997
John McCalle3027922010-08-25 11:45:40 +00004998 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004999 case CK_CPointerToObjCPointerCast:
5000 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005001 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005002 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005003 if (!Visit(SubExpr))
5004 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005005 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5006 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5007 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005008 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005009 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005010 if (SubExpr->getType()->isVoidPointerType())
5011 CCEDiag(E, diag::note_constexpr_invalid_cast)
5012 << 3 << SubExpr->getType();
5013 else
5014 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5015 }
Richard Smith96e0c102011-11-04 02:25:55 +00005016 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005017
Anders Carlsson18275092010-10-31 20:41:46 +00005018 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005019 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005020 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005021 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005022 if (!Result.Base && Result.Offset.isZero())
5023 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005024
Richard Smithd62306a2011-11-10 06:34:14 +00005025 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005026 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005027 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5028 castAs<PointerType>()->getPointeeType(),
5029 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005030
Richard Smith027bf112011-11-17 22:56:20 +00005031 case CK_BaseToDerived:
5032 if (!Visit(E->getSubExpr()))
5033 return false;
5034 if (!Result.Base && Result.Offset.isZero())
5035 return true;
5036 return HandleBaseToDerivedCast(Info, E, Result);
5037
Richard Smith0b0a0b62011-10-29 20:57:55 +00005038 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005039 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005040 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005041
John McCalle3027922010-08-25 11:45:40 +00005042 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005043 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5044
Richard Smith2e312c82012-03-03 22:46:17 +00005045 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005046 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005047 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005048
John McCall45d55e42010-05-07 21:00:08 +00005049 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005050 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5051 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005052 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005053 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005054 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005055 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005056 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005057 return true;
5058 } else {
5059 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005060 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005061 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005062 }
5063 }
John McCalle3027922010-08-25 11:45:40 +00005064 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005065 if (SubExpr->isGLValue()) {
5066 if (!EvaluateLValue(SubExpr, Result, Info))
5067 return false;
5068 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005069 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005070 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005071 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005072 return false;
5073 }
Richard Smith96e0c102011-11-04 02:25:55 +00005074 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005075 if (const ConstantArrayType *CAT
5076 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5077 Result.addArray(Info, E, CAT);
5078 else
5079 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005080 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005081
John McCalle3027922010-08-25 11:45:40 +00005082 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005083 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005084 }
5085
Richard Smith11562c52011-10-28 17:51:58 +00005086 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005087}
Chris Lattner05706e882008-07-11 18:11:29 +00005088
Hal Finkel0dd05d42014-10-03 17:18:37 +00005089static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5090 // C++ [expr.alignof]p3:
5091 // When alignof is applied to a reference type, the result is the
5092 // alignment of the referenced type.
5093 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5094 T = Ref->getPointeeType();
5095
5096 // __alignof is defined to return the preferred alignment.
5097 return Info.Ctx.toCharUnitsFromBits(
5098 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5099}
5100
5101static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5102 E = E->IgnoreParens();
5103
5104 // The kinds of expressions that we have special-case logic here for
5105 // should be kept up to date with the special checks for those
5106 // expressions in Sema.
5107
5108 // alignof decl is always accepted, even if it doesn't make sense: we default
5109 // to 1 in those cases.
5110 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5111 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5112 /*RefAsPointee*/true);
5113
5114 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5115 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5116 /*RefAsPointee*/true);
5117
5118 return GetAlignOfType(Info, E->getType());
5119}
5120
Peter Collingbournee9200682011-05-13 03:29:01 +00005121bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005122 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005123 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005124
Alp Tokera724cff2013-12-28 21:59:02 +00005125 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005126 case Builtin::BI__builtin_addressof:
5127 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005128 case Builtin::BI__builtin_assume_aligned: {
5129 // We need to be very careful here because: if the pointer does not have the
5130 // asserted alignment, then the behavior is undefined, and undefined
5131 // behavior is non-constant.
5132 if (!EvaluatePointer(E->getArg(0), Result, Info))
5133 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005134
Hal Finkel0dd05d42014-10-03 17:18:37 +00005135 LValue OffsetResult(Result);
5136 APSInt Alignment;
5137 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5138 return false;
5139 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5140
5141 if (E->getNumArgs() > 2) {
5142 APSInt Offset;
5143 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5144 return false;
5145
5146 int64_t AdditionalOffset = -getExtValue(Offset);
5147 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5148 }
5149
5150 // If there is a base object, then it must have the correct alignment.
5151 if (OffsetResult.Base) {
5152 CharUnits BaseAlignment;
5153 if (const ValueDecl *VD =
5154 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5155 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5156 } else {
5157 BaseAlignment =
5158 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5159 }
5160
5161 if (BaseAlignment < Align) {
5162 Result.Designator.setInvalid();
5163 // FIXME: Quantities here cast to integers because the plural modifier
5164 // does not work on APSInts yet.
5165 CCEDiag(E->getArg(0),
5166 diag::note_constexpr_baa_insufficient_alignment) << 0
5167 << (int) BaseAlignment.getQuantity()
5168 << (unsigned) getExtValue(Alignment);
5169 return false;
5170 }
5171 }
5172
5173 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005174 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005175 Result.Designator.setInvalid();
5176 APSInt Offset(64, false);
5177 Offset = OffsetResult.Offset.getQuantity();
5178
5179 if (OffsetResult.Base)
5180 CCEDiag(E->getArg(0),
5181 diag::note_constexpr_baa_insufficient_alignment) << 1
5182 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5183 else
5184 CCEDiag(E->getArg(0),
5185 diag::note_constexpr_baa_value_insufficient_alignment)
5186 << Offset << (unsigned) getExtValue(Alignment);
5187
5188 return false;
5189 }
5190
5191 return true;
5192 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005193 default:
5194 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5195 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005196}
Chris Lattner05706e882008-07-11 18:11:29 +00005197
5198//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005199// Member Pointer Evaluation
5200//===----------------------------------------------------------------------===//
5201
5202namespace {
5203class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005204 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005205 MemberPtr &Result;
5206
5207 bool Success(const ValueDecl *D) {
5208 Result = MemberPtr(D);
5209 return true;
5210 }
5211public:
5212
5213 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5214 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5215
Richard Smith2e312c82012-03-03 22:46:17 +00005216 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005217 Result.setFrom(V);
5218 return true;
5219 }
Richard Smithfddd3842011-12-30 21:15:51 +00005220 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005221 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005222 }
5223
5224 bool VisitCastExpr(const CastExpr *E);
5225 bool VisitUnaryAddrOf(const UnaryOperator *E);
5226};
5227} // end anonymous namespace
5228
5229static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5230 EvalInfo &Info) {
5231 assert(E->isRValue() && E->getType()->isMemberPointerType());
5232 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5233}
5234
5235bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5236 switch (E->getCastKind()) {
5237 default:
5238 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5239
5240 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005241 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005242 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005243
5244 case CK_BaseToDerivedMemberPointer: {
5245 if (!Visit(E->getSubExpr()))
5246 return false;
5247 if (E->path_empty())
5248 return true;
5249 // Base-to-derived member pointer casts store the path in derived-to-base
5250 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5251 // the wrong end of the derived->base arc, so stagger the path by one class.
5252 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5253 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5254 PathI != PathE; ++PathI) {
5255 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5256 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5257 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005258 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005259 }
5260 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5261 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005262 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005263 return true;
5264 }
5265
5266 case CK_DerivedToBaseMemberPointer:
5267 if (!Visit(E->getSubExpr()))
5268 return false;
5269 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5270 PathE = E->path_end(); PathI != PathE; ++PathI) {
5271 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5272 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5273 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005274 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005275 }
5276 return true;
5277 }
5278}
5279
5280bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5281 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5282 // member can be formed.
5283 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5284}
5285
5286//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005287// Record Evaluation
5288//===----------------------------------------------------------------------===//
5289
5290namespace {
5291 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005292 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005293 const LValue &This;
5294 APValue &Result;
5295 public:
5296
5297 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5298 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5299
Richard Smith2e312c82012-03-03 22:46:17 +00005300 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005301 Result = V;
5302 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005303 }
Richard Smithb8348f52016-05-12 22:16:28 +00005304 bool ZeroInitialization(const Expr *E) {
5305 return ZeroInitialization(E, E->getType());
5306 }
5307 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005308
Richard Smith52a980a2015-08-28 02:43:42 +00005309 bool VisitCallExpr(const CallExpr *E) {
5310 return handleCallExpr(E, Result, &This);
5311 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005312 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005313 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005314 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5315 return VisitCXXConstructExpr(E, E->getType());
5316 }
5317 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005318 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005319 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005320}
Richard Smithd62306a2011-11-10 06:34:14 +00005321
Richard Smithfddd3842011-12-30 21:15:51 +00005322/// Perform zero-initialization on an object of non-union class type.
5323/// C++11 [dcl.init]p5:
5324/// To zero-initialize an object or reference of type T means:
5325/// [...]
5326/// -- if T is a (possibly cv-qualified) non-union class type,
5327/// each non-static data member and each base-class subobject is
5328/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005329static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5330 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005331 const LValue &This, APValue &Result) {
5332 assert(!RD->isUnion() && "Expected non-union class type");
5333 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5334 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005335 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005336
John McCalld7bca762012-05-01 00:38:49 +00005337 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005338 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5339
5340 if (CD) {
5341 unsigned Index = 0;
5342 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005343 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005344 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5345 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005346 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5347 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005348 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005349 Result.getStructBase(Index)))
5350 return false;
5351 }
5352 }
5353
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005354 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005355 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005356 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005357 continue;
5358
5359 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005360 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005361 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005362
David Blaikie2d7c57e2012-04-30 02:36:29 +00005363 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005364 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005365 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005366 return false;
5367 }
5368
5369 return true;
5370}
5371
Richard Smithb8348f52016-05-12 22:16:28 +00005372bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5373 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005374 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005375 if (RD->isUnion()) {
5376 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5377 // object's first non-static named data member is zero-initialized
5378 RecordDecl::field_iterator I = RD->field_begin();
5379 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005380 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005381 return true;
5382 }
5383
5384 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005385 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005386 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005387 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005388 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005389 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005390 }
5391
Richard Smith5d108602012-02-17 00:44:16 +00005392 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005393 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005394 return false;
5395 }
5396
Richard Smitha8105bc2012-01-06 16:39:00 +00005397 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005398}
5399
Richard Smithe97cbd72011-11-11 04:05:33 +00005400bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5401 switch (E->getCastKind()) {
5402 default:
5403 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5404
5405 case CK_ConstructorConversion:
5406 return Visit(E->getSubExpr());
5407
5408 case CK_DerivedToBase:
5409 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005410 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005411 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005412 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005413 if (!DerivedObject.isStruct())
5414 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005415
5416 // Derived-to-base rvalue conversion: just slice off the derived part.
5417 APValue *Value = &DerivedObject;
5418 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5419 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5420 PathE = E->path_end(); PathI != PathE; ++PathI) {
5421 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5422 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5423 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5424 RD = Base;
5425 }
5426 Result = *Value;
5427 return true;
5428 }
5429 }
5430}
5431
Richard Smithd62306a2011-11-10 06:34:14 +00005432bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5433 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005434 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005435 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5436
5437 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005438 const FieldDecl *Field = E->getInitializedFieldInUnion();
5439 Result = APValue(Field);
5440 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005441 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005442
5443 // If the initializer list for a union does not contain any elements, the
5444 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005445 // FIXME: The element should be initialized from an initializer list.
5446 // Is this difference ever observable for initializer lists which
5447 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005448 ImplicitValueInitExpr VIE(Field->getType());
5449 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5450
Richard Smithd62306a2011-11-10 06:34:14 +00005451 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005452 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5453 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005454
5455 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5456 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5457 isa<CXXDefaultInitExpr>(InitExpr));
5458
Richard Smithb228a862012-02-15 02:18:13 +00005459 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005460 }
5461
Richard Smith872307e2016-03-08 22:17:41 +00005462 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005463 if (Result.isUninit())
5464 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5465 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005466 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005467 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005468
5469 // Initialize base classes.
5470 if (CXXRD) {
5471 for (const auto &Base : CXXRD->bases()) {
5472 assert(ElementNo < E->getNumInits() && "missing init for base class");
5473 const Expr *Init = E->getInit(ElementNo);
5474
5475 LValue Subobject = This;
5476 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5477 return false;
5478
5479 APValue &FieldVal = Result.getStructBase(ElementNo);
5480 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
5481 if (!Info.keepEvaluatingAfterFailure())
5482 return false;
5483 Success = false;
5484 }
5485 ++ElementNo;
5486 }
5487 }
5488
5489 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005490 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005491 // Anonymous bit-fields are not considered members of the class for
5492 // purposes of aggregate initialization.
5493 if (Field->isUnnamedBitfield())
5494 continue;
5495
5496 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005497
Richard Smith253c2a32012-01-27 01:14:48 +00005498 bool HaveInit = ElementNo < E->getNumInits();
5499
5500 // FIXME: Diagnostics here should point to the end of the initializer
5501 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005502 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005503 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005504 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005505
5506 // Perform an implicit value-initialization for members beyond the end of
5507 // the initializer list.
5508 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005509 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005510
Richard Smith852c9db2013-04-20 22:23:05 +00005511 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5512 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5513 isa<CXXDefaultInitExpr>(Init));
5514
Richard Smith49ca8aa2013-08-06 07:09:20 +00005515 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5516 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5517 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005518 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005519 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005520 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005521 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005522 }
5523 }
5524
Richard Smith253c2a32012-01-27 01:14:48 +00005525 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005526}
5527
Richard Smithb8348f52016-05-12 22:16:28 +00005528bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5529 QualType T) {
5530 // Note that E's type is not necessarily the type of our class here; we might
5531 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005532 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005533 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5534
Richard Smithfddd3842011-12-30 21:15:51 +00005535 bool ZeroInit = E->requiresZeroInitialization();
5536 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005537 // If we've already performed zero-initialization, we're already done.
5538 if (!Result.isUninit())
5539 return true;
5540
Richard Smithda3f4fd2014-03-05 23:32:50 +00005541 // We can get here in two different ways:
5542 // 1) We're performing value-initialization, and should zero-initialize
5543 // the object, or
5544 // 2) We're performing default-initialization of an object with a trivial
5545 // constexpr default constructor, in which case we should start the
5546 // lifetimes of all the base subobjects (there can be no data member
5547 // subobjects in this case) per [basic.life]p1.
5548 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005549 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005550 }
5551
Craig Topper36250ad2014-05-12 05:36:57 +00005552 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005553 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005554
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005555 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005556 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005557
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005558 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005559 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005560 if (const MaterializeTemporaryExpr *ME
5561 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5562 return Visit(ME->GetTemporaryExpr());
5563
Richard Smithb8348f52016-05-12 22:16:28 +00005564 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005565 return false;
5566
Craig Topper5fc8fc22014-08-27 06:28:36 +00005567 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005568 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005569 cast<CXXConstructorDecl>(Definition), Info,
5570 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005571}
5572
Richard Smithcc1b96d2013-06-12 22:31:48 +00005573bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5574 const CXXStdInitializerListExpr *E) {
5575 const ConstantArrayType *ArrayType =
5576 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5577
5578 LValue Array;
5579 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5580 return false;
5581
5582 // Get a pointer to the first element of the array.
5583 Array.addArray(Info, E, ArrayType);
5584
5585 // FIXME: Perform the checks on the field types in SemaInit.
5586 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5587 RecordDecl::field_iterator Field = Record->field_begin();
5588 if (Field == Record->field_end())
5589 return Error(E);
5590
5591 // Start pointer.
5592 if (!Field->getType()->isPointerType() ||
5593 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5594 ArrayType->getElementType()))
5595 return Error(E);
5596
5597 // FIXME: What if the initializer_list type has base classes, etc?
5598 Result = APValue(APValue::UninitStruct(), 0, 2);
5599 Array.moveInto(Result.getStructField(0));
5600
5601 if (++Field == Record->field_end())
5602 return Error(E);
5603
5604 if (Field->getType()->isPointerType() &&
5605 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5606 ArrayType->getElementType())) {
5607 // End pointer.
5608 if (!HandleLValueArrayAdjustment(Info, E, Array,
5609 ArrayType->getElementType(),
5610 ArrayType->getSize().getZExtValue()))
5611 return false;
5612 Array.moveInto(Result.getStructField(1));
5613 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5614 // Length.
5615 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5616 else
5617 return Error(E);
5618
5619 if (++Field != Record->field_end())
5620 return Error(E);
5621
5622 return true;
5623}
5624
Richard Smithd62306a2011-11-10 06:34:14 +00005625static bool EvaluateRecord(const Expr *E, const LValue &This,
5626 APValue &Result, EvalInfo &Info) {
5627 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005628 "can't evaluate expression as a record rvalue");
5629 return RecordExprEvaluator(Info, This, Result).Visit(E);
5630}
5631
5632//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005633// Temporary Evaluation
5634//
5635// Temporaries are represented in the AST as rvalues, but generally behave like
5636// lvalues. The full-object of which the temporary is a subobject is implicitly
5637// materialized so that a reference can bind to it.
5638//===----------------------------------------------------------------------===//
5639namespace {
5640class TemporaryExprEvaluator
5641 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5642public:
5643 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5644 LValueExprEvaluatorBaseTy(Info, Result) {}
5645
5646 /// Visit an expression which constructs the value of this temporary.
5647 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005648 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005649 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5650 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005651 }
5652
5653 bool VisitCastExpr(const CastExpr *E) {
5654 switch (E->getCastKind()) {
5655 default:
5656 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5657
5658 case CK_ConstructorConversion:
5659 return VisitConstructExpr(E->getSubExpr());
5660 }
5661 }
5662 bool VisitInitListExpr(const InitListExpr *E) {
5663 return VisitConstructExpr(E);
5664 }
5665 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5666 return VisitConstructExpr(E);
5667 }
5668 bool VisitCallExpr(const CallExpr *E) {
5669 return VisitConstructExpr(E);
5670 }
Richard Smith513955c2014-12-17 19:24:30 +00005671 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5672 return VisitConstructExpr(E);
5673 }
Richard Smith027bf112011-11-17 22:56:20 +00005674};
5675} // end anonymous namespace
5676
5677/// Evaluate an expression of record type as a temporary.
5678static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005679 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005680 return TemporaryExprEvaluator(Info, Result).Visit(E);
5681}
5682
5683//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005684// Vector Evaluation
5685//===----------------------------------------------------------------------===//
5686
5687namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005688 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005689 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005690 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005691 public:
Mike Stump11289f42009-09-09 15:08:12 +00005692
Richard Smith2d406342011-10-22 21:10:00 +00005693 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5694 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005695
Craig Topper9798b932015-09-29 04:30:05 +00005696 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005697 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5698 // FIXME: remove this APValue copy.
5699 Result = APValue(V.data(), V.size());
5700 return true;
5701 }
Richard Smith2e312c82012-03-03 22:46:17 +00005702 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005703 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005704 Result = V;
5705 return true;
5706 }
Richard Smithfddd3842011-12-30 21:15:51 +00005707 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005708
Richard Smith2d406342011-10-22 21:10:00 +00005709 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005710 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005711 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005712 bool VisitInitListExpr(const InitListExpr *E);
5713 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005714 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005715 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005716 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005717 };
5718} // end anonymous namespace
5719
5720static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005721 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005722 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005723}
5724
George Burgess IV533ff002015-12-11 00:23:35 +00005725bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005726 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005727 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005728
Richard Smith161f09a2011-12-06 22:44:34 +00005729 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005730 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005731
Eli Friedmanc757de22011-03-25 00:43:55 +00005732 switch (E->getCastKind()) {
5733 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005734 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005735 if (SETy->isIntegerType()) {
5736 APSInt IntResult;
5737 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005738 return false;
5739 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005740 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005741 APFloat FloatResult(0.0);
5742 if (!EvaluateFloat(SE, FloatResult, Info))
5743 return false;
5744 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005745 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005746 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005747 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005748
5749 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005750 SmallVector<APValue, 4> Elts(NElts, Val);
5751 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005752 }
Eli Friedman803acb32011-12-22 03:51:45 +00005753 case CK_BitCast: {
5754 // Evaluate the operand into an APInt we can extract from.
5755 llvm::APInt SValInt;
5756 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5757 return false;
5758 // Extract the elements
5759 QualType EltTy = VTy->getElementType();
5760 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5761 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5762 SmallVector<APValue, 4> Elts;
5763 if (EltTy->isRealFloatingType()) {
5764 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005765 unsigned FloatEltSize = EltSize;
5766 if (&Sem == &APFloat::x87DoubleExtended)
5767 FloatEltSize = 80;
5768 for (unsigned i = 0; i < NElts; i++) {
5769 llvm::APInt Elt;
5770 if (BigEndian)
5771 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5772 else
5773 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005774 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005775 }
5776 } else if (EltTy->isIntegerType()) {
5777 for (unsigned i = 0; i < NElts; i++) {
5778 llvm::APInt Elt;
5779 if (BigEndian)
5780 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5781 else
5782 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5783 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5784 }
5785 } else {
5786 return Error(E);
5787 }
5788 return Success(Elts, E);
5789 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005790 default:
Richard Smith11562c52011-10-28 17:51:58 +00005791 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005792 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005793}
5794
Richard Smith2d406342011-10-22 21:10:00 +00005795bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005796VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005797 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005798 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005799 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005800
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005801 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005802 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005803
Eli Friedmanb9c71292012-01-03 23:24:20 +00005804 // The number of initializers can be less than the number of
5805 // vector elements. For OpenCL, this can be due to nested vector
5806 // initialization. For GCC compatibility, missing trailing elements
5807 // should be initialized with zeroes.
5808 unsigned CountInits = 0, CountElts = 0;
5809 while (CountElts < NumElements) {
5810 // Handle nested vector initialization.
5811 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005812 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005813 APValue v;
5814 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5815 return Error(E);
5816 unsigned vlen = v.getVectorLength();
5817 for (unsigned j = 0; j < vlen; j++)
5818 Elements.push_back(v.getVectorElt(j));
5819 CountElts += vlen;
5820 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005821 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005822 if (CountInits < NumInits) {
5823 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005824 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005825 } else // trailing integer zero.
5826 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5827 Elements.push_back(APValue(sInt));
5828 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005829 } else {
5830 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005831 if (CountInits < NumInits) {
5832 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005833 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005834 } else // trailing float zero.
5835 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5836 Elements.push_back(APValue(f));
5837 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005838 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005839 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005840 }
Richard Smith2d406342011-10-22 21:10:00 +00005841 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005842}
5843
Richard Smith2d406342011-10-22 21:10:00 +00005844bool
Richard Smithfddd3842011-12-30 21:15:51 +00005845VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005846 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005847 QualType EltTy = VT->getElementType();
5848 APValue ZeroElement;
5849 if (EltTy->isIntegerType())
5850 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5851 else
5852 ZeroElement =
5853 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5854
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005855 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005856 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005857}
5858
Richard Smith2d406342011-10-22 21:10:00 +00005859bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005860 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005861 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005862}
5863
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005864//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005865// Array Evaluation
5866//===----------------------------------------------------------------------===//
5867
5868namespace {
5869 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005870 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005871 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005872 APValue &Result;
5873 public:
5874
Richard Smithd62306a2011-11-10 06:34:14 +00005875 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5876 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005877
5878 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005879 assert((V.isArray() || V.isLValue()) &&
5880 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005881 Result = V;
5882 return true;
5883 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005884
Richard Smithfddd3842011-12-30 21:15:51 +00005885 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005886 const ConstantArrayType *CAT =
5887 Info.Ctx.getAsConstantArrayType(E->getType());
5888 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005889 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005890
5891 Result = APValue(APValue::UninitArray(), 0,
5892 CAT->getSize().getZExtValue());
5893 if (!Result.hasArrayFiller()) return true;
5894
Richard Smithfddd3842011-12-30 21:15:51 +00005895 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005896 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005897 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005898 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005899 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005900 }
5901
Richard Smith52a980a2015-08-28 02:43:42 +00005902 bool VisitCallExpr(const CallExpr *E) {
5903 return handleCallExpr(E, Result, &This);
5904 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005905 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005906 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005907 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5908 const LValue &Subobject,
5909 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005910 };
5911} // end anonymous namespace
5912
Richard Smithd62306a2011-11-10 06:34:14 +00005913static bool EvaluateArray(const Expr *E, const LValue &This,
5914 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005915 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005916 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005917}
5918
5919bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5920 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5921 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005922 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005923
Richard Smithca2cfbf2011-12-22 01:07:19 +00005924 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5925 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005926 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005927 LValue LV;
5928 if (!EvaluateLValue(E->getInit(0), LV, Info))
5929 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005930 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005931 LV.moveInto(Val);
5932 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005933 }
5934
Richard Smith253c2a32012-01-27 01:14:48 +00005935 bool Success = true;
5936
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005937 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5938 "zero-initialized array shouldn't have any initialized elts");
5939 APValue Filler;
5940 if (Result.isArray() && Result.hasArrayFiller())
5941 Filler = Result.getArrayFiller();
5942
Richard Smith9543c5e2013-04-22 14:44:29 +00005943 unsigned NumEltsToInit = E->getNumInits();
5944 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005945 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005946
5947 // If the initializer might depend on the array index, run it for each
5948 // array element. For now, just whitelist non-class value-initialization.
5949 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5950 NumEltsToInit = NumElts;
5951
5952 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005953
5954 // If the array was previously zero-initialized, preserve the
5955 // zero-initialized values.
5956 if (!Filler.isUninit()) {
5957 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5958 Result.getArrayInitializedElt(I) = Filler;
5959 if (Result.hasArrayFiller())
5960 Result.getArrayFiller() = Filler;
5961 }
5962
Richard Smithd62306a2011-11-10 06:34:14 +00005963 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005964 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005965 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5966 const Expr *Init =
5967 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005968 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005969 Info, Subobject, Init) ||
5970 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005971 CAT->getElementType(), 1)) {
5972 if (!Info.keepEvaluatingAfterFailure())
5973 return false;
5974 Success = false;
5975 }
Richard Smithd62306a2011-11-10 06:34:14 +00005976 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005977
Richard Smith9543c5e2013-04-22 14:44:29 +00005978 if (!Result.hasArrayFiller())
5979 return Success;
5980
5981 // If we get here, we have a trivial filler, which we can just evaluate
5982 // once and splat over the rest of the array elements.
5983 assert(FillerExpr && "no array filler for incomplete init list");
5984 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5985 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005986}
5987
Richard Smith027bf112011-11-17 22:56:20 +00005988bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005989 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5990}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005991
Richard Smith9543c5e2013-04-22 14:44:29 +00005992bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5993 const LValue &Subobject,
5994 APValue *Value,
5995 QualType Type) {
5996 bool HadZeroInit = !Value->isUninit();
5997
5998 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5999 unsigned N = CAT->getSize().getZExtValue();
6000
6001 // Preserve the array filler if we had prior zero-initialization.
6002 APValue Filler =
6003 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6004 : APValue();
6005
6006 *Value = APValue(APValue::UninitArray(), N, N);
6007
6008 if (HadZeroInit)
6009 for (unsigned I = 0; I != N; ++I)
6010 Value->getArrayInitializedElt(I) = Filler;
6011
6012 // Initialize the elements.
6013 LValue ArrayElt = Subobject;
6014 ArrayElt.addArray(Info, E, CAT);
6015 for (unsigned I = 0; I != N; ++I)
6016 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6017 CAT->getElementType()) ||
6018 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6019 CAT->getElementType(), 1))
6020 return false;
6021
6022 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006023 }
Richard Smith027bf112011-11-17 22:56:20 +00006024
Richard Smith9543c5e2013-04-22 14:44:29 +00006025 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006026 return Error(E);
6027
Richard Smithb8348f52016-05-12 22:16:28 +00006028 return RecordExprEvaluator(Info, Subobject, *Value)
6029 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006030}
6031
Richard Smithf3e9e432011-11-07 09:22:26 +00006032//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006033// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006034//
6035// As a GNU extension, we support casting pointers to sufficiently-wide integer
6036// types and back in constant folding. Integer values are thus represented
6037// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006038//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006039
6040namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006041class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006042 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006043 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006044public:
Richard Smith2e312c82012-03-03 22:46:17 +00006045 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006046 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006048 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006049 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006050 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006051 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006052 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006053 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006054 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006055 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006056 return true;
6057 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006058 bool Success(const llvm::APSInt &SI, const Expr *E) {
6059 return Success(SI, E, Result);
6060 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006061
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006062 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006063 assert(E->getType()->isIntegralOrEnumerationType() &&
6064 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006065 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006066 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006067 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006068 Result.getInt().setIsUnsigned(
6069 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006070 return true;
6071 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006072 bool Success(const llvm::APInt &I, const Expr *E) {
6073 return Success(I, E, Result);
6074 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006075
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006076 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006077 assert(E->getType()->isIntegralOrEnumerationType() &&
6078 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006079 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006080 return true;
6081 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006082 bool Success(uint64_t Value, const Expr *E) {
6083 return Success(Value, E, Result);
6084 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006085
Ken Dyckdbc01912011-03-11 02:13:43 +00006086 bool Success(CharUnits Size, const Expr *E) {
6087 return Success(Size.getQuantity(), E);
6088 }
6089
Richard Smith2e312c82012-03-03 22:46:17 +00006090 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006091 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006092 Result = V;
6093 return true;
6094 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006095 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006096 }
Mike Stump11289f42009-09-09 15:08:12 +00006097
Richard Smithfddd3842011-12-30 21:15:51 +00006098 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006099
Peter Collingbournee9200682011-05-13 03:29:01 +00006100 //===--------------------------------------------------------------------===//
6101 // Visitor Methods
6102 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006103
Chris Lattner7174bf32008-07-12 00:38:25 +00006104 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006105 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006106 }
6107 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006108 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006109 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006110
6111 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6112 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006113 if (CheckReferencedDecl(E, E->getDecl()))
6114 return true;
6115
6116 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006117 }
6118 bool VisitMemberExpr(const MemberExpr *E) {
6119 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006120 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006121 return true;
6122 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006123
6124 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006125 }
6126
Peter Collingbournee9200682011-05-13 03:29:01 +00006127 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006128 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006129 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006130 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006131
Peter Collingbournee9200682011-05-13 03:29:01 +00006132 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006133 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006134
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006135 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006136 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006137 }
Mike Stump11289f42009-09-09 15:08:12 +00006138
Ted Kremeneke65b0862012-03-06 20:05:56 +00006139 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6140 return Success(E->getValue(), E);
6141 }
6142
Richard Smith4ce706a2011-10-11 21:43:33 +00006143 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006144 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006145 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006146 }
6147
Douglas Gregor29c42f22012-02-24 07:38:34 +00006148 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6149 return Success(E->getValue(), E);
6150 }
6151
John Wiegley6242b6a2011-04-28 00:16:57 +00006152 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6153 return Success(E->getValue(), E);
6154 }
6155
John Wiegleyf9f65842011-04-25 06:54:41 +00006156 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6157 return Success(E->getValue(), E);
6158 }
6159
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006160 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006161 bool VisitUnaryImag(const UnaryOperator *E);
6162
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006163 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006164 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006165
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006166private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006167 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006168 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006169};
Chris Lattner05706e882008-07-11 18:11:29 +00006170} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006171
Richard Smith11562c52011-10-28 17:51:58 +00006172/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6173/// produce either the integer value or a pointer.
6174///
6175/// GCC has a heinous extension which folds casts between pointer types and
6176/// pointer-sized integral types. We support this by allowing the evaluation of
6177/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6178/// Some simple arithmetic on such values is supported (they are treated much
6179/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006180static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006181 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006182 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006183 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006184}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006185
Richard Smithf57d8cb2011-12-09 22:58:01 +00006186static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006187 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006188 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006189 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006190 if (!Val.isInt()) {
6191 // FIXME: It would be better to produce the diagnostic for casting
6192 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006193 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006194 return false;
6195 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006196 Result = Val.getInt();
6197 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006198}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006199
Richard Smithf57d8cb2011-12-09 22:58:01 +00006200/// Check whether the given declaration can be directly converted to an integral
6201/// rvalue. If not, no diagnostic is produced; there are other things we can
6202/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006203bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006204 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006205 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006206 // Check for signedness/width mismatches between E type and ECD value.
6207 bool SameSign = (ECD->getInitVal().isSigned()
6208 == E->getType()->isSignedIntegerOrEnumerationType());
6209 bool SameWidth = (ECD->getInitVal().getBitWidth()
6210 == Info.Ctx.getIntWidth(E->getType()));
6211 if (SameSign && SameWidth)
6212 return Success(ECD->getInitVal(), E);
6213 else {
6214 // Get rid of mismatch (otherwise Success assertions will fail)
6215 // by computing a new value matching the type of E.
6216 llvm::APSInt Val = ECD->getInitVal();
6217 if (!SameSign)
6218 Val.setIsSigned(!ECD->getInitVal().isSigned());
6219 if (!SameWidth)
6220 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6221 return Success(Val, E);
6222 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006223 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006224 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006225}
6226
Chris Lattner86ee2862008-10-06 06:40:35 +00006227/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6228/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006229static int EvaluateBuiltinClassifyType(const CallExpr *E,
6230 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006231 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006232 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006233 enum gcc_type_class {
6234 no_type_class = -1,
6235 void_type_class, integer_type_class, char_type_class,
6236 enumeral_type_class, boolean_type_class,
6237 pointer_type_class, reference_type_class, offset_type_class,
6238 real_type_class, complex_type_class,
6239 function_type_class, method_type_class,
6240 record_type_class, union_type_class,
6241 array_type_class, string_type_class,
6242 lang_type_class
6243 };
Mike Stump11289f42009-09-09 15:08:12 +00006244
6245 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006246 // ideal, however it is what gcc does.
6247 if (E->getNumArgs() == 0)
6248 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006249
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006250 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6251 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6252
6253 switch (CanTy->getTypeClass()) {
6254#define TYPE(ID, BASE)
6255#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6256#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6257#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6258#include "clang/AST/TypeNodes.def"
6259 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6260
6261 case Type::Builtin:
6262 switch (BT->getKind()) {
6263#define BUILTIN_TYPE(ID, SINGLETON_ID)
6264#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6265#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6266#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6267#include "clang/AST/BuiltinTypes.def"
6268 case BuiltinType::Void:
6269 return void_type_class;
6270
6271 case BuiltinType::Bool:
6272 return boolean_type_class;
6273
6274 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6275 case BuiltinType::UChar:
6276 case BuiltinType::UShort:
6277 case BuiltinType::UInt:
6278 case BuiltinType::ULong:
6279 case BuiltinType::ULongLong:
6280 case BuiltinType::UInt128:
6281 return integer_type_class;
6282
6283 case BuiltinType::NullPtr:
6284 return pointer_type_class;
6285
6286 case BuiltinType::WChar_U:
6287 case BuiltinType::Char16:
6288 case BuiltinType::Char32:
6289 case BuiltinType::ObjCId:
6290 case BuiltinType::ObjCClass:
6291 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006292#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6293 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006294#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006295 case BuiltinType::OCLSampler:
6296 case BuiltinType::OCLEvent:
6297 case BuiltinType::OCLClkEvent:
6298 case BuiltinType::OCLQueue:
6299 case BuiltinType::OCLNDRange:
6300 case BuiltinType::OCLReserveID:
6301 case BuiltinType::Dependent:
6302 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6303 };
6304
6305 case Type::Enum:
6306 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6307 break;
6308
6309 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006310 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006311 break;
6312
6313 case Type::MemberPointer:
6314 if (CanTy->isMemberDataPointerType())
6315 return offset_type_class;
6316 else {
6317 // We expect member pointers to be either data or function pointers,
6318 // nothing else.
6319 assert(CanTy->isMemberFunctionPointerType());
6320 return method_type_class;
6321 }
6322
6323 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006324 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006325
6326 case Type::FunctionNoProto:
6327 case Type::FunctionProto:
6328 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6329
6330 case Type::Record:
6331 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6332 switch (RT->getDecl()->getTagKind()) {
6333 case TagTypeKind::TTK_Struct:
6334 case TagTypeKind::TTK_Class:
6335 case TagTypeKind::TTK_Interface:
6336 return record_type_class;
6337
6338 case TagTypeKind::TTK_Enum:
6339 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6340
6341 case TagTypeKind::TTK_Union:
6342 return union_type_class;
6343 }
6344 }
David Blaikie83d382b2011-09-23 05:06:16 +00006345 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006346
6347 case Type::ConstantArray:
6348 case Type::VariableArray:
6349 case Type::IncompleteArray:
6350 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6351
6352 case Type::BlockPointer:
6353 case Type::LValueReference:
6354 case Type::RValueReference:
6355 case Type::Vector:
6356 case Type::ExtVector:
6357 case Type::Auto:
6358 case Type::ObjCObject:
6359 case Type::ObjCInterface:
6360 case Type::ObjCObjectPointer:
6361 case Type::Pipe:
6362 case Type::Atomic:
6363 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6364 }
6365
6366 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006367}
6368
Richard Smith5fab0c92011-12-28 19:48:30 +00006369/// EvaluateBuiltinConstantPForLValue - Determine the result of
6370/// __builtin_constant_p when applied to the given lvalue.
6371///
6372/// An lvalue is only "constant" if it is a pointer or reference to the first
6373/// character of a string literal.
6374template<typename LValue>
6375static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006376 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006377 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6378}
6379
6380/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6381/// GCC as we can manage.
6382static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6383 QualType ArgType = Arg->getType();
6384
6385 // __builtin_constant_p always has one operand. The rules which gcc follows
6386 // are not precisely documented, but are as follows:
6387 //
6388 // - If the operand is of integral, floating, complex or enumeration type,
6389 // and can be folded to a known value of that type, it returns 1.
6390 // - If the operand and can be folded to a pointer to the first character
6391 // of a string literal (or such a pointer cast to an integral type), it
6392 // returns 1.
6393 //
6394 // Otherwise, it returns 0.
6395 //
6396 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6397 // its support for this does not currently work.
6398 if (ArgType->isIntegralOrEnumerationType()) {
6399 Expr::EvalResult Result;
6400 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6401 return false;
6402
6403 APValue &V = Result.Val;
6404 if (V.getKind() == APValue::Int)
6405 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006406 if (V.getKind() == APValue::LValue)
6407 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006408 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6409 return Arg->isEvaluatable(Ctx);
6410 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6411 LValue LV;
6412 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006413 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006414 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6415 : EvaluatePointer(Arg, LV, Info)) &&
6416 !Status.HasSideEffects)
6417 return EvaluateBuiltinConstantPForLValue(LV);
6418 }
6419
6420 // Anything else isn't considered to be sufficiently constant.
6421 return false;
6422}
6423
John McCall95007602010-05-10 23:27:23 +00006424/// Retrieves the "underlying object type" of the given expression,
6425/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006426static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006427 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6428 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006429 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006430 } else if (const Expr *E = B.get<const Expr*>()) {
6431 if (isa<CompoundLiteralExpr>(E))
6432 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006433 }
6434
6435 return QualType();
6436}
6437
George Burgess IV3a03fab2015-09-04 21:28:13 +00006438/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006439/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6440/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006441/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6442///
6443/// Always returns an RValue with a pointer representation.
6444static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6445 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6446
6447 auto *NoParens = E->IgnoreParens();
6448 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006449 if (Cast == nullptr)
6450 return NoParens;
6451
6452 // We only conservatively allow a few kinds of casts, because this code is
6453 // inherently a simple solution that seeks to support the common case.
6454 auto CastKind = Cast->getCastKind();
6455 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6456 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006457 return NoParens;
6458
6459 auto *SubExpr = Cast->getSubExpr();
6460 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6461 return NoParens;
6462 return ignorePointerCastsAndParens(SubExpr);
6463}
6464
George Burgess IVa51c4072015-10-16 01:49:01 +00006465/// Checks to see if the given LValue's Designator is at the end of the LValue's
6466/// record layout. e.g.
6467/// struct { struct { int a, b; } fst, snd; } obj;
6468/// obj.fst // no
6469/// obj.snd // yes
6470/// obj.fst.a // no
6471/// obj.fst.b // no
6472/// obj.snd.a // no
6473/// obj.snd.b // yes
6474///
6475/// Please note: this function is specialized for how __builtin_object_size
6476/// views "objects".
6477static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6478 assert(!LVal.Designator.Invalid);
6479
6480 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6481 if (FD->getParent()->isUnion())
6482 return true;
6483 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6484 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6485 };
6486
6487 auto &Base = LVal.getLValueBase();
6488 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6489 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6490 if (!IsLastFieldDecl(FD))
6491 return false;
6492 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6493 for (auto *FD : IFD->chain())
6494 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6495 return false;
6496 }
6497 }
6498
6499 QualType BaseType = getType(Base);
6500 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6501 if (BaseType->isArrayType()) {
6502 // Because __builtin_object_size treats arrays as objects, we can ignore
6503 // the index iff this is the last array in the Designator.
6504 if (I + 1 == E)
6505 return true;
6506 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6507 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6508 if (Index + 1 != CAT->getSize())
6509 return false;
6510 BaseType = CAT->getElementType();
6511 } else if (BaseType->isAnyComplexType()) {
6512 auto *CT = BaseType->castAs<ComplexType>();
6513 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6514 if (Index != 1)
6515 return false;
6516 BaseType = CT->getElementType();
6517 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6518 if (!IsLastFieldDecl(FD))
6519 return false;
6520 BaseType = FD->getType();
6521 } else {
6522 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6523 "Expecting cast to a base class");
6524 return false;
6525 }
6526 }
6527 return true;
6528}
6529
6530/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6531static bool refersToCompleteObject(const LValue &LVal) {
6532 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6533 return false;
6534
6535 if (!LVal.InvalidBase)
6536 return true;
6537
6538 auto *E = LVal.Base.dyn_cast<const Expr *>();
6539 (void)E;
6540 assert(E != nullptr && isa<MemberExpr>(E));
6541 return false;
6542}
6543
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006544/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6545/// true and stores the result in @p Size.
6546///
6547/// If @p WasError is non-null, this will report whether the failure to evaluate
6548/// is to be treated as an Error in IntExprEvaluator.
6549static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6550 EvalInfo &Info, uint64_t &Size,
6551 bool *WasError = nullptr) {
6552 if (WasError != nullptr)
6553 *WasError = false;
6554
6555 auto Error = [&](const Expr *E) {
6556 if (WasError != nullptr)
6557 *WasError = true;
6558 return false;
6559 };
6560
6561 auto Success = [&](uint64_t S, const Expr *E) {
6562 Size = S;
6563 return true;
6564 };
6565
George Burgess IVbdb5b262015-08-19 02:19:07 +00006566 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006567 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006568 {
6569 // The operand of __builtin_object_size is never evaluated for side-effects.
6570 // If there are any, but we can determine the pointed-to object anyway, then
6571 // ignore the side-effects.
6572 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006573 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006574
6575 if (E->isGLValue()) {
6576 // It's possible for us to be given GLValues if we're called via
6577 // Expr::tryEvaluateObjectSize.
6578 APValue RVal;
6579 if (!EvaluateAsRValue(Info, E, RVal))
6580 return false;
6581 Base.setFrom(Info.Ctx, RVal);
6582 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006583 return false;
6584 }
John McCall95007602010-05-10 23:27:23 +00006585
George Burgess IVbdb5b262015-08-19 02:19:07 +00006586 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006587 // If we point to before the start of the object, there are no accessible
6588 // bytes.
6589 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006590 return Success(0, E);
6591
George Burgess IV3a03fab2015-09-04 21:28:13 +00006592 // In the case where we're not dealing with a subobject, we discard the
6593 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006594 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006595
6596 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6597 // exist. If we can't verify the base, then we can't do that.
6598 //
6599 // As a special case, we produce a valid object size for an unknown object
6600 // with a known designator if Type & 1 is 1. For instance:
6601 //
6602 // extern struct X { char buff[32]; int a, b, c; } *p;
6603 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6604 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6605 //
6606 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006607 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006608 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006609
George Burgess IVa51c4072015-10-16 01:49:01 +00006610 // If we're not examining only the subobject, then we reset to a complete
6611 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006612 //
6613 // If Type is 1 and we've lost track of the subobject, just find the complete
6614 // object instead. (If Type is 3, that's not correct behavior and we should
6615 // return 0 instead.)
6616 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006617 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006618 QualType T = getObjectType(End.getLValueBase());
6619 if (T.isNull())
6620 End.Designator.setInvalid();
6621 else {
6622 End.Designator = SubobjectDesignator(T);
6623 End.Offset = CharUnits::Zero();
6624 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006625 }
John McCall95007602010-05-10 23:27:23 +00006626
George Burgess IVbdb5b262015-08-19 02:19:07 +00006627 // If it is not possible to determine which objects ptr points to at compile
6628 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6629 // and (size_t) 0 for type 2 or 3.
6630 if (End.Designator.Invalid)
6631 return false;
6632
6633 // According to the GCC documentation, we want the size of the subobject
6634 // denoted by the pointer. But that's not quite right -- what we actually
6635 // want is the size of the immediately-enclosing array, if there is one.
6636 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006637 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006638 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6639 // We got a pointer to an array. Step to its end.
6640 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006641 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006642 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006643 // We're already pointing at the end of the object.
6644 AmountToAdd = 0;
6645 }
6646
George Burgess IV3a03fab2015-09-04 21:28:13 +00006647 QualType PointeeType = End.Designator.MostDerivedType;
6648 assert(!PointeeType.isNull());
6649 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006650 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006651
George Burgess IVbdb5b262015-08-19 02:19:07 +00006652 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6653 AmountToAdd))
6654 return false;
John McCall95007602010-05-10 23:27:23 +00006655
George Burgess IVbdb5b262015-08-19 02:19:07 +00006656 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006657
6658 // The following is a moderately common idiom in C:
6659 //
6660 // struct Foo { int a; char c[1]; };
6661 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6662 // strcpy(&F->c[0], Bar);
6663 //
6664 // So, if we see that we're examining a 1-length (or 0-length) array at the
6665 // end of a struct with an unknown base, we give up instead of breaking code
6666 // that behaves this way. Note that we only do this when Type=1, because
6667 // Type=3 is a lower bound, so answering conservatively is fine.
6668 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6669 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6670 End.Designator.MostDerivedIsArrayElement &&
6671 End.Designator.MostDerivedArraySize < 2 &&
6672 isDesignatorAtObjectEnd(Info.Ctx, End))
6673 return false;
6674
George Burgess IVbdb5b262015-08-19 02:19:07 +00006675 if (BaseOffset > EndOffset)
6676 return Success(0, E);
6677
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006678 return Success((EndOffset - BaseOffset).getQuantity(), E);
6679}
6680
6681bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6682 unsigned Type) {
6683 uint64_t Size;
6684 bool WasError;
6685 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6686 return Success(Size, E);
6687 if (WasError)
6688 return Error(E);
6689 return false;
John McCall95007602010-05-10 23:27:23 +00006690}
6691
Peter Collingbournee9200682011-05-13 03:29:01 +00006692bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006693 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006694 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006695 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006696
6697 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006698 // The type was checked when we built the expression.
6699 unsigned Type =
6700 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6701 assert(Type <= 3 && "unexpected type");
6702
6703 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006704 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006705
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006706 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006707 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006708
Richard Smith01ade172012-05-23 04:13:20 +00006709 // Expression had no side effects, but we couldn't statically determine the
6710 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006711 switch (Info.EvalMode) {
6712 case EvalInfo::EM_ConstantExpression:
6713 case EvalInfo::EM_PotentialConstantExpression:
6714 case EvalInfo::EM_ConstantFold:
6715 case EvalInfo::EM_EvaluateForOverflow:
6716 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006717 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006718 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006719 return Error(E);
6720 case EvalInfo::EM_ConstantExpressionUnevaluated:
6721 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006722 // Reduce it to a constant now.
6723 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006724 }
Mike Stump722cedf2009-10-26 18:35:08 +00006725 }
6726
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006727 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006728 case Builtin::BI__builtin_bswap32:
6729 case Builtin::BI__builtin_bswap64: {
6730 APSInt Val;
6731 if (!EvaluateInteger(E->getArg(0), Val, Info))
6732 return false;
6733
6734 return Success(Val.byteSwap(), E);
6735 }
6736
Richard Smith8889a3d2013-06-13 06:26:32 +00006737 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006738 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006739
6740 // FIXME: BI__builtin_clrsb
6741 // FIXME: BI__builtin_clrsbl
6742 // FIXME: BI__builtin_clrsbll
6743
Richard Smith80b3c8e2013-06-13 05:04:16 +00006744 case Builtin::BI__builtin_clz:
6745 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006746 case Builtin::BI__builtin_clzll:
6747 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006748 APSInt Val;
6749 if (!EvaluateInteger(E->getArg(0), Val, Info))
6750 return false;
6751 if (!Val)
6752 return Error(E);
6753
6754 return Success(Val.countLeadingZeros(), E);
6755 }
6756
Richard Smith8889a3d2013-06-13 06:26:32 +00006757 case Builtin::BI__builtin_constant_p:
6758 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6759
Richard Smith80b3c8e2013-06-13 05:04:16 +00006760 case Builtin::BI__builtin_ctz:
6761 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006762 case Builtin::BI__builtin_ctzll:
6763 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006764 APSInt Val;
6765 if (!EvaluateInteger(E->getArg(0), Val, Info))
6766 return false;
6767 if (!Val)
6768 return Error(E);
6769
6770 return Success(Val.countTrailingZeros(), E);
6771 }
6772
Richard Smith8889a3d2013-06-13 06:26:32 +00006773 case Builtin::BI__builtin_eh_return_data_regno: {
6774 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6775 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6776 return Success(Operand, E);
6777 }
6778
6779 case Builtin::BI__builtin_expect:
6780 return Visit(E->getArg(0));
6781
6782 case Builtin::BI__builtin_ffs:
6783 case Builtin::BI__builtin_ffsl:
6784 case Builtin::BI__builtin_ffsll: {
6785 APSInt Val;
6786 if (!EvaluateInteger(E->getArg(0), Val, Info))
6787 return false;
6788
6789 unsigned N = Val.countTrailingZeros();
6790 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6791 }
6792
6793 case Builtin::BI__builtin_fpclassify: {
6794 APFloat Val(0.0);
6795 if (!EvaluateFloat(E->getArg(5), Val, Info))
6796 return false;
6797 unsigned Arg;
6798 switch (Val.getCategory()) {
6799 case APFloat::fcNaN: Arg = 0; break;
6800 case APFloat::fcInfinity: Arg = 1; break;
6801 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6802 case APFloat::fcZero: Arg = 4; break;
6803 }
6804 return Visit(E->getArg(Arg));
6805 }
6806
6807 case Builtin::BI__builtin_isinf_sign: {
6808 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006809 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006810 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6811 }
6812
Richard Smithea3019d2013-10-15 19:07:14 +00006813 case Builtin::BI__builtin_isinf: {
6814 APFloat Val(0.0);
6815 return EvaluateFloat(E->getArg(0), Val, Info) &&
6816 Success(Val.isInfinity() ? 1 : 0, E);
6817 }
6818
6819 case Builtin::BI__builtin_isfinite: {
6820 APFloat Val(0.0);
6821 return EvaluateFloat(E->getArg(0), Val, Info) &&
6822 Success(Val.isFinite() ? 1 : 0, E);
6823 }
6824
6825 case Builtin::BI__builtin_isnan: {
6826 APFloat Val(0.0);
6827 return EvaluateFloat(E->getArg(0), Val, Info) &&
6828 Success(Val.isNaN() ? 1 : 0, E);
6829 }
6830
6831 case Builtin::BI__builtin_isnormal: {
6832 APFloat Val(0.0);
6833 return EvaluateFloat(E->getArg(0), Val, Info) &&
6834 Success(Val.isNormal() ? 1 : 0, E);
6835 }
6836
Richard Smith8889a3d2013-06-13 06:26:32 +00006837 case Builtin::BI__builtin_parity:
6838 case Builtin::BI__builtin_parityl:
6839 case Builtin::BI__builtin_parityll: {
6840 APSInt Val;
6841 if (!EvaluateInteger(E->getArg(0), Val, Info))
6842 return false;
6843
6844 return Success(Val.countPopulation() % 2, E);
6845 }
6846
Richard Smith80b3c8e2013-06-13 05:04:16 +00006847 case Builtin::BI__builtin_popcount:
6848 case Builtin::BI__builtin_popcountl:
6849 case Builtin::BI__builtin_popcountll: {
6850 APSInt Val;
6851 if (!EvaluateInteger(E->getArg(0), Val, Info))
6852 return false;
6853
6854 return Success(Val.countPopulation(), E);
6855 }
6856
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006857 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006858 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006859 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006860 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006861 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6862 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006863 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006864 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006865 case Builtin::BI__builtin_strlen: {
6866 // As an extension, we support __builtin_strlen() as a constant expression,
6867 // and support folding strlen() to a constant.
6868 LValue String;
6869 if (!EvaluatePointer(E->getArg(0), String, Info))
6870 return false;
6871
6872 // Fast path: if it's a string literal, search the string value.
6873 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6874 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006875 // The string literal may have embedded null characters. Find the first
6876 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006877 StringRef Str = S->getBytes();
6878 int64_t Off = String.Offset.getQuantity();
6879 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6880 S->getCharByteWidth() == 1) {
6881 Str = Str.substr(Off);
6882
6883 StringRef::size_type Pos = Str.find(0);
6884 if (Pos != StringRef::npos)
6885 Str = Str.substr(0, Pos);
6886
6887 return Success(Str.size(), E);
6888 }
6889
6890 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006891 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006892
6893 // Slow path: scan the bytes of the string looking for the terminating 0.
6894 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6895 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6896 APValue Char;
6897 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6898 !Char.isInt())
6899 return false;
6900 if (!Char.getInt())
6901 return Success(Strlen, E);
6902 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6903 return false;
6904 }
6905 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006906
Richard Smith01ba47d2012-04-13 00:45:38 +00006907 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006908 case Builtin::BI__atomic_is_lock_free:
6909 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006910 APSInt SizeVal;
6911 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6912 return false;
6913
6914 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6915 // of two less than the maximum inline atomic width, we know it is
6916 // lock-free. If the size isn't a power of two, or greater than the
6917 // maximum alignment where we promote atomics, we know it is not lock-free
6918 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6919 // the answer can only be determined at runtime; for example, 16-byte
6920 // atomics have lock-free implementations on some, but not all,
6921 // x86-64 processors.
6922
6923 // Check power-of-two.
6924 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006925 if (Size.isPowerOfTwo()) {
6926 // Check against inlining width.
6927 unsigned InlineWidthBits =
6928 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6929 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6930 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6931 Size == CharUnits::One() ||
6932 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6933 Expr::NPC_NeverValueDependent))
6934 // OK, we will inline appropriately-aligned operations of this size,
6935 // and _Atomic(T) is appropriately-aligned.
6936 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006937
Richard Smith01ba47d2012-04-13 00:45:38 +00006938 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6939 castAs<PointerType>()->getPointeeType();
6940 if (!PointeeType->isIncompleteType() &&
6941 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6942 // OK, we will inline operations on this object.
6943 return Success(1, E);
6944 }
6945 }
6946 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006947
Richard Smith01ba47d2012-04-13 00:45:38 +00006948 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6949 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006950 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006951 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006952}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006953
Richard Smith8b3497e2011-10-31 01:37:14 +00006954static bool HasSameBase(const LValue &A, const LValue &B) {
6955 if (!A.getLValueBase())
6956 return !B.getLValueBase();
6957 if (!B.getLValueBase())
6958 return false;
6959
Richard Smithce40ad62011-11-12 22:28:03 +00006960 if (A.getLValueBase().getOpaqueValue() !=
6961 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006962 const Decl *ADecl = GetLValueBaseDecl(A);
6963 if (!ADecl)
6964 return false;
6965 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006966 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006967 return false;
6968 }
6969
6970 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006971 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006972}
6973
Richard Smithd20f1e62014-10-21 23:01:04 +00006974/// \brief Determine whether this is a pointer past the end of the complete
6975/// object referred to by the lvalue.
6976static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6977 const LValue &LV) {
6978 // A null pointer can be viewed as being "past the end" but we don't
6979 // choose to look at it that way here.
6980 if (!LV.getLValueBase())
6981 return false;
6982
6983 // If the designator is valid and refers to a subobject, we're not pointing
6984 // past the end.
6985 if (!LV.getLValueDesignator().Invalid &&
6986 !LV.getLValueDesignator().isOnePastTheEnd())
6987 return false;
6988
David Majnemerc378ca52015-08-29 08:32:55 +00006989 // A pointer to an incomplete type might be past-the-end if the type's size is
6990 // zero. We cannot tell because the type is incomplete.
6991 QualType Ty = getType(LV.getLValueBase());
6992 if (Ty->isIncompleteType())
6993 return true;
6994
Richard Smithd20f1e62014-10-21 23:01:04 +00006995 // We're a past-the-end pointer if we point to the byte after the object,
6996 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006997 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006998 return LV.getLValueOffset() == Size;
6999}
7000
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007001namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007002
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007003/// \brief Data recursive integer evaluator of certain binary operators.
7004///
7005/// We use a data recursive algorithm for binary operators so that we are able
7006/// to handle extreme cases of chained binary operators without causing stack
7007/// overflow.
7008class DataRecursiveIntBinOpEvaluator {
7009 struct EvalResult {
7010 APValue Val;
7011 bool Failed;
7012
7013 EvalResult() : Failed(false) { }
7014
7015 void swap(EvalResult &RHS) {
7016 Val.swap(RHS.Val);
7017 Failed = RHS.Failed;
7018 RHS.Failed = false;
7019 }
7020 };
7021
7022 struct Job {
7023 const Expr *E;
7024 EvalResult LHSResult; // meaningful only for binary operator expression.
7025 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007026
David Blaikie73726062015-08-12 23:09:24 +00007027 Job() = default;
7028 Job(Job &&J)
7029 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
7030 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
7031 J.StoredInfo = nullptr;
7032 }
7033
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007034 void startSpeculativeEval(EvalInfo &Info) {
7035 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00007036 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007037 StoredInfo = &Info;
7038 }
7039 ~Job() {
7040 if (StoredInfo) {
7041 StoredInfo->EvalStatus = OldEvalStatus;
7042 }
7043 }
7044 private:
David Blaikie73726062015-08-12 23:09:24 +00007045 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007046 Expr::EvalStatus OldEvalStatus;
7047 };
7048
7049 SmallVector<Job, 16> Queue;
7050
7051 IntExprEvaluator &IntEval;
7052 EvalInfo &Info;
7053 APValue &FinalResult;
7054
7055public:
7056 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7057 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7058
7059 /// \brief True if \param E is a binary operator that we are going to handle
7060 /// data recursively.
7061 /// We handle binary operators that are comma, logical, or that have operands
7062 /// with integral or enumeration type.
7063 static bool shouldEnqueue(const BinaryOperator *E) {
7064 return E->getOpcode() == BO_Comma ||
7065 E->isLogicalOp() ||
7066 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7067 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007068 }
7069
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007070 bool Traverse(const BinaryOperator *E) {
7071 enqueue(E);
7072 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007073 while (!Queue.empty())
7074 process(PrevResult);
7075
7076 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007077
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007078 FinalResult.swap(PrevResult.Val);
7079 return true;
7080 }
7081
7082private:
7083 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7084 return IntEval.Success(Value, E, Result);
7085 }
7086 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7087 return IntEval.Success(Value, E, Result);
7088 }
7089 bool Error(const Expr *E) {
7090 return IntEval.Error(E);
7091 }
7092 bool Error(const Expr *E, diag::kind D) {
7093 return IntEval.Error(E, D);
7094 }
7095
7096 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7097 return Info.CCEDiag(E, D);
7098 }
7099
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007100 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7101 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007102 bool &SuppressRHSDiags);
7103
7104 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7105 const BinaryOperator *E, APValue &Result);
7106
7107 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7108 Result.Failed = !Evaluate(Result.Val, Info, E);
7109 if (Result.Failed)
7110 Result.Val = APValue();
7111 }
7112
Richard Trieuba4d0872012-03-21 23:30:30 +00007113 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007114
7115 void enqueue(const Expr *E) {
7116 E = E->IgnoreParens();
7117 Queue.resize(Queue.size()+1);
7118 Queue.back().E = E;
7119 Queue.back().Kind = Job::AnyExprKind;
7120 }
7121};
7122
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007123}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007124
7125bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007126 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007127 bool &SuppressRHSDiags) {
7128 if (E->getOpcode() == BO_Comma) {
7129 // Ignore LHS but note if we could not evaluate it.
7130 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007131 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007132 return true;
7133 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007134
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007135 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007136 bool LHSAsBool;
7137 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007138 // We were able to evaluate the LHS, see if we can get away with not
7139 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007140 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7141 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007142 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007143 }
7144 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007145 LHSResult.Failed = true;
7146
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007147 // Since we weren't able to evaluate the left hand side, it
7148 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007149 if (!Info.noteSideEffect())
7150 return false;
7151
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007152 // We can't evaluate the LHS; however, sometimes the result
7153 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7154 // Don't ignore RHS and suppress diagnostics from this arm.
7155 SuppressRHSDiags = true;
7156 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007157
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007158 return true;
7159 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007160
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007161 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7162 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007163
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007164 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007165 return false; // Ignore RHS;
7166
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007167 return true;
7168}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007169
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007170bool DataRecursiveIntBinOpEvaluator::
7171 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7172 const BinaryOperator *E, APValue &Result) {
7173 if (E->getOpcode() == BO_Comma) {
7174 if (RHSResult.Failed)
7175 return false;
7176 Result = RHSResult.Val;
7177 return true;
7178 }
7179
7180 if (E->isLogicalOp()) {
7181 bool lhsResult, rhsResult;
7182 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7183 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7184
7185 if (LHSIsOK) {
7186 if (RHSIsOK) {
7187 if (E->getOpcode() == BO_LOr)
7188 return Success(lhsResult || rhsResult, E, Result);
7189 else
7190 return Success(lhsResult && rhsResult, E, Result);
7191 }
7192 } else {
7193 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007194 // We can't evaluate the LHS; however, sometimes the result
7195 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7196 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007197 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007198 }
7199 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007200
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007201 return false;
7202 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007203
7204 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7205 E->getRHS()->getType()->isIntegralOrEnumerationType());
7206
7207 if (LHSResult.Failed || RHSResult.Failed)
7208 return false;
7209
7210 const APValue &LHSVal = LHSResult.Val;
7211 const APValue &RHSVal = RHSResult.Val;
7212
7213 // Handle cases like (unsigned long)&a + 4.
7214 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7215 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007216 CharUnits AdditionalOffset =
7217 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007218 if (E->getOpcode() == BO_Add)
7219 Result.getLValueOffset() += AdditionalOffset;
7220 else
7221 Result.getLValueOffset() -= AdditionalOffset;
7222 return true;
7223 }
7224
7225 // Handle cases like 4 + (unsigned long)&a
7226 if (E->getOpcode() == BO_Add &&
7227 RHSVal.isLValue() && LHSVal.isInt()) {
7228 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007229 Result.getLValueOffset() +=
7230 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007231 return true;
7232 }
7233
7234 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7235 // Handle (intptr_t)&&A - (intptr_t)&&B.
7236 if (!LHSVal.getLValueOffset().isZero() ||
7237 !RHSVal.getLValueOffset().isZero())
7238 return false;
7239 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7240 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7241 if (!LHSExpr || !RHSExpr)
7242 return false;
7243 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7244 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7245 if (!LHSAddrExpr || !RHSAddrExpr)
7246 return false;
7247 // Make sure both labels come from the same function.
7248 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7249 RHSAddrExpr->getLabel()->getDeclContext())
7250 return false;
7251 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7252 return true;
7253 }
Richard Smith43e77732013-05-07 04:50:00 +00007254
7255 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007256 if (!LHSVal.isInt() || !RHSVal.isInt())
7257 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007258
7259 // Set up the width and signedness manually, in case it can't be deduced
7260 // from the operation we're performing.
7261 // FIXME: Don't do this in the cases where we can deduce it.
7262 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7263 E->getType()->isUnsignedIntegerOrEnumerationType());
7264 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7265 RHSVal.getInt(), Value))
7266 return false;
7267 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007268}
7269
Richard Trieuba4d0872012-03-21 23:30:30 +00007270void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007271 Job &job = Queue.back();
7272
7273 switch (job.Kind) {
7274 case Job::AnyExprKind: {
7275 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7276 if (shouldEnqueue(Bop)) {
7277 job.Kind = Job::BinOpKind;
7278 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007279 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007280 }
7281 }
7282
7283 EvaluateExpr(job.E, Result);
7284 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007285 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007286 }
7287
7288 case Job::BinOpKind: {
7289 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007290 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007291 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007292 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007293 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007294 }
7295 if (SuppressRHSDiags)
7296 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007297 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007298 job.Kind = Job::BinOpVisitedLHSKind;
7299 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007300 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007301 }
7302
7303 case Job::BinOpVisitedLHSKind: {
7304 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7305 EvalResult RHS;
7306 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007307 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007308 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007309 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007310 }
7311 }
7312
7313 llvm_unreachable("Invalid Job::Kind!");
7314}
7315
7316bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00007317 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007318 return Error(E);
7319
7320 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7321 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007322
Anders Carlssonacc79812008-11-16 07:17:21 +00007323 QualType LHSTy = E->getLHS()->getType();
7324 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007325
Chandler Carruthb29a7432014-10-11 11:03:30 +00007326 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007327 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007328 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007329 if (E->isAssignmentOp()) {
7330 LValue LV;
7331 EvaluateLValue(E->getLHS(), LV, Info);
7332 LHSOK = false;
7333 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007334 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7335 if (LHSOK) {
7336 LHS.makeComplexFloat();
7337 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7338 }
7339 } else {
7340 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7341 }
Richard Smith253c2a32012-01-27 01:14:48 +00007342 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007343 return false;
7344
Chandler Carruthb29a7432014-10-11 11:03:30 +00007345 if (E->getRHS()->getType()->isRealFloatingType()) {
7346 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7347 return false;
7348 RHS.makeComplexFloat();
7349 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7350 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007351 return false;
7352
7353 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007354 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007355 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007356 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007357 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7358
John McCalle3027922010-08-25 11:45:40 +00007359 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007360 return Success((CR_r == APFloat::cmpEqual &&
7361 CR_i == APFloat::cmpEqual), E);
7362 else {
John McCalle3027922010-08-25 11:45:40 +00007363 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007364 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007365 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007366 CR_r == APFloat::cmpLessThan ||
7367 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007368 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007369 CR_i == APFloat::cmpLessThan ||
7370 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007371 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007372 } else {
John McCalle3027922010-08-25 11:45:40 +00007373 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007374 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7375 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7376 else {
John McCalle3027922010-08-25 11:45:40 +00007377 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007378 "Invalid compex comparison.");
7379 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7380 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7381 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007382 }
7383 }
Mike Stump11289f42009-09-09 15:08:12 +00007384
Anders Carlssonacc79812008-11-16 07:17:21 +00007385 if (LHSTy->isRealFloatingType() &&
7386 RHSTy->isRealFloatingType()) {
7387 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007388
Richard Smith253c2a32012-01-27 01:14:48 +00007389 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7390 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007391 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007392
Richard Smith253c2a32012-01-27 01:14:48 +00007393 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007395
Anders Carlssonacc79812008-11-16 07:17:21 +00007396 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007397
Anders Carlssonacc79812008-11-16 07:17:21 +00007398 switch (E->getOpcode()) {
7399 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007400 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007401 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007402 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007403 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007404 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007405 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007406 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007407 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007408 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007409 E);
John McCalle3027922010-08-25 11:45:40 +00007410 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007411 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007412 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007413 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007414 || CR == APFloat::cmpLessThan
7415 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007416 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007417 }
Mike Stump11289f42009-09-09 15:08:12 +00007418
Eli Friedmana38da572009-04-28 19:17:36 +00007419 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007420 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007421 LValue LHSValue, RHSValue;
7422
7423 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
Richard Smith0c6124b2015-12-03 01:36:22 +00007424 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007425 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007426
Richard Smith253c2a32012-01-27 01:14:48 +00007427 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007428 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007429
Richard Smith8b3497e2011-10-31 01:37:14 +00007430 // Reject differing bases from the normal codepath; we special-case
7431 // comparisons to null.
7432 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007433 if (E->getOpcode() == BO_Sub) {
7434 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007435 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007436 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007437 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007438 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007439 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007440 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007441 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7442 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7443 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007444 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007445 // Make sure both labels come from the same function.
7446 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7447 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007448 return Error(E);
7449 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007450 }
Richard Smith83c68212011-10-31 05:11:32 +00007451 // Inequalities and subtractions between unrelated pointers have
7452 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007453 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007454 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007455 // A constant address may compare equal to the address of a symbol.
7456 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007457 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007458 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7459 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007460 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007461 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007462 // distinct addresses. In clang, the result of such a comparison is
7463 // unspecified, so it is not a constant expression. However, we do know
7464 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007465 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7466 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007467 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007468 // We can't tell whether weak symbols will end up pointing to the same
7469 // object.
7470 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007471 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007472 // We can't compare the address of the start of one object with the
7473 // past-the-end address of another object, per C++ DR1652.
7474 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7475 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7476 (RHSValue.Base && RHSValue.Offset.isZero() &&
7477 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7478 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007479 // We can't tell whether an object is at the same address as another
7480 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007481 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7482 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007483 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007484 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007485 // (Note that clang defaults to -fmerge-all-constants, which can
7486 // lead to inconsistent results for comparisons involving the address
7487 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007488 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007489 }
Eli Friedman64004332009-03-23 04:38:34 +00007490
Richard Smith1b470412012-02-01 08:10:20 +00007491 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7492 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7493
Richard Smith84f6dcf2012-02-02 01:16:57 +00007494 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7495 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7496
John McCalle3027922010-08-25 11:45:40 +00007497 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007498 // C++11 [expr.add]p6:
7499 // Unless both pointers point to elements of the same array object, or
7500 // one past the last element of the array object, the behavior is
7501 // undefined.
7502 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7503 !AreElementsOfSameArray(getType(LHSValue.Base),
7504 LHSDesignator, RHSDesignator))
7505 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7506
Chris Lattner882bdf22010-04-20 17:13:14 +00007507 QualType Type = E->getLHS()->getType();
7508 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007509
Richard Smithd62306a2011-11-10 06:34:14 +00007510 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007511 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007512 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007513
Richard Smith84c6b3d2013-09-10 21:34:14 +00007514 // As an extension, a type may have zero size (empty struct or union in
7515 // C, array of zero length). Pointer subtraction in such cases has
7516 // undefined behavior, so is not constant.
7517 if (ElementSize.isZero()) {
7518 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7519 << ElementType;
7520 return false;
7521 }
7522
Richard Smith1b470412012-02-01 08:10:20 +00007523 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7524 // and produce incorrect results when it overflows. Such behavior
7525 // appears to be non-conforming, but is common, so perhaps we should
7526 // assume the standard intended for such cases to be undefined behavior
7527 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007528
Richard Smith1b470412012-02-01 08:10:20 +00007529 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7530 // overflow in the final conversion to ptrdiff_t.
7531 APSInt LHS(
7532 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7533 APSInt RHS(
7534 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7535 APSInt ElemSize(
7536 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7537 APSInt TrueResult = (LHS - RHS) / ElemSize;
7538 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7539
Richard Smith0c6124b2015-12-03 01:36:22 +00007540 if (Result.extend(65) != TrueResult &&
7541 !HandleOverflow(Info, E, TrueResult, E->getType()))
7542 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007543 return Success(Result, E);
7544 }
Richard Smithde21b242012-01-31 06:41:30 +00007545
7546 // C++11 [expr.rel]p3:
7547 // Pointers to void (after pointer conversions) can be compared, with a
7548 // result defined as follows: If both pointers represent the same
7549 // address or are both the null pointer value, the result is true if the
7550 // operator is <= or >= and false otherwise; otherwise the result is
7551 // unspecified.
7552 // We interpret this as applying to pointers to *cv* void.
7553 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007554 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007555 CCEDiag(E, diag::note_constexpr_void_comparison);
7556
Richard Smith84f6dcf2012-02-02 01:16:57 +00007557 // C++11 [expr.rel]p2:
7558 // - If two pointers point to non-static data members of the same object,
7559 // or to subobjects or array elements fo such members, recursively, the
7560 // pointer to the later declared member compares greater provided the
7561 // two members have the same access control and provided their class is
7562 // not a union.
7563 // [...]
7564 // - Otherwise pointer comparisons are unspecified.
7565 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7566 E->isRelationalOp()) {
7567 bool WasArrayIndex;
7568 unsigned Mismatch =
7569 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7570 RHSDesignator, WasArrayIndex);
7571 // At the point where the designators diverge, the comparison has a
7572 // specified value if:
7573 // - we are comparing array indices
7574 // - we are comparing fields of a union, or fields with the same access
7575 // Otherwise, the result is unspecified and thus the comparison is not a
7576 // constant expression.
7577 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7578 Mismatch < RHSDesignator.Entries.size()) {
7579 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7580 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7581 if (!LF && !RF)
7582 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7583 else if (!LF)
7584 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7585 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7586 << RF->getParent() << RF;
7587 else if (!RF)
7588 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7589 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7590 << LF->getParent() << LF;
7591 else if (!LF->getParent()->isUnion() &&
7592 LF->getAccess() != RF->getAccess())
7593 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7594 << LF << LF->getAccess() << RF << RF->getAccess()
7595 << LF->getParent();
7596 }
7597 }
7598
Eli Friedman6c31cb42012-04-16 04:30:08 +00007599 // The comparison here must be unsigned, and performed with the same
7600 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007601 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7602 uint64_t CompareLHS = LHSOffset.getQuantity();
7603 uint64_t CompareRHS = RHSOffset.getQuantity();
7604 assert(PtrSize <= 64 && "Unexpected pointer width");
7605 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7606 CompareLHS &= Mask;
7607 CompareRHS &= Mask;
7608
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007609 // If there is a base and this is a relational operator, we can only
7610 // compare pointers within the object in question; otherwise, the result
7611 // depends on where the object is located in memory.
7612 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7613 QualType BaseTy = getType(LHSValue.Base);
7614 if (BaseTy->isIncompleteType())
7615 return Error(E);
7616 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7617 uint64_t OffsetLimit = Size.getQuantity();
7618 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7619 return Error(E);
7620 }
7621
Richard Smith8b3497e2011-10-31 01:37:14 +00007622 switch (E->getOpcode()) {
7623 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007624 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7625 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7626 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7627 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7628 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7629 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007630 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007631 }
7632 }
Richard Smith7bb00672012-02-01 01:42:44 +00007633
7634 if (LHSTy->isMemberPointerType()) {
7635 assert(E->isEqualityOp() && "unexpected member pointer operation");
7636 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7637
7638 MemberPtr LHSValue, RHSValue;
7639
7640 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7641 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7642 return false;
7643
7644 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7645 return false;
7646
7647 // C++11 [expr.eq]p2:
7648 // If both operands are null, they compare equal. Otherwise if only one is
7649 // null, they compare unequal.
7650 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7651 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7652 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7653 }
7654
7655 // Otherwise if either is a pointer to a virtual member function, the
7656 // result is unspecified.
7657 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7658 if (MD->isVirtual())
7659 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7660 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7661 if (MD->isVirtual())
7662 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7663
7664 // Otherwise they compare equal if and only if they would refer to the
7665 // same member of the same most derived object or the same subobject if
7666 // they were dereferenced with a hypothetical object of the associated
7667 // class type.
7668 bool Equal = LHSValue == RHSValue;
7669 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7670 }
7671
Richard Smithab44d9b2012-02-14 22:35:28 +00007672 if (LHSTy->isNullPtrType()) {
7673 assert(E->isComparisonOp() && "unexpected nullptr operation");
7674 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7675 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7676 // are compared, the result is true of the operator is <=, >= or ==, and
7677 // false otherwise.
7678 BinaryOperator::Opcode Opcode = E->getOpcode();
7679 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7680 }
7681
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007682 assert((!LHSTy->isIntegralOrEnumerationType() ||
7683 !RHSTy->isIntegralOrEnumerationType()) &&
7684 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7685 // We can't continue from here for non-integral types.
7686 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007687}
7688
Peter Collingbournee190dee2011-03-11 19:24:49 +00007689/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7690/// a result as the expression's type.
7691bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7692 const UnaryExprOrTypeTraitExpr *E) {
7693 switch(E->getKind()) {
7694 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007695 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007696 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007697 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007698 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007699 }
Eli Friedman64004332009-03-23 04:38:34 +00007700
Peter Collingbournee190dee2011-03-11 19:24:49 +00007701 case UETT_VecStep: {
7702 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007703
Peter Collingbournee190dee2011-03-11 19:24:49 +00007704 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007705 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007706
Peter Collingbournee190dee2011-03-11 19:24:49 +00007707 // The vec_step built-in functions that take a 3-component
7708 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7709 if (n == 3)
7710 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007711
Peter Collingbournee190dee2011-03-11 19:24:49 +00007712 return Success(n, E);
7713 } else
7714 return Success(1, E);
7715 }
7716
7717 case UETT_SizeOf: {
7718 QualType SrcTy = E->getTypeOfArgument();
7719 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7720 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007721 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7722 SrcTy = Ref->getPointeeType();
7723
Richard Smithd62306a2011-11-10 06:34:14 +00007724 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007725 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007726 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007727 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007728 }
Alexey Bataev00396512015-07-02 03:40:19 +00007729 case UETT_OpenMPRequiredSimdAlign:
7730 assert(E->isArgumentType());
7731 return Success(
7732 Info.Ctx.toCharUnitsFromBits(
7733 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7734 .getQuantity(),
7735 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007736 }
7737
7738 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007739}
7740
Peter Collingbournee9200682011-05-13 03:29:01 +00007741bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007742 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007743 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007744 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007745 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007746 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007747 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007748 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007749 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007750 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007751 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007752 APSInt IdxResult;
7753 if (!EvaluateInteger(Idx, IdxResult, Info))
7754 return false;
7755 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7756 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007757 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007758 CurrentType = AT->getElementType();
7759 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7760 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007761 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007762 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007763
James Y Knight7281c352015-12-29 22:31:18 +00007764 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007765 FieldDecl *MemberDecl = ON.getField();
7766 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007767 if (!RT)
7768 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007769 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007770 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007771 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007772 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007773 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007774 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007775 CurrentType = MemberDecl->getType().getNonReferenceType();
7776 break;
7777 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007778
James Y Knight7281c352015-12-29 22:31:18 +00007779 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007780 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007781
James Y Knight7281c352015-12-29 22:31:18 +00007782 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007783 CXXBaseSpecifier *BaseSpec = ON.getBase();
7784 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007785 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007786
7787 // Find the layout of the class whose base we are looking into.
7788 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007789 if (!RT)
7790 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007791 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007792 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007793 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7794
7795 // Find the base class itself.
7796 CurrentType = BaseSpec->getType();
7797 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7798 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007799 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007800
7801 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007802 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007803 break;
7804 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007805 }
7806 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007807 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007808}
7809
Chris Lattnere13042c2008-07-11 19:10:17 +00007810bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007811 switch (E->getOpcode()) {
7812 default:
7813 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7814 // See C99 6.6p3.
7815 return Error(E);
7816 case UO_Extension:
7817 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7818 // If so, we could clear the diagnostic ID.
7819 return Visit(E->getSubExpr());
7820 case UO_Plus:
7821 // The result is just the value.
7822 return Visit(E->getSubExpr());
7823 case UO_Minus: {
7824 if (!Visit(E->getSubExpr()))
7825 return false;
7826 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007827 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007828 if (Value.isSigned() && Value.isMinSignedValue() &&
7829 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7830 E->getType()))
7831 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007832 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007833 }
7834 case UO_Not: {
7835 if (!Visit(E->getSubExpr()))
7836 return false;
7837 if (!Result.isInt()) return Error(E);
7838 return Success(~Result.getInt(), E);
7839 }
7840 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007841 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007842 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007843 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007844 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007845 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007846 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007847}
Mike Stump11289f42009-09-09 15:08:12 +00007848
Chris Lattner477c4be2008-07-12 01:15:53 +00007849/// HandleCast - This is used to evaluate implicit or explicit casts where the
7850/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007851bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7852 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007853 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007854 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007855
Eli Friedmanc757de22011-03-25 00:43:55 +00007856 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007857 case CK_BaseToDerived:
7858 case CK_DerivedToBase:
7859 case CK_UncheckedDerivedToBase:
7860 case CK_Dynamic:
7861 case CK_ToUnion:
7862 case CK_ArrayToPointerDecay:
7863 case CK_FunctionToPointerDecay:
7864 case CK_NullToPointer:
7865 case CK_NullToMemberPointer:
7866 case CK_BaseToDerivedMemberPointer:
7867 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007868 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007869 case CK_ConstructorConversion:
7870 case CK_IntegralToPointer:
7871 case CK_ToVoid:
7872 case CK_VectorSplat:
7873 case CK_IntegralToFloating:
7874 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007875 case CK_CPointerToObjCPointerCast:
7876 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007877 case CK_AnyPointerToBlockPointerCast:
7878 case CK_ObjCObjectLValueCast:
7879 case CK_FloatingRealToComplex:
7880 case CK_FloatingComplexToReal:
7881 case CK_FloatingComplexCast:
7882 case CK_FloatingComplexToIntegralComplex:
7883 case CK_IntegralRealToComplex:
7884 case CK_IntegralComplexCast:
7885 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007886 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007887 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007888 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007889 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007890 llvm_unreachable("invalid cast kind for integral value");
7891
Eli Friedman9faf2f92011-03-25 19:07:11 +00007892 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007893 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007894 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007895 case CK_ARCProduceObject:
7896 case CK_ARCConsumeObject:
7897 case CK_ARCReclaimReturnedObject:
7898 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007899 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007900 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007901
Richard Smith4ef685b2012-01-17 21:17:26 +00007902 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007903 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007904 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007905 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007906 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007907
7908 case CK_MemberPointerToBoolean:
7909 case CK_PointerToBoolean:
7910 case CK_IntegralToBoolean:
7911 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00007912 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00007913 case CK_FloatingComplexToBoolean:
7914 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007915 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007916 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007917 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00007918 uint64_t IntResult = BoolResult;
7919 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
7920 IntResult = (uint64_t)-1;
7921 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007922 }
7923
Eli Friedmanc757de22011-03-25 00:43:55 +00007924 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007925 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007926 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007927
Eli Friedman742421e2009-02-20 01:15:07 +00007928 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007929 // Allow casts of address-of-label differences if they are no-ops
7930 // or narrowing. (The narrowing case isn't actually guaranteed to
7931 // be constant-evaluatable except in some narrow cases which are hard
7932 // to detect here. We let it through on the assumption the user knows
7933 // what they are doing.)
7934 if (Result.isAddrLabelDiff())
7935 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007936 // Only allow casts of lvalues if they are lossless.
7937 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7938 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007939
Richard Smith911e1422012-01-30 22:27:01 +00007940 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7941 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007942 }
Mike Stump11289f42009-09-09 15:08:12 +00007943
Eli Friedmanc757de22011-03-25 00:43:55 +00007944 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007945 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7946
John McCall45d55e42010-05-07 21:00:08 +00007947 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007948 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007949 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007950
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007951 if (LV.getLValueBase()) {
7952 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007953 // FIXME: Allow a larger integer size than the pointer size, and allow
7954 // narrowing back down to pointer width in subsequent integral casts.
7955 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007956 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007957 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007958
Richard Smithcf74da72011-11-16 07:18:12 +00007959 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007960 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007961 return true;
7962 }
7963
Ken Dyck02990832010-01-15 12:37:54 +00007964 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7965 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007966 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007967 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007968
Eli Friedmanc757de22011-03-25 00:43:55 +00007969 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007970 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007971 if (!EvaluateComplex(SubExpr, C, Info))
7972 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007973 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007974 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007975
Eli Friedmanc757de22011-03-25 00:43:55 +00007976 case CK_FloatingToIntegral: {
7977 APFloat F(0.0);
7978 if (!EvaluateFloat(SubExpr, F, Info))
7979 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007980
Richard Smith357362d2011-12-13 06:39:58 +00007981 APSInt Value;
7982 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7983 return false;
7984 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007985 }
7986 }
Mike Stump11289f42009-09-09 15:08:12 +00007987
Eli Friedmanc757de22011-03-25 00:43:55 +00007988 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007989}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007990
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007991bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7992 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007993 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007994 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7995 return false;
7996 if (!LV.isComplexInt())
7997 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007998 return Success(LV.getComplexIntReal(), E);
7999 }
8000
8001 return Visit(E->getSubExpr());
8002}
8003
Eli Friedman4e7a2412009-02-27 04:45:43 +00008004bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008005 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008006 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008007 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8008 return false;
8009 if (!LV.isComplexInt())
8010 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008011 return Success(LV.getComplexIntImag(), E);
8012 }
8013
Richard Smith4a678122011-10-24 18:44:57 +00008014 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008015 return Success(0, E);
8016}
8017
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008018bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8019 return Success(E->getPackLength(), E);
8020}
8021
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008022bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8023 return Success(E->getValue(), E);
8024}
8025
Chris Lattner05706e882008-07-11 18:11:29 +00008026//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008027// Float Evaluation
8028//===----------------------------------------------------------------------===//
8029
8030namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008031class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008032 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008033 APFloat &Result;
8034public:
8035 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008036 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008037
Richard Smith2e312c82012-03-03 22:46:17 +00008038 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008039 Result = V.getFloat();
8040 return true;
8041 }
Eli Friedman24c01542008-08-22 00:06:13 +00008042
Richard Smithfddd3842011-12-30 21:15:51 +00008043 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008044 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8045 return true;
8046 }
8047
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008048 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008049
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008050 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008051 bool VisitBinaryOperator(const BinaryOperator *E);
8052 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008053 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008054
John McCallb1fb0d32010-05-07 22:08:54 +00008055 bool VisitUnaryReal(const UnaryOperator *E);
8056 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008057
Richard Smithfddd3842011-12-30 21:15:51 +00008058 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008059};
8060} // end anonymous namespace
8061
8062static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008063 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008064 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008065}
8066
Jay Foad39c79802011-01-12 09:06:06 +00008067static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008068 QualType ResultTy,
8069 const Expr *Arg,
8070 bool SNaN,
8071 llvm::APFloat &Result) {
8072 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8073 if (!S) return false;
8074
8075 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8076
8077 llvm::APInt fill;
8078
8079 // Treat empty strings as if they were zero.
8080 if (S->getString().empty())
8081 fill = llvm::APInt(32, 0);
8082 else if (S->getString().getAsInteger(0, fill))
8083 return false;
8084
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008085 if (Context.getTargetInfo().isNan2008()) {
8086 if (SNaN)
8087 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8088 else
8089 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8090 } else {
8091 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8092 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8093 // a different encoding to what became a standard in 2008, and for pre-
8094 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8095 // sNaN. This is now known as "legacy NaN" encoding.
8096 if (SNaN)
8097 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8098 else
8099 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8100 }
8101
John McCall16291492010-02-28 13:00:19 +00008102 return true;
8103}
8104
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008105bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008106 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008107 default:
8108 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8109
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008110 case Builtin::BI__builtin_huge_val:
8111 case Builtin::BI__builtin_huge_valf:
8112 case Builtin::BI__builtin_huge_vall:
8113 case Builtin::BI__builtin_inf:
8114 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008115 case Builtin::BI__builtin_infl: {
8116 const llvm::fltSemantics &Sem =
8117 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008118 Result = llvm::APFloat::getInf(Sem);
8119 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008120 }
Mike Stump11289f42009-09-09 15:08:12 +00008121
John McCall16291492010-02-28 13:00:19 +00008122 case Builtin::BI__builtin_nans:
8123 case Builtin::BI__builtin_nansf:
8124 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008125 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8126 true, Result))
8127 return Error(E);
8128 return true;
John McCall16291492010-02-28 13:00:19 +00008129
Chris Lattner0b7282e2008-10-06 06:31:58 +00008130 case Builtin::BI__builtin_nan:
8131 case Builtin::BI__builtin_nanf:
8132 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008133 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008134 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008135 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8136 false, Result))
8137 return Error(E);
8138 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008139
8140 case Builtin::BI__builtin_fabs:
8141 case Builtin::BI__builtin_fabsf:
8142 case Builtin::BI__builtin_fabsl:
8143 if (!EvaluateFloat(E->getArg(0), Result, Info))
8144 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008145
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008146 if (Result.isNegative())
8147 Result.changeSign();
8148 return true;
8149
Richard Smith8889a3d2013-06-13 06:26:32 +00008150 // FIXME: Builtin::BI__builtin_powi
8151 // FIXME: Builtin::BI__builtin_powif
8152 // FIXME: Builtin::BI__builtin_powil
8153
Mike Stump11289f42009-09-09 15:08:12 +00008154 case Builtin::BI__builtin_copysign:
8155 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008156 case Builtin::BI__builtin_copysignl: {
8157 APFloat RHS(0.);
8158 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8159 !EvaluateFloat(E->getArg(1), RHS, Info))
8160 return false;
8161 Result.copySign(RHS);
8162 return true;
8163 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008164 }
8165}
8166
John McCallb1fb0d32010-05-07 22:08:54 +00008167bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008168 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8169 ComplexValue CV;
8170 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8171 return false;
8172 Result = CV.FloatReal;
8173 return true;
8174 }
8175
8176 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008177}
8178
8179bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008180 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8181 ComplexValue CV;
8182 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8183 return false;
8184 Result = CV.FloatImag;
8185 return true;
8186 }
8187
Richard Smith4a678122011-10-24 18:44:57 +00008188 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008189 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8190 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008191 return true;
8192}
8193
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008194bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008195 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008196 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008197 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008198 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008199 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008200 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8201 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008202 Result.changeSign();
8203 return true;
8204 }
8205}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008206
Eli Friedman24c01542008-08-22 00:06:13 +00008207bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008208 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8209 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008210
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008211 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008212 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8213 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008214 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008215 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8216 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008217}
8218
8219bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8220 Result = E->getValue();
8221 return true;
8222}
8223
Peter Collingbournee9200682011-05-13 03:29:01 +00008224bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8225 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008226
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008227 switch (E->getCastKind()) {
8228 default:
Richard Smith11562c52011-10-28 17:51:58 +00008229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008230
8231 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008232 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008233 return EvaluateInteger(SubExpr, IntResult, Info) &&
8234 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8235 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008236 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008237
8238 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008239 if (!Visit(SubExpr))
8240 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008241 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8242 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008243 }
John McCalld7646252010-11-14 08:17:51 +00008244
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008245 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008246 ComplexValue V;
8247 if (!EvaluateComplex(SubExpr, V, Info))
8248 return false;
8249 Result = V.getComplexFloatReal();
8250 return true;
8251 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008252 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008253}
8254
Eli Friedman24c01542008-08-22 00:06:13 +00008255//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008256// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008257//===----------------------------------------------------------------------===//
8258
8259namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008260class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008261 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008262 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008263
Anders Carlsson537969c2008-11-16 20:27:53 +00008264public:
John McCall93d91dc2010-05-07 17:22:02 +00008265 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008266 : ExprEvaluatorBaseTy(info), Result(Result) {}
8267
Richard Smith2e312c82012-03-03 22:46:17 +00008268 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008269 Result.setFrom(V);
8270 return true;
8271 }
Mike Stump11289f42009-09-09 15:08:12 +00008272
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008273 bool ZeroInitialization(const Expr *E);
8274
Anders Carlsson537969c2008-11-16 20:27:53 +00008275 //===--------------------------------------------------------------------===//
8276 // Visitor Methods
8277 //===--------------------------------------------------------------------===//
8278
Peter Collingbournee9200682011-05-13 03:29:01 +00008279 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008280 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008281 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008282 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008283 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008284};
8285} // end anonymous namespace
8286
John McCall93d91dc2010-05-07 17:22:02 +00008287static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8288 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008289 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008290 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008291}
8292
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008293bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008294 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008295 if (ElemTy->isRealFloatingType()) {
8296 Result.makeComplexFloat();
8297 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8298 Result.FloatReal = Zero;
8299 Result.FloatImag = Zero;
8300 } else {
8301 Result.makeComplexInt();
8302 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8303 Result.IntReal = Zero;
8304 Result.IntImag = Zero;
8305 }
8306 return true;
8307}
8308
Peter Collingbournee9200682011-05-13 03:29:01 +00008309bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8310 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008311
8312 if (SubExpr->getType()->isRealFloatingType()) {
8313 Result.makeComplexFloat();
8314 APFloat &Imag = Result.FloatImag;
8315 if (!EvaluateFloat(SubExpr, Imag, Info))
8316 return false;
8317
8318 Result.FloatReal = APFloat(Imag.getSemantics());
8319 return true;
8320 } else {
8321 assert(SubExpr->getType()->isIntegerType() &&
8322 "Unexpected imaginary literal.");
8323
8324 Result.makeComplexInt();
8325 APSInt &Imag = Result.IntImag;
8326 if (!EvaluateInteger(SubExpr, Imag, Info))
8327 return false;
8328
8329 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8330 return true;
8331 }
8332}
8333
Peter Collingbournee9200682011-05-13 03:29:01 +00008334bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008335
John McCallfcef3cf2010-12-14 17:51:41 +00008336 switch (E->getCastKind()) {
8337 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008338 case CK_BaseToDerived:
8339 case CK_DerivedToBase:
8340 case CK_UncheckedDerivedToBase:
8341 case CK_Dynamic:
8342 case CK_ToUnion:
8343 case CK_ArrayToPointerDecay:
8344 case CK_FunctionToPointerDecay:
8345 case CK_NullToPointer:
8346 case CK_NullToMemberPointer:
8347 case CK_BaseToDerivedMemberPointer:
8348 case CK_DerivedToBaseMemberPointer:
8349 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008350 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008351 case CK_ConstructorConversion:
8352 case CK_IntegralToPointer:
8353 case CK_PointerToIntegral:
8354 case CK_PointerToBoolean:
8355 case CK_ToVoid:
8356 case CK_VectorSplat:
8357 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008358 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008359 case CK_IntegralToBoolean:
8360 case CK_IntegralToFloating:
8361 case CK_FloatingToIntegral:
8362 case CK_FloatingToBoolean:
8363 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008364 case CK_CPointerToObjCPointerCast:
8365 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008366 case CK_AnyPointerToBlockPointerCast:
8367 case CK_ObjCObjectLValueCast:
8368 case CK_FloatingComplexToReal:
8369 case CK_FloatingComplexToBoolean:
8370 case CK_IntegralComplexToReal:
8371 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008372 case CK_ARCProduceObject:
8373 case CK_ARCConsumeObject:
8374 case CK_ARCReclaimReturnedObject:
8375 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008376 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008377 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008378 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008379 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008380 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008381 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008382
John McCallfcef3cf2010-12-14 17:51:41 +00008383 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008384 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008385 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008386 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008387
8388 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008389 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008390 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008391 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008392
8393 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008394 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008395 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008396 return false;
8397
John McCallfcef3cf2010-12-14 17:51:41 +00008398 Result.makeComplexFloat();
8399 Result.FloatImag = APFloat(Real.getSemantics());
8400 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008401 }
8402
John McCallfcef3cf2010-12-14 17:51:41 +00008403 case CK_FloatingComplexCast: {
8404 if (!Visit(E->getSubExpr()))
8405 return false;
8406
8407 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8408 QualType From
8409 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8410
Richard Smith357362d2011-12-13 06:39:58 +00008411 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8412 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008413 }
8414
8415 case CK_FloatingComplexToIntegralComplex: {
8416 if (!Visit(E->getSubExpr()))
8417 return false;
8418
8419 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8420 QualType From
8421 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8422 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008423 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8424 To, Result.IntReal) &&
8425 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8426 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008427 }
8428
8429 case CK_IntegralRealToComplex: {
8430 APSInt &Real = Result.IntReal;
8431 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8432 return false;
8433
8434 Result.makeComplexInt();
8435 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8436 return true;
8437 }
8438
8439 case CK_IntegralComplexCast: {
8440 if (!Visit(E->getSubExpr()))
8441 return false;
8442
8443 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8444 QualType From
8445 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8446
Richard Smith911e1422012-01-30 22:27:01 +00008447 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8448 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008449 return true;
8450 }
8451
8452 case CK_IntegralComplexToFloatingComplex: {
8453 if (!Visit(E->getSubExpr()))
8454 return false;
8455
Ted Kremenek28831752012-08-23 20:46:57 +00008456 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008457 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008458 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008459 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008460 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8461 To, Result.FloatReal) &&
8462 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8463 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008464 }
8465 }
8466
8467 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008468}
8469
John McCall93d91dc2010-05-07 17:22:02 +00008470bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008471 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008472 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8473
Chandler Carrutha216cad2014-10-11 00:57:18 +00008474 // Track whether the LHS or RHS is real at the type system level. When this is
8475 // the case we can simplify our evaluation strategy.
8476 bool LHSReal = false, RHSReal = false;
8477
8478 bool LHSOK;
8479 if (E->getLHS()->getType()->isRealFloatingType()) {
8480 LHSReal = true;
8481 APFloat &Real = Result.FloatReal;
8482 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8483 if (LHSOK) {
8484 Result.makeComplexFloat();
8485 Result.FloatImag = APFloat(Real.getSemantics());
8486 }
8487 } else {
8488 LHSOK = Visit(E->getLHS());
8489 }
Richard Smith253c2a32012-01-27 01:14:48 +00008490 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008491 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008492
John McCall93d91dc2010-05-07 17:22:02 +00008493 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008494 if (E->getRHS()->getType()->isRealFloatingType()) {
8495 RHSReal = true;
8496 APFloat &Real = RHS.FloatReal;
8497 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8498 return false;
8499 RHS.makeComplexFloat();
8500 RHS.FloatImag = APFloat(Real.getSemantics());
8501 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008502 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008503
Chandler Carrutha216cad2014-10-11 00:57:18 +00008504 assert(!(LHSReal && RHSReal) &&
8505 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008506 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008507 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008508 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008509 if (Result.isComplexFloat()) {
8510 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8511 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008512 if (LHSReal)
8513 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8514 else if (!RHSReal)
8515 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8516 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008517 } else {
8518 Result.getComplexIntReal() += RHS.getComplexIntReal();
8519 Result.getComplexIntImag() += RHS.getComplexIntImag();
8520 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008521 break;
John McCalle3027922010-08-25 11:45:40 +00008522 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008523 if (Result.isComplexFloat()) {
8524 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8525 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008526 if (LHSReal) {
8527 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8528 Result.getComplexFloatImag().changeSign();
8529 } else if (!RHSReal) {
8530 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8531 APFloat::rmNearestTiesToEven);
8532 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008533 } else {
8534 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8535 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8536 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008537 break;
John McCalle3027922010-08-25 11:45:40 +00008538 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008539 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008540 // This is an implementation of complex multiplication according to the
8541 // constraints laid out in C11 Annex G. The implemantion uses the
8542 // following naming scheme:
8543 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008544 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008545 APFloat &A = LHS.getComplexFloatReal();
8546 APFloat &B = LHS.getComplexFloatImag();
8547 APFloat &C = RHS.getComplexFloatReal();
8548 APFloat &D = RHS.getComplexFloatImag();
8549 APFloat &ResR = Result.getComplexFloatReal();
8550 APFloat &ResI = Result.getComplexFloatImag();
8551 if (LHSReal) {
8552 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8553 ResR = A * C;
8554 ResI = A * D;
8555 } else if (RHSReal) {
8556 ResR = C * A;
8557 ResI = C * B;
8558 } else {
8559 // In the fully general case, we need to handle NaNs and infinities
8560 // robustly.
8561 APFloat AC = A * C;
8562 APFloat BD = B * D;
8563 APFloat AD = A * D;
8564 APFloat BC = B * C;
8565 ResR = AC - BD;
8566 ResI = AD + BC;
8567 if (ResR.isNaN() && ResI.isNaN()) {
8568 bool Recalc = false;
8569 if (A.isInfinity() || B.isInfinity()) {
8570 A = APFloat::copySign(
8571 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8572 B = APFloat::copySign(
8573 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8574 if (C.isNaN())
8575 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8576 if (D.isNaN())
8577 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8578 Recalc = true;
8579 }
8580 if (C.isInfinity() || D.isInfinity()) {
8581 C = APFloat::copySign(
8582 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8583 D = APFloat::copySign(
8584 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8585 if (A.isNaN())
8586 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8587 if (B.isNaN())
8588 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8589 Recalc = true;
8590 }
8591 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8592 AD.isInfinity() || BC.isInfinity())) {
8593 if (A.isNaN())
8594 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8595 if (B.isNaN())
8596 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8597 if (C.isNaN())
8598 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8599 if (D.isNaN())
8600 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8601 Recalc = true;
8602 }
8603 if (Recalc) {
8604 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8605 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8606 }
8607 }
8608 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008609 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008610 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008611 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008612 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8613 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008614 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008615 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8616 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8617 }
8618 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008619 case BO_Div:
8620 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008621 // This is an implementation of complex division according to the
8622 // constraints laid out in C11 Annex G. The implemantion uses the
8623 // following naming scheme:
8624 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008625 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008626 APFloat &A = LHS.getComplexFloatReal();
8627 APFloat &B = LHS.getComplexFloatImag();
8628 APFloat &C = RHS.getComplexFloatReal();
8629 APFloat &D = RHS.getComplexFloatImag();
8630 APFloat &ResR = Result.getComplexFloatReal();
8631 APFloat &ResI = Result.getComplexFloatImag();
8632 if (RHSReal) {
8633 ResR = A / C;
8634 ResI = B / C;
8635 } else {
8636 if (LHSReal) {
8637 // No real optimizations we can do here, stub out with zero.
8638 B = APFloat::getZero(A.getSemantics());
8639 }
8640 int DenomLogB = 0;
8641 APFloat MaxCD = maxnum(abs(C), abs(D));
8642 if (MaxCD.isFinite()) {
8643 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008644 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8645 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008646 }
8647 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008648 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8649 APFloat::rmNearestTiesToEven);
8650 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8651 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008652 if (ResR.isNaN() && ResI.isNaN()) {
8653 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8654 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8655 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8656 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8657 D.isFinite()) {
8658 A = APFloat::copySign(
8659 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8660 B = APFloat::copySign(
8661 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8662 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8663 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8664 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8665 C = APFloat::copySign(
8666 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8667 D = APFloat::copySign(
8668 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8669 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8670 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8671 }
8672 }
8673 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008674 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008675 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8676 return Error(E, diag::note_expr_divide_by_zero);
8677
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008678 ComplexValue LHS = Result;
8679 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8680 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8681 Result.getComplexIntReal() =
8682 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8683 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8684 Result.getComplexIntImag() =
8685 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8686 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8687 }
8688 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008689 }
8690
John McCall93d91dc2010-05-07 17:22:02 +00008691 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008692}
8693
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008694bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8695 // Get the operand value into 'Result'.
8696 if (!Visit(E->getSubExpr()))
8697 return false;
8698
8699 switch (E->getOpcode()) {
8700 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008701 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008702 case UO_Extension:
8703 return true;
8704 case UO_Plus:
8705 // The result is always just the subexpr.
8706 return true;
8707 case UO_Minus:
8708 if (Result.isComplexFloat()) {
8709 Result.getComplexFloatReal().changeSign();
8710 Result.getComplexFloatImag().changeSign();
8711 }
8712 else {
8713 Result.getComplexIntReal() = -Result.getComplexIntReal();
8714 Result.getComplexIntImag() = -Result.getComplexIntImag();
8715 }
8716 return true;
8717 case UO_Not:
8718 if (Result.isComplexFloat())
8719 Result.getComplexFloatImag().changeSign();
8720 else
8721 Result.getComplexIntImag() = -Result.getComplexIntImag();
8722 return true;
8723 }
8724}
8725
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008726bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8727 if (E->getNumInits() == 2) {
8728 if (E->getType()->isComplexType()) {
8729 Result.makeComplexFloat();
8730 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8731 return false;
8732 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8733 return false;
8734 } else {
8735 Result.makeComplexInt();
8736 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8737 return false;
8738 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8739 return false;
8740 }
8741 return true;
8742 }
8743 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8744}
8745
Anders Carlsson537969c2008-11-16 20:27:53 +00008746//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008747// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8748// implicit conversion.
8749//===----------------------------------------------------------------------===//
8750
8751namespace {
8752class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008753 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008754 APValue &Result;
8755public:
8756 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8757 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8758
8759 bool Success(const APValue &V, const Expr *E) {
8760 Result = V;
8761 return true;
8762 }
8763
8764 bool ZeroInitialization(const Expr *E) {
8765 ImplicitValueInitExpr VIE(
8766 E->getType()->castAs<AtomicType>()->getValueType());
8767 return Evaluate(Result, Info, &VIE);
8768 }
8769
8770 bool VisitCastExpr(const CastExpr *E) {
8771 switch (E->getCastKind()) {
8772 default:
8773 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8774 case CK_NonAtomicToAtomic:
8775 return Evaluate(Result, Info, E->getSubExpr());
8776 }
8777 }
8778};
8779} // end anonymous namespace
8780
8781static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8782 assert(E->isRValue() && E->getType()->isAtomicType());
8783 return AtomicExprEvaluator(Info, Result).Visit(E);
8784}
8785
8786//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008787// Void expression evaluation, primarily for a cast to void on the LHS of a
8788// comma operator
8789//===----------------------------------------------------------------------===//
8790
8791namespace {
8792class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008793 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008794public:
8795 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8796
Richard Smith2e312c82012-03-03 22:46:17 +00008797 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008798
8799 bool VisitCastExpr(const CastExpr *E) {
8800 switch (E->getCastKind()) {
8801 default:
8802 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8803 case CK_ToVoid:
8804 VisitIgnoredValue(E->getSubExpr());
8805 return true;
8806 }
8807 }
Hal Finkela8443c32014-07-17 14:49:58 +00008808
8809 bool VisitCallExpr(const CallExpr *E) {
8810 switch (E->getBuiltinCallee()) {
8811 default:
8812 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8813 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008814 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008815 // The argument is not evaluated!
8816 return true;
8817 }
8818 }
Richard Smith42d3af92011-12-07 00:43:50 +00008819};
8820} // end anonymous namespace
8821
8822static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8823 assert(E->isRValue() && E->getType()->isVoidType());
8824 return VoidExprEvaluator(Info).Visit(E);
8825}
8826
8827//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008828// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008829//===----------------------------------------------------------------------===//
8830
Richard Smith2e312c82012-03-03 22:46:17 +00008831static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008832 // In C, function designators are not lvalues, but we evaluate them as if they
8833 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008834 QualType T = E->getType();
8835 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008836 LValue LV;
8837 if (!EvaluateLValue(E, LV, Info))
8838 return false;
8839 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008840 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008841 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008842 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008843 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008844 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008845 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008846 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008847 LValue LV;
8848 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008849 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008850 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008851 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008852 llvm::APFloat F(0.0);
8853 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008854 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008855 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008856 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008857 ComplexValue C;
8858 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008859 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008860 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008861 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008862 MemberPtr P;
8863 if (!EvaluateMemberPointer(E, P, Info))
8864 return false;
8865 P.moveInto(Result);
8866 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008867 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008868 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008869 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008870 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8871 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008872 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008873 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008874 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008875 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008876 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008877 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8878 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008879 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008880 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008881 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008882 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008883 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008884 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008885 if (!EvaluateVoid(E, Info))
8886 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008887 } else if (T->isAtomicType()) {
8888 if (!EvaluateAtomic(E, Result, Info))
8889 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008890 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008891 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008892 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008893 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008894 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008895 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008896 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008897
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008898 return true;
8899}
8900
Richard Smithb228a862012-02-15 02:18:13 +00008901/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8902/// cases, the in-place evaluation is essential, since later initializers for
8903/// an object can indirectly refer to subobjects which were initialized earlier.
8904static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008905 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008906 assert(!E->isValueDependent());
8907
Richard Smith7525ff62013-05-09 07:14:00 +00008908 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008909 return false;
8910
8911 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008912 // Evaluate arrays and record types in-place, so that later initializers can
8913 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008914 if (E->getType()->isArrayType())
8915 return EvaluateArray(E, This, Result, Info);
8916 else if (E->getType()->isRecordType())
8917 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008918 }
8919
8920 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008921 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008922}
8923
Richard Smithf57d8cb2011-12-09 22:58:01 +00008924/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8925/// lvalue-to-rvalue cast if it is an lvalue.
8926static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008927 if (E->getType().isNull())
8928 return false;
8929
Richard Smithfddd3842011-12-30 21:15:51 +00008930 if (!CheckLiteralType(Info, E))
8931 return false;
8932
Richard Smith2e312c82012-03-03 22:46:17 +00008933 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008934 return false;
8935
8936 if (E->isGLValue()) {
8937 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008938 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008939 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008940 return false;
8941 }
8942
Richard Smith2e312c82012-03-03 22:46:17 +00008943 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008944 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008945}
Richard Smith11562c52011-10-28 17:51:58 +00008946
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008947static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8948 const ASTContext &Ctx, bool &IsConst) {
8949 // Fast-path evaluations of integer literals, since we sometimes see files
8950 // containing vast quantities of these.
8951 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8952 Result.Val = APValue(APSInt(L->getValue(),
8953 L->getType()->isUnsignedIntegerType()));
8954 IsConst = true;
8955 return true;
8956 }
James Dennett0492ef02014-03-14 17:44:10 +00008957
8958 // This case should be rare, but we need to check it before we check on
8959 // the type below.
8960 if (Exp->getType().isNull()) {
8961 IsConst = false;
8962 return true;
8963 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008964
8965 // FIXME: Evaluating values of large array and record types can cause
8966 // performance problems. Only do so in C++11 for now.
8967 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8968 Exp->getType()->isRecordType()) &&
8969 !Ctx.getLangOpts().CPlusPlus11) {
8970 IsConst = false;
8971 return true;
8972 }
8973 return false;
8974}
8975
8976
Richard Smith7b553f12011-10-29 00:50:52 +00008977/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008978/// any crazy technique (that has nothing to do with language standards) that
8979/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008980/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8981/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008982bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008983 bool IsConst;
8984 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8985 return IsConst;
8986
Richard Smith6d4c6582013-11-05 22:18:15 +00008987 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008988 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008989}
8990
Jay Foad39c79802011-01-12 09:06:06 +00008991bool Expr::EvaluateAsBooleanCondition(bool &Result,
8992 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008993 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008994 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008995 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008996}
8997
Richard Smithce8eca52015-12-08 03:21:47 +00008998static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
8999 Expr::SideEffectsKind SEK) {
9000 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9001 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9002}
9003
Richard Smith5fab0c92011-12-28 19:48:30 +00009004bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9005 SideEffectsKind AllowSideEffects) const {
9006 if (!getType()->isIntegralOrEnumerationType())
9007 return false;
9008
Richard Smith11562c52011-10-28 17:51:58 +00009009 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009010 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009011 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009012 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009013
Richard Smith11562c52011-10-28 17:51:58 +00009014 Result = ExprResult.Val.getInt();
9015 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009016}
9017
Richard Trieube234c32016-04-21 21:04:55 +00009018bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9019 SideEffectsKind AllowSideEffects) const {
9020 if (!getType()->isRealFloatingType())
9021 return false;
9022
9023 EvalResult ExprResult;
9024 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9025 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9026 return false;
9027
9028 Result = ExprResult.Val.getFloat();
9029 return true;
9030}
9031
Jay Foad39c79802011-01-12 09:06:06 +00009032bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009033 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009034
John McCall45d55e42010-05-07 21:00:08 +00009035 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009036 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9037 !CheckLValueConstantExpression(Info, getExprLoc(),
9038 Ctx.getLValueReferenceType(getType()), LV))
9039 return false;
9040
Richard Smith2e312c82012-03-03 22:46:17 +00009041 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009042 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009043}
9044
Richard Smithd0b4dd62011-12-19 06:19:21 +00009045bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9046 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009047 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009048 // FIXME: Evaluating initializers for large array and record types can cause
9049 // performance problems. Only do so in C++11 for now.
9050 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009051 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009052 return false;
9053
Richard Smithd0b4dd62011-12-19 06:19:21 +00009054 Expr::EvalStatus EStatus;
9055 EStatus.Diag = &Notes;
9056
Richard Smith0c6124b2015-12-03 01:36:22 +00009057 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9058 ? EvalInfo::EM_ConstantExpression
9059 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009060 InitInfo.setEvaluatingDecl(VD, Value);
9061
9062 LValue LVal;
9063 LVal.set(VD);
9064
Richard Smithfddd3842011-12-30 21:15:51 +00009065 // C++11 [basic.start.init]p2:
9066 // Variables with static storage duration or thread storage duration shall be
9067 // zero-initialized before any other initialization takes place.
9068 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009069 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009070 !VD->getType()->isReferenceType()) {
9071 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009072 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009073 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009074 return false;
9075 }
9076
Richard Smith7525ff62013-05-09 07:14:00 +00009077 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9078 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009079 EStatus.HasSideEffects)
9080 return false;
9081
9082 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9083 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009084}
9085
Richard Smith7b553f12011-10-29 00:50:52 +00009086/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9087/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009088bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009089 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009090 return EvaluateAsRValue(Result, Ctx) &&
9091 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009092}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009093
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009094APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009095 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009096 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009097 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009098 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009099 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009100 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009101 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009102
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009103 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009104}
John McCall864e3962010-05-07 05:32:02 +00009105
Richard Smithe9ff7702013-11-05 22:23:30 +00009106void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009107 bool IsConst;
9108 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009109 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009110 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009111 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9112 }
9113}
9114
Richard Smithe6c01442013-06-05 00:46:14 +00009115bool Expr::EvalResult::isGlobalLValue() const {
9116 assert(Val.isLValue());
9117 return IsGlobalLValue(Val.getLValueBase());
9118}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009119
9120
John McCall864e3962010-05-07 05:32:02 +00009121/// isIntegerConstantExpr - this recursive routine will test if an expression is
9122/// an integer constant expression.
9123
9124/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9125/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009126
9127// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009128// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9129// and a (possibly null) SourceLocation indicating the location of the problem.
9130//
John McCall864e3962010-05-07 05:32:02 +00009131// Note that to reduce code duplication, this helper does no evaluation
9132// itself; the caller checks whether the expression is evaluatable, and
9133// in the rare cases where CheckICE actually cares about the evaluated
9134// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009135
Dan Gohman28ade552010-07-26 21:25:24 +00009136namespace {
9137
Richard Smith9e575da2012-12-28 13:25:52 +00009138enum ICEKind {
9139 /// This expression is an ICE.
9140 IK_ICE,
9141 /// This expression is not an ICE, but if it isn't evaluated, it's
9142 /// a legal subexpression for an ICE. This return value is used to handle
9143 /// the comma operator in C99 mode, and non-constant subexpressions.
9144 IK_ICEIfUnevaluated,
9145 /// This expression is not an ICE, and is not a legal subexpression for one.
9146 IK_NotICE
9147};
9148
John McCall864e3962010-05-07 05:32:02 +00009149struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009150 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009151 SourceLocation Loc;
9152
Richard Smith9e575da2012-12-28 13:25:52 +00009153 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009154};
9155
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009156}
Dan Gohman28ade552010-07-26 21:25:24 +00009157
Richard Smith9e575da2012-12-28 13:25:52 +00009158static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9159
9160static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009161
Craig Toppera31a8822013-08-22 07:09:37 +00009162static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009163 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009164 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009165 !EVResult.Val.isInt())
9166 return ICEDiag(IK_NotICE, E->getLocStart());
9167
John McCall864e3962010-05-07 05:32:02 +00009168 return NoDiag();
9169}
9170
Craig Toppera31a8822013-08-22 07:09:37 +00009171static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009172 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009173 if (!E->getType()->isIntegralOrEnumerationType())
9174 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009175
9176 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009177#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009178#define STMT(Node, Base) case Expr::Node##Class:
9179#define EXPR(Node, Base)
9180#include "clang/AST/StmtNodes.inc"
9181 case Expr::PredefinedExprClass:
9182 case Expr::FloatingLiteralClass:
9183 case Expr::ImaginaryLiteralClass:
9184 case Expr::StringLiteralClass:
9185 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009186 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009187 case Expr::MemberExprClass:
9188 case Expr::CompoundAssignOperatorClass:
9189 case Expr::CompoundLiteralExprClass:
9190 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009191 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009192 case Expr::NoInitExprClass:
9193 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009194 case Expr::ImplicitValueInitExprClass:
9195 case Expr::ParenListExprClass:
9196 case Expr::VAArgExprClass:
9197 case Expr::AddrLabelExprClass:
9198 case Expr::StmtExprClass:
9199 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009200 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009201 case Expr::CXXDynamicCastExprClass:
9202 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009203 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009204 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009205 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009206 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009207 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009208 case Expr::CXXThisExprClass:
9209 case Expr::CXXThrowExprClass:
9210 case Expr::CXXNewExprClass:
9211 case Expr::CXXDeleteExprClass:
9212 case Expr::CXXPseudoDestructorExprClass:
9213 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009214 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009215 case Expr::DependentScopeDeclRefExprClass:
9216 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009217 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009218 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009219 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009220 case Expr::CXXTemporaryObjectExprClass:
9221 case Expr::CXXUnresolvedConstructExprClass:
9222 case Expr::CXXDependentScopeMemberExprClass:
9223 case Expr::UnresolvedMemberExprClass:
9224 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009225 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009226 case Expr::ObjCArrayLiteralClass:
9227 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009228 case Expr::ObjCEncodeExprClass:
9229 case Expr::ObjCMessageExprClass:
9230 case Expr::ObjCSelectorExprClass:
9231 case Expr::ObjCProtocolExprClass:
9232 case Expr::ObjCIvarRefExprClass:
9233 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009234 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009235 case Expr::ObjCIsaExprClass:
9236 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009237 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009238 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009239 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009240 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009241 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009242 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009243 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009244 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009245 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009246 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009247 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009248 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009249 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009250 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009251 case Expr::CoawaitExprClass:
9252 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009253 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009254
Richard Smithf137f932014-01-25 20:50:08 +00009255 case Expr::InitListExprClass: {
9256 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9257 // form "T x = { a };" is equivalent to "T x = a;".
9258 // Unless we're initializing a reference, T is a scalar as it is known to be
9259 // of integral or enumeration type.
9260 if (E->isRValue())
9261 if (cast<InitListExpr>(E)->getNumInits() == 1)
9262 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9263 return ICEDiag(IK_NotICE, E->getLocStart());
9264 }
9265
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009266 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009267 case Expr::GNUNullExprClass:
9268 // GCC considers the GNU __null value to be an integral constant expression.
9269 return NoDiag();
9270
John McCall7c454bb2011-07-15 05:09:51 +00009271 case Expr::SubstNonTypeTemplateParmExprClass:
9272 return
9273 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9274
John McCall864e3962010-05-07 05:32:02 +00009275 case Expr::ParenExprClass:
9276 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009277 case Expr::GenericSelectionExprClass:
9278 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009279 case Expr::IntegerLiteralClass:
9280 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009281 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009282 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009283 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009284 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009285 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009286 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009287 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009288 return NoDiag();
9289 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009290 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009291 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9292 // constant expressions, but they can never be ICEs because an ICE cannot
9293 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009294 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009295 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009296 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009297 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009298 }
Richard Smith6365c912012-02-24 22:12:32 +00009299 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009300 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9301 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009302 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009303 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009304 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009305 // Parameter variables are never constants. Without this check,
9306 // getAnyInitializer() can find a default argument, which leads
9307 // to chaos.
9308 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009309 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009310
9311 // C++ 7.1.5.1p2
9312 // A variable of non-volatile const-qualified integral or enumeration
9313 // type initialized by an ICE can be used in ICEs.
9314 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009315 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009316 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009317
Richard Smithd0b4dd62011-12-19 06:19:21 +00009318 const VarDecl *VD;
9319 // Look for a declaration of this variable that has an initializer, and
9320 // check whether it is an ICE.
9321 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9322 return NoDiag();
9323 else
Richard Smith9e575da2012-12-28 13:25:52 +00009324 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009325 }
9326 }
Richard Smith9e575da2012-12-28 13:25:52 +00009327 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009328 }
John McCall864e3962010-05-07 05:32:02 +00009329 case Expr::UnaryOperatorClass: {
9330 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9331 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009332 case UO_PostInc:
9333 case UO_PostDec:
9334 case UO_PreInc:
9335 case UO_PreDec:
9336 case UO_AddrOf:
9337 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009338 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009339 // C99 6.6/3 allows increment and decrement within unevaluated
9340 // subexpressions of constant expressions, but they can never be ICEs
9341 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009342 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009343 case UO_Extension:
9344 case UO_LNot:
9345 case UO_Plus:
9346 case UO_Minus:
9347 case UO_Not:
9348 case UO_Real:
9349 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009350 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009351 }
Richard Smith9e575da2012-12-28 13:25:52 +00009352
John McCall864e3962010-05-07 05:32:02 +00009353 // OffsetOf falls through here.
9354 }
9355 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009356 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9357 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9358 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9359 // compliance: we should warn earlier for offsetof expressions with
9360 // array subscripts that aren't ICEs, and if the array subscripts
9361 // are ICEs, the value of the offsetof must be an integer constant.
9362 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009363 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009364 case Expr::UnaryExprOrTypeTraitExprClass: {
9365 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9366 if ((Exp->getKind() == UETT_SizeOf) &&
9367 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009368 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009369 return NoDiag();
9370 }
9371 case Expr::BinaryOperatorClass: {
9372 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9373 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009374 case BO_PtrMemD:
9375 case BO_PtrMemI:
9376 case BO_Assign:
9377 case BO_MulAssign:
9378 case BO_DivAssign:
9379 case BO_RemAssign:
9380 case BO_AddAssign:
9381 case BO_SubAssign:
9382 case BO_ShlAssign:
9383 case BO_ShrAssign:
9384 case BO_AndAssign:
9385 case BO_XorAssign:
9386 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009387 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9388 // constant expressions, but they can never be ICEs because an ICE cannot
9389 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009390 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009391
John McCalle3027922010-08-25 11:45:40 +00009392 case BO_Mul:
9393 case BO_Div:
9394 case BO_Rem:
9395 case BO_Add:
9396 case BO_Sub:
9397 case BO_Shl:
9398 case BO_Shr:
9399 case BO_LT:
9400 case BO_GT:
9401 case BO_LE:
9402 case BO_GE:
9403 case BO_EQ:
9404 case BO_NE:
9405 case BO_And:
9406 case BO_Xor:
9407 case BO_Or:
9408 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009409 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9410 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009411 if (Exp->getOpcode() == BO_Div ||
9412 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009413 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009414 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009415 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009416 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009417 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009418 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009419 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009420 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009421 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009422 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009423 }
9424 }
9425 }
John McCalle3027922010-08-25 11:45:40 +00009426 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009427 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009428 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9429 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009430 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9431 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009432 } else {
9433 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009434 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009435 }
9436 }
Richard Smith9e575da2012-12-28 13:25:52 +00009437 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009438 }
John McCalle3027922010-08-25 11:45:40 +00009439 case BO_LAnd:
9440 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009441 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9442 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009443 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009444 // Rare case where the RHS has a comma "side-effect"; we need
9445 // to actually check the condition to see whether the side
9446 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009447 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009448 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009449 return RHSResult;
9450 return NoDiag();
9451 }
9452
Richard Smith9e575da2012-12-28 13:25:52 +00009453 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009454 }
9455 }
9456 }
9457 case Expr::ImplicitCastExprClass:
9458 case Expr::CStyleCastExprClass:
9459 case Expr::CXXFunctionalCastExprClass:
9460 case Expr::CXXStaticCastExprClass:
9461 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009462 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009463 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009464 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009465 if (isa<ExplicitCastExpr>(E)) {
9466 if (const FloatingLiteral *FL
9467 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9468 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9469 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9470 APSInt IgnoredVal(DestWidth, !DestSigned);
9471 bool Ignored;
9472 // If the value does not fit in the destination type, the behavior is
9473 // undefined, so we are not required to treat it as a constant
9474 // expression.
9475 if (FL->getValue().convertToInteger(IgnoredVal,
9476 llvm::APFloat::rmTowardZero,
9477 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009478 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009479 return NoDiag();
9480 }
9481 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009482 switch (cast<CastExpr>(E)->getCastKind()) {
9483 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009484 case CK_AtomicToNonAtomic:
9485 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009486 case CK_NoOp:
9487 case CK_IntegralToBoolean:
9488 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009489 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009490 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009491 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009492 }
John McCall864e3962010-05-07 05:32:02 +00009493 }
John McCallc07a0c72011-02-17 10:25:35 +00009494 case Expr::BinaryConditionalOperatorClass: {
9495 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9496 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009497 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009498 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009499 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9500 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9501 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009502 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009503 return FalseResult;
9504 }
John McCall864e3962010-05-07 05:32:02 +00009505 case Expr::ConditionalOperatorClass: {
9506 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9507 // If the condition (ignoring parens) is a __builtin_constant_p call,
9508 // then only the true side is actually considered in an integer constant
9509 // expression, and it is fully evaluated. This is an important GNU
9510 // extension. See GCC PR38377 for discussion.
9511 if (const CallExpr *CallCE
9512 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009513 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009514 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009515 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009516 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009517 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009518
Richard Smithf57d8cb2011-12-09 22:58:01 +00009519 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9520 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009521
Richard Smith9e575da2012-12-28 13:25:52 +00009522 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009523 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009524 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009525 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009526 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009527 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009528 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009529 return NoDiag();
9530 // Rare case where the diagnostics depend on which side is evaluated
9531 // Note that if we get here, CondResult is 0, and at least one of
9532 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009533 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009534 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009535 return TrueResult;
9536 }
9537 case Expr::CXXDefaultArgExprClass:
9538 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009539 case Expr::CXXDefaultInitExprClass:
9540 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009541 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009542 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009543 }
9544 }
9545
David Blaikiee4d798f2012-01-20 21:50:17 +00009546 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009547}
9548
Richard Smithf57d8cb2011-12-09 22:58:01 +00009549/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009550static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009551 const Expr *E,
9552 llvm::APSInt *Value,
9553 SourceLocation *Loc) {
9554 if (!E->getType()->isIntegralOrEnumerationType()) {
9555 if (Loc) *Loc = E->getExprLoc();
9556 return false;
9557 }
9558
Richard Smith66e05fe2012-01-18 05:21:49 +00009559 APValue Result;
9560 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009561 return false;
9562
Richard Smith98710fc2014-11-13 23:03:19 +00009563 if (!Result.isInt()) {
9564 if (Loc) *Loc = E->getExprLoc();
9565 return false;
9566 }
9567
Richard Smith66e05fe2012-01-18 05:21:49 +00009568 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009569 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009570}
9571
Craig Toppera31a8822013-08-22 07:09:37 +00009572bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9573 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009574 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009575 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009576
Richard Smith9e575da2012-12-28 13:25:52 +00009577 ICEDiag D = CheckICE(this, Ctx);
9578 if (D.Kind != IK_ICE) {
9579 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009580 return false;
9581 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009582 return true;
9583}
9584
Craig Toppera31a8822013-08-22 07:09:37 +00009585bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009586 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009587 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009588 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9589
9590 if (!isIntegerConstantExpr(Ctx, Loc))
9591 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009592 // The only possible side-effects here are due to UB discovered in the
9593 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9594 // required to treat the expression as an ICE, so we produce the folded
9595 // value.
9596 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009597 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009598 return true;
9599}
Richard Smith66e05fe2012-01-18 05:21:49 +00009600
Craig Toppera31a8822013-08-22 07:09:37 +00009601bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009602 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009603}
9604
Craig Toppera31a8822013-08-22 07:09:37 +00009605bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009606 SourceLocation *Loc) const {
9607 // We support this checking in C++98 mode in order to diagnose compatibility
9608 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009609 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009610
Richard Smith98a0a492012-02-14 21:38:30 +00009611 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009612 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009613 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009614 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009615 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009616
9617 APValue Scratch;
9618 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9619
9620 if (!Diags.empty()) {
9621 IsConstExpr = false;
9622 if (Loc) *Loc = Diags[0].first;
9623 } else if (!IsConstExpr) {
9624 // FIXME: This shouldn't happen.
9625 if (Loc) *Loc = getExprLoc();
9626 }
9627
9628 return IsConstExpr;
9629}
Richard Smith253c2a32012-01-27 01:14:48 +00009630
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009631bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9632 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009633 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009634 Expr::EvalStatus Status;
9635 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9636
9637 ArgVector ArgValues(Args.size());
9638 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9639 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009640 if ((*I)->isValueDependent() ||
9641 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009642 // If evaluation fails, throw away the argument entirely.
9643 ArgValues[I - Args.begin()] = APValue();
9644 if (Info.EvalStatus.HasSideEffects)
9645 return false;
9646 }
9647
9648 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009649 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009650 ArgValues.data());
9651 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9652}
9653
Richard Smith253c2a32012-01-27 01:14:48 +00009654bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009655 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009656 PartialDiagnosticAt> &Diags) {
9657 // FIXME: It would be useful to check constexpr function templates, but at the
9658 // moment the constant expression evaluator cannot cope with the non-rigorous
9659 // ASTs which we build for dependent expressions.
9660 if (FD->isDependentContext())
9661 return true;
9662
9663 Expr::EvalStatus Status;
9664 Status.Diag = &Diags;
9665
Richard Smith6d4c6582013-11-05 22:18:15 +00009666 EvalInfo Info(FD->getASTContext(), Status,
9667 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009668
9669 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009670 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009671
Richard Smith7525ff62013-05-09 07:14:00 +00009672 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009673 // is a temporary being used as the 'this' pointer.
9674 LValue This;
9675 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009676 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009677
Richard Smith253c2a32012-01-27 01:14:48 +00009678 ArrayRef<const Expr*> Args;
9679
9680 SourceLocation Loc = FD->getLocation();
9681
Richard Smith2e312c82012-03-03 22:46:17 +00009682 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009683 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9684 // Evaluate the call as a constant initializer, to allow the construction
9685 // of objects of non-literal types.
9686 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009687 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009688 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009689 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009690 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009691
9692 return Diags.empty();
9693}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009694
9695bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9696 const FunctionDecl *FD,
9697 SmallVectorImpl<
9698 PartialDiagnosticAt> &Diags) {
9699 Expr::EvalStatus Status;
9700 Status.Diag = &Diags;
9701
9702 EvalInfo Info(FD->getASTContext(), Status,
9703 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9704
9705 // Fabricate a call stack frame to give the arguments a plausible cover story.
9706 ArrayRef<const Expr*> Args;
9707 ArgVector ArgValues(0);
9708 bool Success = EvaluateArgs(Args, ArgValues, Info);
9709 (void)Success;
9710 assert(Success &&
9711 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009712 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009713
9714 APValue ResultScratch;
9715 Evaluate(ResultScratch, Info, E);
9716 return Diags.empty();
9717}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009718
9719bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9720 unsigned Type) const {
9721 if (!getType()->isPointerType())
9722 return false;
9723
9724 Expr::EvalStatus Status;
9725 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9726 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9727}