blob: 6771175ba6d4d862fa83d54d92f1e4a9c66e2ba7 [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
George Burgess IV8c892b52016-05-25 22:31:54 +0000481 /// \brief Whether or not we're currently speculatively evaluating.
482 bool IsSpeculativelyEvaluating;
483
Richard Smith6d4c6582013-11-05 22:18:15 +0000484 enum EvaluationMode {
485 /// Evaluate as a constant expression. Stop if we find that the expression
486 /// is not a constant expression.
487 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000488
Richard Smith6d4c6582013-11-05 22:18:15 +0000489 /// Evaluate as a potential constant expression. Keep going if we hit a
490 /// construct that we can't evaluate yet (because we don't yet know the
491 /// value of something) but stop if we hit something that could never be
492 /// a constant expression.
493 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000494
Richard Smith6d4c6582013-11-05 22:18:15 +0000495 /// Fold the expression to a constant. Stop if we hit a side-effect that
496 /// we can't model.
497 EM_ConstantFold,
498
499 /// Evaluate the expression looking for integer overflow and similar
500 /// issues. Don't worry about side-effects, and try to visit all
501 /// subexpressions.
502 EM_EvaluateForOverflow,
503
504 /// Evaluate in any way we know how. Don't worry about side-effects that
505 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000506 EM_IgnoreSideEffects,
507
508 /// Evaluate as a constant expression. Stop if we find that the expression
509 /// is not a constant expression. Some expressions can be retried in the
510 /// optimizer if we don't constant fold them here, but in an unevaluated
511 /// context we try to fold them immediately since the optimizer never
512 /// gets a chance to look at it.
513 EM_ConstantExpressionUnevaluated,
514
515 /// Evaluate as a potential constant expression. Keep going if we hit a
516 /// construct that we can't evaluate yet (because we don't yet know the
517 /// value of something) but stop if we hit something that could never be
518 /// a constant expression. Some expressions can be retried in the
519 /// optimizer if we don't constant fold them here, but in an unevaluated
520 /// context we try to fold them immediately since the optimizer never
521 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000522 EM_PotentialConstantExpressionUnevaluated,
523
524 /// Evaluate as a constant expression. Continue evaluating if we find a
525 /// MemberExpr with a base that can't be evaluated.
526 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000527 } EvalMode;
528
529 /// Are we checking whether the expression is a potential constant
530 /// expression?
531 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000532 return EvalMode == EM_PotentialConstantExpression ||
533 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000534 }
535
536 /// Are we checking an expression for overflow?
537 // FIXME: We should check for any kind of undefined or suspicious behavior
538 // in such constructs, not just overflow.
539 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
540
541 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000542 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000544 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000545 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
546 EvaluatingDecl((const ValueDecl *)nullptr),
547 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000548 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
549 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000550
Richard Smith7525ff62013-05-09 07:14:00 +0000551 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
552 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000553 EvaluatingDeclValue = &Value;
554 }
555
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000557
Richard Smith357362d2011-12-13 06:39:58 +0000558 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000559 // Don't perform any constexpr calls (other than the call we're checking)
560 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000561 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000562 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000563 if (NextCallIndex == 0) {
564 // NextCallIndex has wrapped around.
565 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
566 return false;
567 }
Richard Smith357362d2011-12-13 06:39:58 +0000568 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
569 return true;
570 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
571 << getLangOpts().ConstexprCallDepth;
572 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000573 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574
Richard Smithb228a862012-02-15 02:18:13 +0000575 CallStackFrame *getCallFrame(unsigned CallIndex) {
576 assert(CallIndex && "no call index in getCallFrame");
577 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
578 // be null in this loop.
579 CallStackFrame *Frame = CurrentCall;
580 while (Frame->Index > CallIndex)
581 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000583 }
584
Richard Smitha3d3bd22013-05-08 02:12:03 +0000585 bool nextStep(const Stmt *S) {
586 if (!StepsLeft) {
587 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
588 return false;
589 }
590 --StepsLeft;
591 return true;
592 }
593
Richard Smith357362d2011-12-13 06:39:58 +0000594 private:
595 /// Add a diagnostic to the diagnostics list.
596 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
597 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
598 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
599 return EvalStatus.Diag->back().second;
600 }
601
Richard Smithf6f003a2011-12-16 19:06:07 +0000602 /// Add notes containing a call stack to the current point of evaluation.
603 void addCallStack(unsigned Limit);
604
Richard Smith357362d2011-12-13 06:39:58 +0000605 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000606 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000607 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
608 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000609 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000610 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 // If we have a prior diagnostic, it will be noting that the expression
612 // isn't a constant expression. This diagnostic is more important,
613 // unless we require this evaluation to produce a constant expression.
614 //
615 // FIXME: We might want to show both diagnostics to the user in
616 // EM_ConstantFold mode.
617 if (!EvalStatus.Diag->empty()) {
618 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000619 case EM_ConstantFold:
620 case EM_IgnoreSideEffects:
621 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000622 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000623 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000625 case EM_ConstantExpression:
626 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000627 case EM_ConstantExpressionUnevaluated:
628 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000629 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 HasActiveDiagnostic = false;
631 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 }
633 }
634
Richard Smithf6f003a2011-12-16 19:06:07 +0000635 unsigned CallStackNotes = CallStackDepth - 1;
636 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
637 if (Limit)
638 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000639 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000640 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000641
Richard Smith357362d2011-12-13 06:39:58 +0000642 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000643 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000645 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
646 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000647 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000648 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000649 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000650 }
Richard Smith357362d2011-12-13 06:39:58 +0000651 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 return OptionalDiagnostic();
653 }
654
Richard Smithce1ec5e2012-03-15 04:53:45 +0000655 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
656 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000657 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000658 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000659 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000660 HasActiveDiagnostic = false;
661 return OptionalDiagnostic();
662 }
663
Richard Smith92b1ce02011-12-12 09:28:41 +0000664 /// Diagnose that the evaluation does not produce a C++11 core constant
665 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 ///
667 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
668 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000669 template<typename LocArg>
670 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000671 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000672 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 // Don't override a previous diagnostic. Don't bother collecting
674 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000675 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000676 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000677 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000678 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000679 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000680 }
681
682 /// Add a note to a prior diagnostic.
683 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
684 if (!HasActiveDiagnostic)
685 return OptionalDiagnostic();
686 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000687 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000688
689 /// Add a stack of notes to a prior diagnostic.
690 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
691 if (HasActiveDiagnostic) {
692 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
693 Diags.begin(), Diags.end());
694 }
695 }
Richard Smith253c2a32012-01-27 01:14:48 +0000696
Richard Smith6d4c6582013-11-05 22:18:15 +0000697 /// Should we continue evaluation after encountering a side-effect that we
698 /// couldn't model?
699 bool keepEvaluatingAfterSideEffect() {
700 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000701 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_EvaluateForOverflow:
704 case EM_IgnoreSideEffects:
705 return true;
706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000708 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000710 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 return false;
712 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000713 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000714 }
715
716 /// Note that we have had a side-effect, and determine whether we should
717 /// keep evaluating.
718 bool noteSideEffect() {
719 EvalStatus.HasSideEffects = true;
720 return keepEvaluatingAfterSideEffect();
721 }
722
Richard Smithce8eca52015-12-08 03:21:47 +0000723 /// Should we continue evaluation after encountering undefined behavior?
724 bool keepEvaluatingAfterUndefinedBehavior() {
725 switch (EvalMode) {
726 case EM_EvaluateForOverflow:
727 case EM_IgnoreSideEffects:
728 case EM_ConstantFold:
729 case EM_DesignatorFold:
730 return true;
731
732 case EM_PotentialConstantExpression:
733 case EM_PotentialConstantExpressionUnevaluated:
734 case EM_ConstantExpression:
735 case EM_ConstantExpressionUnevaluated:
736 return false;
737 }
738 llvm_unreachable("Missed EvalMode case");
739 }
740
741 /// Note that we hit something that was technically undefined behavior, but
742 /// that we can evaluate past it (such as signed overflow or floating-point
743 /// division by zero.)
744 bool noteUndefinedBehavior() {
745 EvalStatus.HasUndefinedBehavior = true;
746 return keepEvaluatingAfterUndefinedBehavior();
747 }
748
Richard Smith253c2a32012-01-27 01:14:48 +0000749 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000751 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 if (!StepsLeft)
753 return false;
754
755 switch (EvalMode) {
756 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000757 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000758 case EM_EvaluateForOverflow:
759 return true;
760
761 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000762 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 case EM_ConstantFold:
764 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000765 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000766 return false;
767 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000768 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000769 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000770
George Burgess IV8c892b52016-05-25 22:31:54 +0000771 /// Notes that we failed to evaluate an expression that other expressions
772 /// directly depend on, and determine if we should keep evaluating. This
773 /// should only be called if we actually intend to keep evaluating.
774 ///
775 /// Call noteSideEffect() instead if we may be able to ignore the value that
776 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
777 ///
778 /// (Foo(), 1) // use noteSideEffect
779 /// (Foo() || true) // use noteSideEffect
780 /// Foo() + 1 // use noteFailure
781 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
782 // Failure when evaluating some expression often means there is some
783 // subexpression whose evaluation was skipped. Therefore, (because we
784 // don't track whether we skipped an expression when unwinding after an
785 // evaluation failure) every evaluation failure that bubbles up from a
786 // subexpression implies that a side-effect has potentially happened. We
787 // skip setting the HasSideEffects flag to true until we decide to
788 // continue evaluating after that point, which happens here.
789 bool KeepGoing = keepEvaluatingAfterFailure();
790 EvalStatus.HasSideEffects |= KeepGoing;
791 return KeepGoing;
792 }
793
George Burgess IV3a03fab2015-09-04 21:28:13 +0000794 bool allowInvalidBaseExpr() const {
795 return EvalMode == EM_DesignatorFold;
796 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000797 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000798
799 /// Object used to treat all foldable expressions as constant expressions.
800 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000801 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000802 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 bool HadNoPriorDiags;
804 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000805
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 explicit FoldConstant(EvalInfo &Info, bool Enabled)
807 : Info(Info),
808 Enabled(Enabled),
809 HadNoPriorDiags(Info.EvalStatus.Diag &&
810 Info.EvalStatus.Diag->empty() &&
811 !Info.EvalStatus.HasSideEffects),
812 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000813 if (Enabled &&
814 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
815 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000816 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000817 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 void keepDiagnostics() { Enabled = false; }
819 ~FoldConstant() {
820 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000821 !Info.EvalStatus.HasSideEffects)
822 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000823 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000824 }
825 };
Richard Smith17100ba2012-02-16 02:46:34 +0000826
George Burgess IV3a03fab2015-09-04 21:28:13 +0000827 /// RAII object used to treat the current evaluation as the correct pointer
828 /// offset fold for the current EvalMode
829 struct FoldOffsetRAII {
830 EvalInfo &Info;
831 EvalInfo::EvaluationMode OldMode;
832 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
833 : Info(Info), OldMode(Info.EvalMode) {
834 if (!Info.checkingPotentialConstantExpression())
835 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
836 : EvalInfo::EM_ConstantFold;
837 }
838
839 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
840 };
841
George Burgess IV8c892b52016-05-25 22:31:54 +0000842 /// RAII object used to optionally suppress diagnostics and side-effects from
843 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000844 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000845 /// Pair of EvalInfo, and a bit that stores whether or not we were
846 /// speculatively evaluating when we created this RAII.
847 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000848 Expr::EvalStatus Old;
849
George Burgess IV8c892b52016-05-25 22:31:54 +0000850 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
851 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
852 Old = Other.Old;
853 Other.InfoAndOldSpecEval.setPointer(nullptr);
854 }
855
856 void maybeRestoreState() {
857 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
858 if (!Info)
859 return;
860
861 Info->EvalStatus = Old;
862 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
863 }
864
Richard Smith17100ba2012-02-16 02:46:34 +0000865 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000866 SpeculativeEvaluationRAII() = default;
867
868 SpeculativeEvaluationRAII(
869 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
870 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
871 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000872 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000873 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000874 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000875
876 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
877 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
878 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000879 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000880
881 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
882 maybeRestoreState();
883 moveFromAndCancel(std::move(Other));
884 return *this;
885 }
886
887 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000888 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000889
890 /// RAII object wrapping a full-expression or block scope, and handling
891 /// the ending of the lifetime of temporaries created within it.
892 template<bool IsFullExpression>
893 class ScopeRAII {
894 EvalInfo &Info;
895 unsigned OldStackSize;
896 public:
897 ScopeRAII(EvalInfo &Info)
898 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
899 ~ScopeRAII() {
900 // Body moved to a static method to encourage the compiler to inline away
901 // instances of this class.
902 cleanup(Info, OldStackSize);
903 }
904 private:
905 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
906 unsigned NewEnd = OldStackSize;
907 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
908 I != N; ++I) {
909 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
910 // Full-expression cleanup of a lifetime-extended temporary: nothing
911 // to do, just move this cleanup to the right place in the stack.
912 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
913 ++NewEnd;
914 } else {
915 // End the lifetime of the object.
916 Info.CleanupStack[I].endLifetime();
917 }
918 }
919 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
920 Info.CleanupStack.end());
921 }
922 };
923 typedef ScopeRAII<false> BlockScopeRAII;
924 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000925}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000926
Richard Smitha8105bc2012-01-06 16:39:00 +0000927bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
928 CheckSubobjectKind CSK) {
929 if (Invalid)
930 return false;
931 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000932 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000933 << CSK;
934 setInvalid();
935 return false;
936 }
937 return true;
938}
939
940void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
941 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000942 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000943 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000944 << static_cast<int>(N) << /*array*/ 0
945 << static_cast<unsigned>(MostDerivedArraySize);
946 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000947 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000948 << static_cast<int>(N) << /*non-array*/ 1;
949 setInvalid();
950}
951
Richard Smithf6f003a2011-12-16 19:06:07 +0000952CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
953 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000954 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000955 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000956 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000957 Info.CurrentCall = this;
958 ++Info.CallStackDepth;
959}
960
961CallStackFrame::~CallStackFrame() {
962 assert(Info.CurrentCall == this && "calls retired out of order");
963 --Info.CallStackDepth;
964 Info.CurrentCall = Caller;
965}
966
Richard Smith08d6a2c2013-07-24 07:11:57 +0000967APValue &CallStackFrame::createTemporary(const void *Key,
968 bool IsLifetimeExtended) {
969 APValue &Result = Temporaries[Key];
970 assert(Result.isUninit() && "temporary created multiple times");
971 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
972 return Result;
973}
974
Richard Smith84401042013-06-03 05:03:02 +0000975static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000976
977void EvalInfo::addCallStack(unsigned Limit) {
978 // Determine which calls to skip, if any.
979 unsigned ActiveCalls = CallStackDepth - 1;
980 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
981 if (Limit && Limit < ActiveCalls) {
982 SkipStart = Limit / 2 + Limit % 2;
983 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000984 }
985
Richard Smithf6f003a2011-12-16 19:06:07 +0000986 // Walk the call stack and add the diagnostics.
987 unsigned CallIdx = 0;
988 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
989 Frame = Frame->Caller, ++CallIdx) {
990 // Skip this call?
991 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
992 if (CallIdx == SkipStart) {
993 // Note that we're skipping calls.
994 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
995 << unsigned(ActiveCalls - Limit);
996 }
997 continue;
998 }
999
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001000 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001001 llvm::raw_svector_ostream Out(Buffer);
1002 describeCall(Frame, Out);
1003 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1004 }
1005}
1006
1007namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001008 struct ComplexValue {
1009 private:
1010 bool IsInt;
1011
1012 public:
1013 APSInt IntReal, IntImag;
1014 APFloat FloatReal, FloatImag;
1015
1016 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1017
1018 void makeComplexFloat() { IsInt = false; }
1019 bool isComplexFloat() const { return !IsInt; }
1020 APFloat &getComplexFloatReal() { return FloatReal; }
1021 APFloat &getComplexFloatImag() { return FloatImag; }
1022
1023 void makeComplexInt() { IsInt = true; }
1024 bool isComplexInt() const { return IsInt; }
1025 APSInt &getComplexIntReal() { return IntReal; }
1026 APSInt &getComplexIntImag() { return IntImag; }
1027
Richard Smith2e312c82012-03-03 22:46:17 +00001028 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001029 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001030 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001031 else
Richard Smith2e312c82012-03-03 22:46:17 +00001032 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001033 }
Richard Smith2e312c82012-03-03 22:46:17 +00001034 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001035 assert(v.isComplexFloat() || v.isComplexInt());
1036 if (v.isComplexFloat()) {
1037 makeComplexFloat();
1038 FloatReal = v.getComplexFloatReal();
1039 FloatImag = v.getComplexFloatImag();
1040 } else {
1041 makeComplexInt();
1042 IntReal = v.getComplexIntReal();
1043 IntImag = v.getComplexIntImag();
1044 }
1045 }
John McCall93d91dc2010-05-07 17:22:02 +00001046 };
John McCall45d55e42010-05-07 21:00:08 +00001047
1048 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001049 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001050 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001051 bool InvalidBase : 1;
1052 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001053 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001054
Richard Smithce40ad62011-11-12 22:28:03 +00001055 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001056 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001057 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001058 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001059 SubobjectDesignator &getLValueDesignator() { return Designator; }
1060 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001061
Richard Smith2e312c82012-03-03 22:46:17 +00001062 void moveInto(APValue &V) const {
1063 if (Designator.Invalid)
1064 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1065 else
1066 V = APValue(Base, Offset, Designator.Entries,
1067 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001068 }
Richard Smith2e312c82012-03-03 22:46:17 +00001069 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001070 assert(V.isLValue());
1071 Base = V.getLValueBase();
1072 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001073 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001074 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001075 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001076 }
1077
George Burgess IV3a03fab2015-09-04 21:28:13 +00001078 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001079 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001080 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001081 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001082 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001083 Designator = SubobjectDesignator(getType(B));
1084 }
1085
George Burgess IV3a03fab2015-09-04 21:28:13 +00001086 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1087 set(B, I, true);
1088 }
1089
Richard Smitha8105bc2012-01-06 16:39:00 +00001090 // Check that this LValue is not based on a null pointer. If it is, produce
1091 // a diagnostic and mark the designator as invalid.
1092 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1093 CheckSubobjectKind CSK) {
1094 if (Designator.Invalid)
1095 return false;
1096 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001097 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001098 << CSK;
1099 Designator.setInvalid();
1100 return false;
1101 }
1102 return true;
1103 }
1104
1105 // Check this LValue refers to an object. If not, set the designator to be
1106 // invalid and emit a diagnostic.
1107 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001108 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001109 Designator.checkSubobject(Info, E, CSK);
1110 }
1111
1112 void addDecl(EvalInfo &Info, const Expr *E,
1113 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001114 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1115 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001116 }
1117 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001118 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1119 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001120 }
Richard Smith66c96992012-02-18 22:04:06 +00001121 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001122 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1123 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001124 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001126 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001127 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001128 }
John McCall45d55e42010-05-07 21:00:08 +00001129 };
Richard Smith027bf112011-11-17 22:56:20 +00001130
1131 struct MemberPtr {
1132 MemberPtr() {}
1133 explicit MemberPtr(const ValueDecl *Decl) :
1134 DeclAndIsDerivedMember(Decl, false), Path() {}
1135
1136 /// The member or (direct or indirect) field referred to by this member
1137 /// pointer, or 0 if this is a null member pointer.
1138 const ValueDecl *getDecl() const {
1139 return DeclAndIsDerivedMember.getPointer();
1140 }
1141 /// Is this actually a member of some type derived from the relevant class?
1142 bool isDerivedMember() const {
1143 return DeclAndIsDerivedMember.getInt();
1144 }
1145 /// Get the class which the declaration actually lives in.
1146 const CXXRecordDecl *getContainingRecord() const {
1147 return cast<CXXRecordDecl>(
1148 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1149 }
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151 void moveInto(APValue &V) const {
1152 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001153 }
Richard Smith2e312c82012-03-03 22:46:17 +00001154 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001155 assert(V.isMemberPointer());
1156 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1157 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1158 Path.clear();
1159 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1160 Path.insert(Path.end(), P.begin(), P.end());
1161 }
1162
1163 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1164 /// whether the member is a member of some class derived from the class type
1165 /// of the member pointer.
1166 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1167 /// Path - The path of base/derived classes from the member declaration's
1168 /// class (exclusive) to the class type of the member pointer (inclusive).
1169 SmallVector<const CXXRecordDecl*, 4> Path;
1170
1171 /// Perform a cast towards the class of the Decl (either up or down the
1172 /// hierarchy).
1173 bool castBack(const CXXRecordDecl *Class) {
1174 assert(!Path.empty());
1175 const CXXRecordDecl *Expected;
1176 if (Path.size() >= 2)
1177 Expected = Path[Path.size() - 2];
1178 else
1179 Expected = getContainingRecord();
1180 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1181 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1182 // if B does not contain the original member and is not a base or
1183 // derived class of the class containing the original member, the result
1184 // of the cast is undefined.
1185 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1186 // (D::*). We consider that to be a language defect.
1187 return false;
1188 }
1189 Path.pop_back();
1190 return true;
1191 }
1192 /// Perform a base-to-derived member pointer cast.
1193 bool castToDerived(const CXXRecordDecl *Derived) {
1194 if (!getDecl())
1195 return true;
1196 if (!isDerivedMember()) {
1197 Path.push_back(Derived);
1198 return true;
1199 }
1200 if (!castBack(Derived))
1201 return false;
1202 if (Path.empty())
1203 DeclAndIsDerivedMember.setInt(false);
1204 return true;
1205 }
1206 /// Perform a derived-to-base member pointer cast.
1207 bool castToBase(const CXXRecordDecl *Base) {
1208 if (!getDecl())
1209 return true;
1210 if (Path.empty())
1211 DeclAndIsDerivedMember.setInt(true);
1212 if (isDerivedMember()) {
1213 Path.push_back(Base);
1214 return true;
1215 }
1216 return castBack(Base);
1217 }
1218 };
Richard Smith357362d2011-12-13 06:39:58 +00001219
Richard Smith7bb00672012-02-01 01:42:44 +00001220 /// Compare two member pointers, which are assumed to be of the same type.
1221 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1222 if (!LHS.getDecl() || !RHS.getDecl())
1223 return !LHS.getDecl() && !RHS.getDecl();
1224 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1225 return false;
1226 return LHS.Path == RHS.Path;
1227 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001228}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001229
Richard Smith2e312c82012-03-03 22:46:17 +00001230static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001231static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1232 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001233 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001234static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1235static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001236static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1237 EvalInfo &Info);
1238static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001239static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001240static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001241 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001242static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001243static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001244static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001245static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001246
1247//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001248// Misc utilities
1249//===----------------------------------------------------------------------===//
1250
Richard Smith84401042013-06-03 05:03:02 +00001251/// Produce a string describing the given constexpr call.
1252static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1253 unsigned ArgIndex = 0;
1254 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1255 !isa<CXXConstructorDecl>(Frame->Callee) &&
1256 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1257
1258 if (!IsMemberCall)
1259 Out << *Frame->Callee << '(';
1260
1261 if (Frame->This && IsMemberCall) {
1262 APValue Val;
1263 Frame->This->moveInto(Val);
1264 Val.printPretty(Out, Frame->Info.Ctx,
1265 Frame->This->Designator.MostDerivedType);
1266 // FIXME: Add parens around Val if needed.
1267 Out << "->" << *Frame->Callee << '(';
1268 IsMemberCall = false;
1269 }
1270
1271 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1272 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1273 if (ArgIndex > (unsigned)IsMemberCall)
1274 Out << ", ";
1275
1276 const ParmVarDecl *Param = *I;
1277 const APValue &Arg = Frame->Arguments[ArgIndex];
1278 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1279
1280 if (ArgIndex == 0 && IsMemberCall)
1281 Out << "->" << *Frame->Callee << '(';
1282 }
1283
1284 Out << ')';
1285}
1286
Richard Smithd9f663b2013-04-22 15:31:51 +00001287/// Evaluate an expression to see if it had side-effects, and discard its
1288/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001289/// \return \c true if the caller should keep evaluating.
1290static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001291 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001292 if (!Evaluate(Scratch, Info, E))
1293 // We don't need the value, but we might have skipped a side effect here.
1294 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001295 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001296}
1297
Richard Smith861b5b52013-05-07 23:34:45 +00001298/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1299/// return its existing value.
1300static int64_t getExtValue(const APSInt &Value) {
1301 return Value.isSigned() ? Value.getSExtValue()
1302 : static_cast<int64_t>(Value.getZExtValue());
1303}
1304
Richard Smithd62306a2011-11-10 06:34:14 +00001305/// Should this call expression be treated as a string literal?
1306static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001307 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001308 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1309 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1310}
1311
Richard Smithce40ad62011-11-12 22:28:03 +00001312static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001313 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1314 // constant expression of pointer type that evaluates to...
1315
1316 // ... a null pointer value, or a prvalue core constant expression of type
1317 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001318 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001319
Richard Smithce40ad62011-11-12 22:28:03 +00001320 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1321 // ... the address of an object with static storage duration,
1322 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1323 return VD->hasGlobalStorage();
1324 // ... the address of a function,
1325 return isa<FunctionDecl>(D);
1326 }
1327
1328 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001329 switch (E->getStmtClass()) {
1330 default:
1331 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001332 case Expr::CompoundLiteralExprClass: {
1333 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1334 return CLE->isFileScope() && CLE->isLValue();
1335 }
Richard Smithe6c01442013-06-05 00:46:14 +00001336 case Expr::MaterializeTemporaryExprClass:
1337 // A materialized temporary might have been lifetime-extended to static
1338 // storage duration.
1339 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001340 // A string literal has static storage duration.
1341 case Expr::StringLiteralClass:
1342 case Expr::PredefinedExprClass:
1343 case Expr::ObjCStringLiteralClass:
1344 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001345 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001346 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001347 return true;
1348 case Expr::CallExprClass:
1349 return IsStringLiteralCall(cast<CallExpr>(E));
1350 // For GCC compatibility, &&label has static storage duration.
1351 case Expr::AddrLabelExprClass:
1352 return true;
1353 // A Block literal expression may be used as the initialization value for
1354 // Block variables at global or local static scope.
1355 case Expr::BlockExprClass:
1356 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001357 case Expr::ImplicitValueInitExprClass:
1358 // FIXME:
1359 // We can never form an lvalue with an implicit value initialization as its
1360 // base through expression evaluation, so these only appear in one case: the
1361 // implicit variable declaration we invent when checking whether a constexpr
1362 // constructor can produce a constant expression. We must assume that such
1363 // an expression might be a global lvalue.
1364 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001365 }
John McCall95007602010-05-10 23:27:23 +00001366}
1367
Richard Smithb228a862012-02-15 02:18:13 +00001368static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1369 assert(Base && "no location for a null lvalue");
1370 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1371 if (VD)
1372 Info.Note(VD->getLocation(), diag::note_declared_at);
1373 else
Ted Kremenek28831752012-08-23 20:46:57 +00001374 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001375 diag::note_constexpr_temporary_here);
1376}
1377
Richard Smith80815602011-11-07 05:07:52 +00001378/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001379/// value for an address or reference constant expression. Return true if we
1380/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001381static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1382 QualType Type, const LValue &LVal) {
1383 bool IsReferenceType = Type->isReferenceType();
1384
Richard Smith357362d2011-12-13 06:39:58 +00001385 APValue::LValueBase Base = LVal.getLValueBase();
1386 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1387
Richard Smith0dea49e2012-02-18 04:58:18 +00001388 // Check that the object is a global. Note that the fake 'this' object we
1389 // manufacture when checking potential constant expressions is conservatively
1390 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001391 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001392 if (Info.getLangOpts().CPlusPlus11) {
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_non_global, 1)
1395 << IsReferenceType << !Designator.Entries.empty()
1396 << !!VD << VD;
1397 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001398 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001399 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001400 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001401 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001402 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001403 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001404 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001405 LVal.getLValueCallIndex() == 0) &&
1406 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001407
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001408 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1409 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001410 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001411 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001412 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001413
Hans Wennborg82dd8772014-06-25 22:19:48 +00001414 // A dllimport variable never acts like a constant.
1415 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001416 return false;
1417 }
1418 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1419 // __declspec(dllimport) must be handled very carefully:
1420 // We must never initialize an expression with the thunk in C++.
1421 // Doing otherwise would allow the same id-expression to yield
1422 // different addresses for the same function in different translation
1423 // units. However, this means that we must dynamically initialize the
1424 // expression with the contents of the import address table at runtime.
1425 //
1426 // The C language has no notion of ODR; furthermore, it has no notion of
1427 // dynamic initialization. This means that we are permitted to
1428 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001429 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001430 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001431 }
1432 }
1433
Richard Smitha8105bc2012-01-06 16:39:00 +00001434 // Allow address constant expressions to be past-the-end pointers. This is
1435 // an extension: the standard requires them to point to an object.
1436 if (!IsReferenceType)
1437 return true;
1438
1439 // A reference constant expression must refer to an object.
1440 if (!Base) {
1441 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001442 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001443 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001444 }
1445
Richard Smith357362d2011-12-13 06:39:58 +00001446 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001447 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001448 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001449 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001450 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001451 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001452 }
1453
Richard Smith80815602011-11-07 05:07:52 +00001454 return true;
1455}
1456
Richard Smithfddd3842011-12-30 21:15:51 +00001457/// Check that this core constant expression is of literal type, and if not,
1458/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001459static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001460 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001461 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001462 return true;
1463
Richard Smith7525ff62013-05-09 07:14:00 +00001464 // C++1y: A constant initializer for an object o [...] may also invoke
1465 // constexpr constructors for o and its subobjects even if those objects
1466 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001467 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001468 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001469 return true;
1470
Richard Smithfddd3842011-12-30 21:15:51 +00001471 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001472 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001473 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001474 << E->getType();
1475 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001477 return false;
1478}
1479
Richard Smith0b0a0b62011-10-29 20:57:55 +00001480/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001481/// constant expression. If not, report an appropriate diagnostic. Does not
1482/// check that the expression is of literal type.
1483static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1484 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001485 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001486 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1487 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001488 return false;
1489 }
1490
Richard Smith77be48a2014-07-31 06:31:19 +00001491 // We allow _Atomic(T) to be initialized from anything that T can be
1492 // initialized from.
1493 if (const AtomicType *AT = Type->getAs<AtomicType>())
1494 Type = AT->getValueType();
1495
Richard Smithb228a862012-02-15 02:18:13 +00001496 // Core issue 1454: For a literal constant expression of array or class type,
1497 // each subobject of its value shall have been initialized by a constant
1498 // expression.
1499 if (Value.isArray()) {
1500 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1501 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1502 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1503 Value.getArrayInitializedElt(I)))
1504 return false;
1505 }
1506 if (!Value.hasArrayFiller())
1507 return true;
1508 return CheckConstantExpression(Info, DiagLoc, EltTy,
1509 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001510 }
Richard Smithb228a862012-02-15 02:18:13 +00001511 if (Value.isUnion() && Value.getUnionField()) {
1512 return CheckConstantExpression(Info, DiagLoc,
1513 Value.getUnionField()->getType(),
1514 Value.getUnionValue());
1515 }
1516 if (Value.isStruct()) {
1517 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1518 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1519 unsigned BaseIndex = 0;
1520 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1521 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1522 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1523 Value.getStructBase(BaseIndex)))
1524 return false;
1525 }
1526 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001527 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001528 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1529 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001530 return false;
1531 }
1532 }
1533
1534 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001535 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001536 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001537 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1538 }
1539
1540 // Everything else is fine.
1541 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001542}
1543
Benjamin Kramer8407df72015-03-09 16:47:52 +00001544static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001545 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001546}
1547
1548static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001549 if (Value.CallIndex)
1550 return false;
1551 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1552 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001553}
1554
Richard Smithcecf1842011-11-01 21:06:14 +00001555static bool IsWeakLValue(const LValue &Value) {
1556 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001557 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001558}
1559
David Majnemerb5116032014-12-09 23:32:34 +00001560static bool isZeroSized(const LValue &Value) {
1561 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001562 if (Decl && isa<VarDecl>(Decl)) {
1563 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001564 if (Ty->isArrayType())
1565 return Ty->isIncompleteType() ||
1566 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001567 }
1568 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001569}
1570
Richard Smith2e312c82012-03-03 22:46:17 +00001571static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001572 // A null base expression indicates a null pointer. These are always
1573 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001574 if (!Value.getLValueBase()) {
1575 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001576 return true;
1577 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001578
Richard Smith027bf112011-11-17 22:56:20 +00001579 // We have a non-null base. These are generally known to be true, but if it's
1580 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001581 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001582 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001583 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001584}
1585
Richard Smith2e312c82012-03-03 22:46:17 +00001586static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001587 switch (Val.getKind()) {
1588 case APValue::Uninitialized:
1589 return false;
1590 case APValue::Int:
1591 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001592 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001593 case APValue::Float:
1594 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001595 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001596 case APValue::ComplexInt:
1597 Result = Val.getComplexIntReal().getBoolValue() ||
1598 Val.getComplexIntImag().getBoolValue();
1599 return true;
1600 case APValue::ComplexFloat:
1601 Result = !Val.getComplexFloatReal().isZero() ||
1602 !Val.getComplexFloatImag().isZero();
1603 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001604 case APValue::LValue:
1605 return EvalPointerValueAsBool(Val, Result);
1606 case APValue::MemberPointer:
1607 Result = Val.getMemberPointerDecl();
1608 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001609 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001610 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001611 case APValue::Struct:
1612 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001613 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001614 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001615 }
1616
Richard Smith11562c52011-10-28 17:51:58 +00001617 llvm_unreachable("unknown APValue kind");
1618}
1619
1620static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1621 EvalInfo &Info) {
1622 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001623 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001624 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001625 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001626 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001627}
1628
Richard Smith357362d2011-12-13 06:39:58 +00001629template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001630static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001631 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001632 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001633 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001634 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001635}
1636
1637static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1638 QualType SrcType, const APFloat &Value,
1639 QualType DestType, APSInt &Result) {
1640 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001641 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001642 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001643
Richard Smith357362d2011-12-13 06:39:58 +00001644 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001645 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001646 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1647 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001648 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001649 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001650}
1651
Richard Smith357362d2011-12-13 06:39:58 +00001652static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1653 QualType SrcType, QualType DestType,
1654 APFloat &Result) {
1655 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001656 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001657 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1658 APFloat::rmNearestTiesToEven, &ignored)
1659 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001660 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001661 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001662}
1663
Richard Smith911e1422012-01-30 22:27:01 +00001664static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1665 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001666 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001667 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001668 APSInt Result = Value;
1669 // Figure out if this is a truncate, extend or noop cast.
1670 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001671 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001672 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001673 return Result;
1674}
1675
Richard Smith357362d2011-12-13 06:39:58 +00001676static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1677 QualType SrcType, const APSInt &Value,
1678 QualType DestType, APFloat &Result) {
1679 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1680 if (Result.convertFromAPInt(Value, Value.isSigned(),
1681 APFloat::rmNearestTiesToEven)
1682 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001683 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001684 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001685}
1686
Richard Smith49ca8aa2013-08-06 07:09:20 +00001687static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1688 APValue &Value, const FieldDecl *FD) {
1689 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1690
1691 if (!Value.isInt()) {
1692 // Trying to store a pointer-cast-to-integer into a bitfield.
1693 // FIXME: In this case, we should provide the diagnostic for casting
1694 // a pointer to an integer.
1695 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1696 Info.Diag(E);
1697 return false;
1698 }
1699
1700 APSInt &Int = Value.getInt();
1701 unsigned OldBitWidth = Int.getBitWidth();
1702 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1703 if (NewBitWidth < OldBitWidth)
1704 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1705 return true;
1706}
1707
Eli Friedman803acb32011-12-22 03:51:45 +00001708static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1709 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001710 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001711 if (!Evaluate(SVal, Info, E))
1712 return false;
1713 if (SVal.isInt()) {
1714 Res = SVal.getInt();
1715 return true;
1716 }
1717 if (SVal.isFloat()) {
1718 Res = SVal.getFloat().bitcastToAPInt();
1719 return true;
1720 }
1721 if (SVal.isVector()) {
1722 QualType VecTy = E->getType();
1723 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1724 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1725 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1726 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1727 Res = llvm::APInt::getNullValue(VecSize);
1728 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1729 APValue &Elt = SVal.getVectorElt(i);
1730 llvm::APInt EltAsInt;
1731 if (Elt.isInt()) {
1732 EltAsInt = Elt.getInt();
1733 } else if (Elt.isFloat()) {
1734 EltAsInt = Elt.getFloat().bitcastToAPInt();
1735 } else {
1736 // Don't try to handle vectors of anything other than int or float
1737 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001738 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001739 return false;
1740 }
1741 unsigned BaseEltSize = EltAsInt.getBitWidth();
1742 if (BigEndian)
1743 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1744 else
1745 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1746 }
1747 return true;
1748 }
1749 // Give up if the input isn't an int, float, or vector. For example, we
1750 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001751 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001752 return false;
1753}
1754
Richard Smith43e77732013-05-07 04:50:00 +00001755/// Perform the given integer operation, which is known to need at most BitWidth
1756/// bits, and check for overflow in the original type (if that type was not an
1757/// unsigned type).
1758template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001759static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1760 const APSInt &LHS, const APSInt &RHS,
1761 unsigned BitWidth, Operation Op,
1762 APSInt &Result) {
1763 if (LHS.isUnsigned()) {
1764 Result = Op(LHS, RHS);
1765 return true;
1766 }
Richard Smith43e77732013-05-07 04:50:00 +00001767
1768 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001769 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001770 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001771 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001772 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001773 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001774 << Result.toString(10) << E->getType();
1775 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001776 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001777 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001778 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001779}
1780
1781/// Perform the given binary integer operation.
1782static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1783 BinaryOperatorKind Opcode, APSInt RHS,
1784 APSInt &Result) {
1785 switch (Opcode) {
1786 default:
1787 Info.Diag(E);
1788 return false;
1789 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001790 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1791 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001792 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001793 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1794 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001795 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001796 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1797 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001798 case BO_And: Result = LHS & RHS; return true;
1799 case BO_Xor: Result = LHS ^ RHS; return true;
1800 case BO_Or: Result = LHS | RHS; return true;
1801 case BO_Div:
1802 case BO_Rem:
1803 if (RHS == 0) {
1804 Info.Diag(E, diag::note_expr_divide_by_zero);
1805 return false;
1806 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001807 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1808 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1809 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001810 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1811 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001812 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1813 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001814 return true;
1815 case BO_Shl: {
1816 if (Info.getLangOpts().OpenCL)
1817 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1818 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1819 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1820 RHS.isUnsigned());
1821 else if (RHS.isSigned() && RHS.isNegative()) {
1822 // During constant-folding, a negative shift is an opposite shift. Such
1823 // a shift is not a constant expression.
1824 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1825 RHS = -RHS;
1826 goto shift_right;
1827 }
1828 shift_left:
1829 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1830 // the shifted type.
1831 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1832 if (SA != RHS) {
1833 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1834 << RHS << E->getType() << LHS.getBitWidth();
1835 } else if (LHS.isSigned()) {
1836 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1837 // operand, and must not overflow the corresponding unsigned type.
1838 if (LHS.isNegative())
1839 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1840 else if (LHS.countLeadingZeros() < SA)
1841 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1842 }
1843 Result = LHS << SA;
1844 return true;
1845 }
1846 case BO_Shr: {
1847 if (Info.getLangOpts().OpenCL)
1848 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1849 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1850 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1851 RHS.isUnsigned());
1852 else if (RHS.isSigned() && RHS.isNegative()) {
1853 // During constant-folding, a negative shift is an opposite shift. Such a
1854 // shift is not a constant expression.
1855 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1856 RHS = -RHS;
1857 goto shift_left;
1858 }
1859 shift_right:
1860 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1861 // shifted type.
1862 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1863 if (SA != RHS)
1864 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1865 << RHS << E->getType() << LHS.getBitWidth();
1866 Result = LHS >> SA;
1867 return true;
1868 }
1869
1870 case BO_LT: Result = LHS < RHS; return true;
1871 case BO_GT: Result = LHS > RHS; return true;
1872 case BO_LE: Result = LHS <= RHS; return true;
1873 case BO_GE: Result = LHS >= RHS; return true;
1874 case BO_EQ: Result = LHS == RHS; return true;
1875 case BO_NE: Result = LHS != RHS; return true;
1876 }
1877}
1878
Richard Smith861b5b52013-05-07 23:34:45 +00001879/// Perform the given binary floating-point operation, in-place, on LHS.
1880static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1881 APFloat &LHS, BinaryOperatorKind Opcode,
1882 const APFloat &RHS) {
1883 switch (Opcode) {
1884 default:
1885 Info.Diag(E);
1886 return false;
1887 case BO_Mul:
1888 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1889 break;
1890 case BO_Add:
1891 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1892 break;
1893 case BO_Sub:
1894 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1895 break;
1896 case BO_Div:
1897 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1898 break;
1899 }
1900
Richard Smith0c6124b2015-12-03 01:36:22 +00001901 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001902 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001903 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001904 }
Richard Smith861b5b52013-05-07 23:34:45 +00001905 return true;
1906}
1907
Richard Smitha8105bc2012-01-06 16:39:00 +00001908/// Cast an lvalue referring to a base subobject to a derived class, by
1909/// truncating the lvalue's path to the given length.
1910static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1911 const RecordDecl *TruncatedType,
1912 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001913 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001914
1915 // Check we actually point to a derived class object.
1916 if (TruncatedElements == D.Entries.size())
1917 return true;
1918 assert(TruncatedElements >= D.MostDerivedPathLength &&
1919 "not casting to a derived class");
1920 if (!Result.checkSubobject(Info, E, CSK_Derived))
1921 return false;
1922
1923 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001924 const RecordDecl *RD = TruncatedType;
1925 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001926 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001927 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1928 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001929 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001930 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001931 else
Richard Smithd62306a2011-11-10 06:34:14 +00001932 Result.Offset -= Layout.getBaseClassOffset(Base);
1933 RD = Base;
1934 }
Richard Smith027bf112011-11-17 22:56:20 +00001935 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001936 return true;
1937}
1938
John McCalld7bca762012-05-01 00:38:49 +00001939static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001940 const CXXRecordDecl *Derived,
1941 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001942 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001943 if (!RL) {
1944 if (Derived->isInvalidDecl()) return false;
1945 RL = &Info.Ctx.getASTRecordLayout(Derived);
1946 }
1947
Richard Smithd62306a2011-11-10 06:34:14 +00001948 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001949 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001950 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001951}
1952
Richard Smitha8105bc2012-01-06 16:39:00 +00001953static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001954 const CXXRecordDecl *DerivedDecl,
1955 const CXXBaseSpecifier *Base) {
1956 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1957
John McCalld7bca762012-05-01 00:38:49 +00001958 if (!Base->isVirtual())
1959 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001960
Richard Smitha8105bc2012-01-06 16:39:00 +00001961 SubobjectDesignator &D = Obj.Designator;
1962 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001963 return false;
1964
Richard Smitha8105bc2012-01-06 16:39:00 +00001965 // Extract most-derived object and corresponding type.
1966 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1967 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1968 return false;
1969
1970 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001971 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001972 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1973 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001974 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001975 return true;
1976}
1977
Richard Smith84401042013-06-03 05:03:02 +00001978static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1979 QualType Type, LValue &Result) {
1980 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1981 PathE = E->path_end();
1982 PathI != PathE; ++PathI) {
1983 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1984 *PathI))
1985 return false;
1986 Type = (*PathI)->getType();
1987 }
1988 return true;
1989}
1990
Richard Smithd62306a2011-11-10 06:34:14 +00001991/// Update LVal to refer to the given field, which must be a member of the type
1992/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001993static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001994 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001995 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001996 if (!RL) {
1997 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001998 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001999 }
Richard Smithd62306a2011-11-10 06:34:14 +00002000
2001 unsigned I = FD->getFieldIndex();
2002 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002003 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002004 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002005}
2006
Richard Smith1b78b3d2012-01-25 22:15:11 +00002007/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002008static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002009 LValue &LVal,
2010 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002011 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002012 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002013 return false;
2014 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002015}
2016
Richard Smithd62306a2011-11-10 06:34:14 +00002017/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002018static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2019 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002020 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2021 // extension.
2022 if (Type->isVoidType() || Type->isFunctionType()) {
2023 Size = CharUnits::One();
2024 return true;
2025 }
2026
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002027 if (Type->isDependentType()) {
2028 Info.Diag(Loc);
2029 return false;
2030 }
2031
Richard Smithd62306a2011-11-10 06:34:14 +00002032 if (!Type->isConstantSizeType()) {
2033 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002034 // FIXME: Better diagnostic.
2035 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002036 return false;
2037 }
2038
2039 Size = Info.Ctx.getTypeSizeInChars(Type);
2040 return true;
2041}
2042
2043/// Update a pointer value to model pointer arithmetic.
2044/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002045/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002046/// \param LVal - The pointer value to be updated.
2047/// \param EltTy - The pointee type represented by LVal.
2048/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002049static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2050 LValue &LVal, QualType EltTy,
2051 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002052 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002053 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002054 return false;
2055
2056 // Compute the new offset in the appropriate width.
2057 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002058 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002059 return true;
2060}
2061
Richard Smith66c96992012-02-18 22:04:06 +00002062/// Update an lvalue to refer to a component of a complex number.
2063/// \param Info - Information about the ongoing evaluation.
2064/// \param LVal - The lvalue to be updated.
2065/// \param EltTy - The complex number's component type.
2066/// \param Imag - False for the real component, true for the imaginary.
2067static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2068 LValue &LVal, QualType EltTy,
2069 bool Imag) {
2070 if (Imag) {
2071 CharUnits SizeOfComponent;
2072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2073 return false;
2074 LVal.Offset += SizeOfComponent;
2075 }
2076 LVal.addComplex(Info, E, EltTy, Imag);
2077 return true;
2078}
2079
Richard Smith27908702011-10-24 17:54:18 +00002080/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002081///
2082/// \param Info Information about the ongoing evaluation.
2083/// \param E An expression to be used when printing diagnostics.
2084/// \param VD The variable whose initializer should be obtained.
2085/// \param Frame The frame in which the variable was created. Must be null
2086/// if this variable is not local to the evaluation.
2087/// \param Result Filled in with a pointer to the value of the variable.
2088static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2089 const VarDecl *VD, CallStackFrame *Frame,
2090 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002091 // If this is a parameter to an active constexpr function call, perform
2092 // argument substitution.
2093 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002094 // Assume arguments of a potential constant expression are unknown
2095 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002096 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002097 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002098 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002099 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002100 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002101 }
Richard Smith3229b742013-05-05 21:17:10 +00002102 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002103 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002104 }
Richard Smith27908702011-10-24 17:54:18 +00002105
Richard Smithd9f663b2013-04-22 15:31:51 +00002106 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002107 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002108 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002109 if (!Result) {
2110 // Assume variables referenced within a lambda's call operator that were
2111 // not declared within the call operator are captures and during checking
2112 // of a potential constant expression, assume they are unknown constant
2113 // expressions.
2114 assert(isLambdaCallOperator(Frame->Callee) &&
2115 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2116 "missing value for local variable");
2117 if (Info.checkingPotentialConstantExpression())
2118 return false;
2119 // FIXME: implement capture evaluation during constant expr evaluation.
2120 Info.Diag(E->getLocStart(),
2121 diag::note_unimplemented_constexpr_lambda_feature_ast)
2122 << "captures not currently allowed";
2123 return false;
2124 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002125 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002126 }
2127
Richard Smithd0b4dd62011-12-19 06:19:21 +00002128 // Dig out the initializer, and use the declaration which it's attached to.
2129 const Expr *Init = VD->getAnyInitializer(VD);
2130 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002131 // If we're checking a potential constant expression, the variable could be
2132 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002133 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002134 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002135 return false;
2136 }
2137
Richard Smithd62306a2011-11-10 06:34:14 +00002138 // If we're currently evaluating the initializer of this declaration, use that
2139 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002140 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002141 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002142 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002143 }
2144
Richard Smithcecf1842011-11-01 21:06:14 +00002145 // Never evaluate the initializer of a weak variable. We can't be sure that
2146 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002147 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002148 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002150 }
Richard Smithcecf1842011-11-01 21:06:14 +00002151
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 // Check that we can fold the initializer. In C++, we will have already done
2153 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002154 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002155 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002156 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002157 Notes.size() + 1) << VD;
2158 Info.Note(VD->getLocation(), diag::note_declared_at);
2159 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002160 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002161 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002162 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002163 Notes.size() + 1) << VD;
2164 Info.Note(VD->getLocation(), diag::note_declared_at);
2165 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 }
Richard Smith27908702011-10-24 17:54:18 +00002167
Richard Smith3229b742013-05-05 21:17:10 +00002168 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002169 return true;
Richard Smith27908702011-10-24 17:54:18 +00002170}
2171
Richard Smith11562c52011-10-28 17:51:58 +00002172static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002173 Qualifiers Quals = T.getQualifiers();
2174 return Quals.hasConst() && !Quals.hasVolatile();
2175}
2176
Richard Smithe97cbd72011-11-11 04:05:33 +00002177/// Get the base index of the given base class within an APValue representing
2178/// the given derived class.
2179static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2180 const CXXRecordDecl *Base) {
2181 Base = Base->getCanonicalDecl();
2182 unsigned Index = 0;
2183 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2184 E = Derived->bases_end(); I != E; ++I, ++Index) {
2185 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2186 return Index;
2187 }
2188
2189 llvm_unreachable("base class missing from derived class's bases list");
2190}
2191
Richard Smith3da88fa2013-04-26 14:36:30 +00002192/// Extract the value of a character from a string literal.
2193static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2194 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002195 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2196 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2197 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002198 const StringLiteral *S = cast<StringLiteral>(Lit);
2199 const ConstantArrayType *CAT =
2200 Info.Ctx.getAsConstantArrayType(S->getType());
2201 assert(CAT && "string literal isn't an array");
2202 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002203 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002204
2205 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002206 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002207 if (Index < S->getLength())
2208 Value = S->getCodeUnit(Index);
2209 return Value;
2210}
2211
Richard Smith3da88fa2013-04-26 14:36:30 +00002212// Expand a string literal into an array of characters.
2213static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2214 APValue &Result) {
2215 const StringLiteral *S = cast<StringLiteral>(Lit);
2216 const ConstantArrayType *CAT =
2217 Info.Ctx.getAsConstantArrayType(S->getType());
2218 assert(CAT && "string literal isn't an array");
2219 QualType CharType = CAT->getElementType();
2220 assert(CharType->isIntegerType() && "unexpected character type");
2221
2222 unsigned Elts = CAT->getSize().getZExtValue();
2223 Result = APValue(APValue::UninitArray(),
2224 std::min(S->getLength(), Elts), Elts);
2225 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2226 CharType->isUnsignedIntegerType());
2227 if (Result.hasArrayFiller())
2228 Result.getArrayFiller() = APValue(Value);
2229 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2230 Value = S->getCodeUnit(I);
2231 Result.getArrayInitializedElt(I) = APValue(Value);
2232 }
2233}
2234
2235// Expand an array so that it has more than Index filled elements.
2236static void expandArray(APValue &Array, unsigned Index) {
2237 unsigned Size = Array.getArraySize();
2238 assert(Index < Size);
2239
2240 // Always at least double the number of elements for which we store a value.
2241 unsigned OldElts = Array.getArrayInitializedElts();
2242 unsigned NewElts = std::max(Index+1, OldElts * 2);
2243 NewElts = std::min(Size, std::max(NewElts, 8u));
2244
2245 // Copy the data across.
2246 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2247 for (unsigned I = 0; I != OldElts; ++I)
2248 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2249 for (unsigned I = OldElts; I != NewElts; ++I)
2250 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2251 if (NewValue.hasArrayFiller())
2252 NewValue.getArrayFiller() = Array.getArrayFiller();
2253 Array.swap(NewValue);
2254}
2255
Richard Smithb01fe402014-09-16 01:24:02 +00002256/// Determine whether a type would actually be read by an lvalue-to-rvalue
2257/// conversion. If it's of class type, we may assume that the copy operation
2258/// is trivial. Note that this is never true for a union type with fields
2259/// (because the copy always "reads" the active member) and always true for
2260/// a non-class type.
2261static bool isReadByLvalueToRvalueConversion(QualType T) {
2262 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2263 if (!RD || (RD->isUnion() && !RD->field_empty()))
2264 return true;
2265 if (RD->isEmpty())
2266 return false;
2267
2268 for (auto *Field : RD->fields())
2269 if (isReadByLvalueToRvalueConversion(Field->getType()))
2270 return true;
2271
2272 for (auto &BaseSpec : RD->bases())
2273 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2274 return true;
2275
2276 return false;
2277}
2278
2279/// Diagnose an attempt to read from any unreadable field within the specified
2280/// type, which might be a class type.
2281static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2282 QualType T) {
2283 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2284 if (!RD)
2285 return false;
2286
2287 if (!RD->hasMutableFields())
2288 return false;
2289
2290 for (auto *Field : RD->fields()) {
2291 // If we're actually going to read this field in some way, then it can't
2292 // be mutable. If we're in a union, then assigning to a mutable field
2293 // (even an empty one) can change the active member, so that's not OK.
2294 // FIXME: Add core issue number for the union case.
2295 if (Field->isMutable() &&
2296 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2297 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2298 Info.Note(Field->getLocation(), diag::note_declared_at);
2299 return true;
2300 }
2301
2302 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2303 return true;
2304 }
2305
2306 for (auto &BaseSpec : RD->bases())
2307 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2308 return true;
2309
2310 // All mutable fields were empty, and thus not actually read.
2311 return false;
2312}
2313
Richard Smith861b5b52013-05-07 23:34:45 +00002314/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002315enum AccessKinds {
2316 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002317 AK_Assign,
2318 AK_Increment,
2319 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002320};
2321
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002322namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002323/// A handle to a complete object (an object that is not a subobject of
2324/// another object).
2325struct CompleteObject {
2326 /// The value of the complete object.
2327 APValue *Value;
2328 /// The type of the complete object.
2329 QualType Type;
2330
Craig Topper36250ad2014-05-12 05:36:57 +00002331 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002332 CompleteObject(APValue *Value, QualType Type)
2333 : Value(Value), Type(Type) {
2334 assert(Value && "missing value for complete object");
2335 }
2336
Aaron Ballman67347662015-02-15 22:00:28 +00002337 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002338};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002339} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002340
Richard Smith3da88fa2013-04-26 14:36:30 +00002341/// Find the designated sub-object of an rvalue.
2342template<typename SubobjectHandler>
2343typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002344findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002345 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002346 if (Sub.Invalid)
2347 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002348 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002349 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002350 if (Info.getLangOpts().CPlusPlus11)
2351 Info.Diag(E, diag::note_constexpr_access_past_end)
2352 << handler.AccessKind;
2353 else
2354 Info.Diag(E);
2355 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002356 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002357
Richard Smith3229b742013-05-05 21:17:10 +00002358 APValue *O = Obj.Value;
2359 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002360 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002361
Richard Smithd62306a2011-11-10 06:34:14 +00002362 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002363 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2364 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002365 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002366 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2367 return handler.failed();
2368 }
2369
Richard Smith49ca8aa2013-08-06 07:09:20 +00002370 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002371 // If we are reading an object of class type, there may still be more
2372 // things we need to check: if there are any mutable subobjects, we
2373 // cannot perform this read. (This only happens when performing a trivial
2374 // copy or assignment.)
2375 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2376 diagnoseUnreadableFields(Info, E, ObjType))
2377 return handler.failed();
2378
Richard Smith49ca8aa2013-08-06 07:09:20 +00002379 if (!handler.found(*O, ObjType))
2380 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002381
Richard Smith49ca8aa2013-08-06 07:09:20 +00002382 // If we modified a bit-field, truncate it to the right width.
2383 if (handler.AccessKind != AK_Read &&
2384 LastField && LastField->isBitField() &&
2385 !truncateBitfieldValue(Info, E, *O, LastField))
2386 return false;
2387
2388 return true;
2389 }
2390
Craig Topper36250ad2014-05-12 05:36:57 +00002391 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002392 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002393 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002394 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002395 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002396 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002397 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002398 // Note, it should not be possible to form a pointer with a valid
2399 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002400 if (Info.getLangOpts().CPlusPlus11)
2401 Info.Diag(E, diag::note_constexpr_access_past_end)
2402 << handler.AccessKind;
2403 else
2404 Info.Diag(E);
2405 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002406 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002407
2408 ObjType = CAT->getElementType();
2409
Richard Smith14a94132012-02-17 03:35:37 +00002410 // An array object is represented as either an Array APValue or as an
2411 // LValue which refers to a string literal.
2412 if (O->isLValue()) {
2413 assert(I == N - 1 && "extracting subobject of character?");
2414 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002415 if (handler.AccessKind != AK_Read)
2416 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2417 *O);
2418 else
2419 return handler.foundString(*O, ObjType, Index);
2420 }
2421
2422 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002423 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002424 else if (handler.AccessKind != AK_Read) {
2425 expandArray(*O, Index);
2426 O = &O->getArrayInitializedElt(Index);
2427 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002428 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002429 } else if (ObjType->isAnyComplexType()) {
2430 // Next subobject is a complex number.
2431 uint64_t Index = Sub.Entries[I].ArrayIndex;
2432 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002433 if (Info.getLangOpts().CPlusPlus11)
2434 Info.Diag(E, diag::note_constexpr_access_past_end)
2435 << handler.AccessKind;
2436 else
2437 Info.Diag(E);
2438 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002439 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002440
2441 bool WasConstQualified = ObjType.isConstQualified();
2442 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2443 if (WasConstQualified)
2444 ObjType.addConst();
2445
Richard Smith66c96992012-02-18 22:04:06 +00002446 assert(I == N - 1 && "extracting subobject of scalar?");
2447 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002448 return handler.found(Index ? O->getComplexIntImag()
2449 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002450 } else {
2451 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 return handler.found(Index ? O->getComplexFloatImag()
2453 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002454 }
Richard Smithd62306a2011-11-10 06:34:14 +00002455 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002456 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002457 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002458 << Field;
2459 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002460 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002461 }
2462
Richard Smithd62306a2011-11-10 06:34:14 +00002463 // Next subobject is a class, struct or union field.
2464 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2465 if (RD->isUnion()) {
2466 const FieldDecl *UnionField = O->getUnionField();
2467 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002468 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002469 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2470 << handler.AccessKind << Field << !UnionField << UnionField;
2471 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002472 }
Richard Smithd62306a2011-11-10 06:34:14 +00002473 O = &O->getUnionValue();
2474 } else
2475 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002476
2477 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002478 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 if (WasConstQualified && !Field->isMutable())
2480 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002481
2482 if (ObjType.isVolatileQualified()) {
2483 if (Info.getLangOpts().CPlusPlus) {
2484 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002485 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2486 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002487 Info.Note(Field->getLocation(), diag::note_declared_at);
2488 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002489 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002490 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002491 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002492 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002493
2494 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002495 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002496 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002497 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2498 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2499 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002500
2501 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002502 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002503 if (WasConstQualified)
2504 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002505 }
2506 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002507}
2508
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002509namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002510struct ExtractSubobjectHandler {
2511 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002512 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002513
2514 static const AccessKinds AccessKind = AK_Read;
2515
2516 typedef bool result_type;
2517 bool failed() { return false; }
2518 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002519 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002520 return true;
2521 }
2522 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002523 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002524 return true;
2525 }
2526 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002527 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002528 return true;
2529 }
2530 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002531 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002532 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2533 return true;
2534 }
2535};
Richard Smith3229b742013-05-05 21:17:10 +00002536} // end anonymous namespace
2537
Richard Smith3da88fa2013-04-26 14:36:30 +00002538const AccessKinds ExtractSubobjectHandler::AccessKind;
2539
2540/// Extract the designated sub-object of an rvalue.
2541static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002542 const CompleteObject &Obj,
2543 const SubobjectDesignator &Sub,
2544 APValue &Result) {
2545 ExtractSubobjectHandler Handler = { Info, Result };
2546 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002547}
2548
Richard Smith3229b742013-05-05 21:17:10 +00002549namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002550struct ModifySubobjectHandler {
2551 EvalInfo &Info;
2552 APValue &NewVal;
2553 const Expr *E;
2554
2555 typedef bool result_type;
2556 static const AccessKinds AccessKind = AK_Assign;
2557
2558 bool checkConst(QualType QT) {
2559 // Assigning to a const object has undefined behavior.
2560 if (QT.isConstQualified()) {
2561 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2562 return false;
2563 }
2564 return true;
2565 }
2566
2567 bool failed() { return false; }
2568 bool found(APValue &Subobj, QualType SubobjType) {
2569 if (!checkConst(SubobjType))
2570 return false;
2571 // We've been given ownership of NewVal, so just swap it in.
2572 Subobj.swap(NewVal);
2573 return true;
2574 }
2575 bool found(APSInt &Value, QualType SubobjType) {
2576 if (!checkConst(SubobjType))
2577 return false;
2578 if (!NewVal.isInt()) {
2579 // Maybe trying to write a cast pointer value into a complex?
2580 Info.Diag(E);
2581 return false;
2582 }
2583 Value = NewVal.getInt();
2584 return true;
2585 }
2586 bool found(APFloat &Value, QualType SubobjType) {
2587 if (!checkConst(SubobjType))
2588 return false;
2589 Value = NewVal.getFloat();
2590 return true;
2591 }
2592 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2593 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2594 }
2595};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002596} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002597
Richard Smith3229b742013-05-05 21:17:10 +00002598const AccessKinds ModifySubobjectHandler::AccessKind;
2599
Richard Smith3da88fa2013-04-26 14:36:30 +00002600/// Update the designated sub-object of an rvalue to the given value.
2601static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002602 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002603 const SubobjectDesignator &Sub,
2604 APValue &NewVal) {
2605 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002606 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002607}
2608
Richard Smith84f6dcf2012-02-02 01:16:57 +00002609/// Find the position where two subobject designators diverge, or equivalently
2610/// the length of the common initial subsequence.
2611static unsigned FindDesignatorMismatch(QualType ObjType,
2612 const SubobjectDesignator &A,
2613 const SubobjectDesignator &B,
2614 bool &WasArrayIndex) {
2615 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2616 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002617 if (!ObjType.isNull() &&
2618 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002619 // Next subobject is an array element.
2620 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2621 WasArrayIndex = true;
2622 return I;
2623 }
Richard Smith66c96992012-02-18 22:04:06 +00002624 if (ObjType->isAnyComplexType())
2625 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2626 else
2627 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002628 } else {
2629 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2630 WasArrayIndex = false;
2631 return I;
2632 }
2633 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2634 // Next subobject is a field.
2635 ObjType = FD->getType();
2636 else
2637 // Next subobject is a base class.
2638 ObjType = QualType();
2639 }
2640 }
2641 WasArrayIndex = false;
2642 return I;
2643}
2644
2645/// Determine whether the given subobject designators refer to elements of the
2646/// same array object.
2647static bool AreElementsOfSameArray(QualType ObjType,
2648 const SubobjectDesignator &A,
2649 const SubobjectDesignator &B) {
2650 if (A.Entries.size() != B.Entries.size())
2651 return false;
2652
George Burgess IVa51c4072015-10-16 01:49:01 +00002653 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002654 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2655 // A is a subobject of the array element.
2656 return false;
2657
2658 // If A (and B) designates an array element, the last entry will be the array
2659 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2660 // of length 1' case, and the entire path must match.
2661 bool WasArrayIndex;
2662 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2663 return CommonLength >= A.Entries.size() - IsArray;
2664}
2665
Richard Smith3229b742013-05-05 21:17:10 +00002666/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002667static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2668 AccessKinds AK, const LValue &LVal,
2669 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002670 if (!LVal.Base) {
2671 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2672 return CompleteObject();
2673 }
2674
Craig Topper36250ad2014-05-12 05:36:57 +00002675 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002676 if (LVal.CallIndex) {
2677 Frame = Info.getCallFrame(LVal.CallIndex);
2678 if (!Frame) {
2679 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2680 << AK << LVal.Base.is<const ValueDecl*>();
2681 NoteLValueLocation(Info, LVal.Base);
2682 return CompleteObject();
2683 }
Richard Smith3229b742013-05-05 21:17:10 +00002684 }
2685
2686 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2687 // is not a constant expression (even if the object is non-volatile). We also
2688 // apply this rule to C++98, in order to conform to the expected 'volatile'
2689 // semantics.
2690 if (LValType.isVolatileQualified()) {
2691 if (Info.getLangOpts().CPlusPlus)
2692 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2693 << AK << LValType;
2694 else
2695 Info.Diag(E);
2696 return CompleteObject();
2697 }
2698
2699 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002700 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002701 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002702
2703 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2704 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2705 // In C++11, constexpr, non-volatile variables initialized with constant
2706 // expressions are constant expressions too. Inside constexpr functions,
2707 // parameters are constant expressions even if they're non-const.
2708 // In C++1y, objects local to a constant expression (those with a Frame) are
2709 // both readable and writable inside constant expressions.
2710 // In C, such things can also be folded, although they are not ICEs.
2711 const VarDecl *VD = dyn_cast<VarDecl>(D);
2712 if (VD) {
2713 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2714 VD = VDef;
2715 }
2716 if (!VD || VD->isInvalidDecl()) {
2717 Info.Diag(E);
2718 return CompleteObject();
2719 }
2720
2721 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002722 if (BaseType.isVolatileQualified()) {
2723 if (Info.getLangOpts().CPlusPlus) {
2724 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2725 << AK << 1 << VD;
2726 Info.Note(VD->getLocation(), diag::note_declared_at);
2727 } else {
2728 Info.Diag(E);
2729 }
2730 return CompleteObject();
2731 }
2732
2733 // Unless we're looking at a local variable or argument in a constexpr call,
2734 // the variable we're reading must be const.
2735 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002736 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002737 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2738 // OK, we can read and modify an object if we're in the process of
2739 // evaluating its initializer, because its lifetime began in this
2740 // evaluation.
2741 } else if (AK != AK_Read) {
2742 // All the remaining cases only permit reading.
2743 Info.Diag(E, diag::note_constexpr_modify_global);
2744 return CompleteObject();
2745 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002746 // OK, we can read this variable.
2747 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002748 // In OpenCL if a variable is in constant address space it is a const value.
2749 if (!(BaseType.isConstQualified() ||
2750 (Info.getLangOpts().OpenCL &&
2751 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002752 if (Info.getLangOpts().CPlusPlus) {
2753 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2754 Info.Note(VD->getLocation(), diag::note_declared_at);
2755 } else {
2756 Info.Diag(E);
2757 }
2758 return CompleteObject();
2759 }
2760 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2761 // We support folding of const floating-point types, in order to make
2762 // static const data members of such types (supported as an extension)
2763 // more useful.
2764 if (Info.getLangOpts().CPlusPlus11) {
2765 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2766 Info.Note(VD->getLocation(), diag::note_declared_at);
2767 } else {
2768 Info.CCEDiag(E);
2769 }
2770 } else {
2771 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002772 if (Info.checkingPotentialConstantExpression() &&
2773 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2774 // The definition of this variable could be constexpr. We can't
2775 // access it right now, but may be able to in future.
2776 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith3229b742013-05-05 21:17:10 +00002777 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2778 Info.Note(VD->getLocation(), diag::note_declared_at);
2779 } else {
2780 Info.Diag(E);
2781 }
2782 return CompleteObject();
2783 }
2784 }
2785
2786 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2787 return CompleteObject();
2788 } else {
2789 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2790
2791 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002792 if (const MaterializeTemporaryExpr *MTE =
2793 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2794 assert(MTE->getStorageDuration() == SD_Static &&
2795 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002796
Richard Smithe6c01442013-06-05 00:46:14 +00002797 // Per C++1y [expr.const]p2:
2798 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2799 // - a [...] glvalue of integral or enumeration type that refers to
2800 // a non-volatile const object [...]
2801 // [...]
2802 // - a [...] glvalue of literal type that refers to a non-volatile
2803 // object whose lifetime began within the evaluation of e.
2804 //
2805 // C++11 misses the 'began within the evaluation of e' check and
2806 // instead allows all temporaries, including things like:
2807 // int &&r = 1;
2808 // int x = ++r;
2809 // constexpr int k = r;
2810 // Therefore we use the C++1y rules in C++11 too.
2811 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2812 const ValueDecl *ED = MTE->getExtendingDecl();
2813 if (!(BaseType.isConstQualified() &&
2814 BaseType->isIntegralOrEnumerationType()) &&
2815 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2816 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2817 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2818 return CompleteObject();
2819 }
2820
2821 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2822 assert(BaseVal && "got reference to unevaluated temporary");
2823 } else {
2824 Info.Diag(E);
2825 return CompleteObject();
2826 }
2827 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002828 BaseVal = Frame->getTemporary(Base);
2829 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002830 }
Richard Smith3229b742013-05-05 21:17:10 +00002831
2832 // Volatile temporary objects cannot be accessed in constant expressions.
2833 if (BaseType.isVolatileQualified()) {
2834 if (Info.getLangOpts().CPlusPlus) {
2835 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2836 << AK << 0;
2837 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2838 } else {
2839 Info.Diag(E);
2840 }
2841 return CompleteObject();
2842 }
2843 }
2844
Richard Smith7525ff62013-05-09 07:14:00 +00002845 // During the construction of an object, it is not yet 'const'.
2846 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2847 // and this doesn't do quite the right thing for const subobjects of the
2848 // object under construction.
2849 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2850 BaseType = Info.Ctx.getCanonicalType(BaseType);
2851 BaseType.removeLocalConst();
2852 }
2853
Richard Smith6d4c6582013-11-05 22:18:15 +00002854 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002855 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002856 //
2857 // FIXME: Not all local state is mutable. Allow local constant subobjects
2858 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002859 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2860 Info.EvalStatus.HasSideEffects) ||
2861 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002862 return CompleteObject();
2863
2864 return CompleteObject(BaseVal, BaseType);
2865}
2866
Richard Smith243ef902013-05-05 23:31:59 +00002867/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2868/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2869/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002870///
2871/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002872/// \param Conv - The expression for which we are performing the conversion.
2873/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002874/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2875/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002876/// \param LVal - The glvalue on which we are attempting to perform this action.
2877/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002878static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002879 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002880 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002881 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002882 return false;
2883
Richard Smith3229b742013-05-05 21:17:10 +00002884 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002885 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002886 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002887 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2888 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2889 // initializer until now for such expressions. Such an expression can't be
2890 // an ICE in C, so this only matters for fold.
2891 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2892 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002893 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002894 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002895 }
Richard Smith3229b742013-05-05 21:17:10 +00002896 APValue Lit;
2897 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2898 return false;
2899 CompleteObject LitObj(&Lit, Base->getType());
2900 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002901 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002902 // We represent a string literal array as an lvalue pointing at the
2903 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002904 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002905 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2906 CompleteObject StrObj(&Str, Base->getType());
2907 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002908 }
Richard Smith11562c52011-10-28 17:51:58 +00002909 }
2910
Richard Smith3229b742013-05-05 21:17:10 +00002911 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2912 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002913}
2914
2915/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002916static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002917 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002918 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002919 return false;
2920
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002921 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002922 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002923 return false;
2924 }
2925
Richard Smith3229b742013-05-05 21:17:10 +00002926 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2927 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002928}
2929
Richard Smith243ef902013-05-05 23:31:59 +00002930static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2931 return T->isSignedIntegerType() &&
2932 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2933}
2934
2935namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002936struct CompoundAssignSubobjectHandler {
2937 EvalInfo &Info;
2938 const Expr *E;
2939 QualType PromotedLHSType;
2940 BinaryOperatorKind Opcode;
2941 const APValue &RHS;
2942
2943 static const AccessKinds AccessKind = AK_Assign;
2944
2945 typedef bool result_type;
2946
2947 bool checkConst(QualType QT) {
2948 // Assigning to a const object has undefined behavior.
2949 if (QT.isConstQualified()) {
2950 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2951 return false;
2952 }
2953 return true;
2954 }
2955
2956 bool failed() { return false; }
2957 bool found(APValue &Subobj, QualType SubobjType) {
2958 switch (Subobj.getKind()) {
2959 case APValue::Int:
2960 return found(Subobj.getInt(), SubobjType);
2961 case APValue::Float:
2962 return found(Subobj.getFloat(), SubobjType);
2963 case APValue::ComplexInt:
2964 case APValue::ComplexFloat:
2965 // FIXME: Implement complex compound assignment.
2966 Info.Diag(E);
2967 return false;
2968 case APValue::LValue:
2969 return foundPointer(Subobj, SubobjType);
2970 default:
2971 // FIXME: can this happen?
2972 Info.Diag(E);
2973 return false;
2974 }
2975 }
2976 bool found(APSInt &Value, QualType SubobjType) {
2977 if (!checkConst(SubobjType))
2978 return false;
2979
2980 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2981 // We don't support compound assignment on integer-cast-to-pointer
2982 // values.
2983 Info.Diag(E);
2984 return false;
2985 }
2986
2987 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2988 SubobjType, Value);
2989 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2990 return false;
2991 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2992 return true;
2993 }
2994 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002995 return checkConst(SubobjType) &&
2996 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2997 Value) &&
2998 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2999 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003000 }
3001 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3002 if (!checkConst(SubobjType))
3003 return false;
3004
3005 QualType PointeeType;
3006 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3007 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003008
3009 if (PointeeType.isNull() || !RHS.isInt() ||
3010 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00003011 Info.Diag(E);
3012 return false;
3013 }
3014
Richard Smith861b5b52013-05-07 23:34:45 +00003015 int64_t Offset = getExtValue(RHS.getInt());
3016 if (Opcode == BO_Sub)
3017 Offset = -Offset;
3018
3019 LValue LVal;
3020 LVal.setFrom(Info.Ctx, Subobj);
3021 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3022 return false;
3023 LVal.moveInto(Subobj);
3024 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003025 }
3026 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3027 llvm_unreachable("shouldn't encounter string elements here");
3028 }
3029};
3030} // end anonymous namespace
3031
3032const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3033
3034/// Perform a compound assignment of LVal <op>= RVal.
3035static bool handleCompoundAssignment(
3036 EvalInfo &Info, const Expr *E,
3037 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3038 BinaryOperatorKind Opcode, const APValue &RVal) {
3039 if (LVal.Designator.Invalid)
3040 return false;
3041
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003042 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00003043 Info.Diag(E);
3044 return false;
3045 }
3046
3047 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3048 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3049 RVal };
3050 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3051}
3052
3053namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003054struct IncDecSubobjectHandler {
3055 EvalInfo &Info;
3056 const Expr *E;
3057 AccessKinds AccessKind;
3058 APValue *Old;
3059
3060 typedef bool result_type;
3061
3062 bool checkConst(QualType QT) {
3063 // Assigning to a const object has undefined behavior.
3064 if (QT.isConstQualified()) {
3065 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
3066 return false;
3067 }
3068 return true;
3069 }
3070
3071 bool failed() { return false; }
3072 bool found(APValue &Subobj, QualType SubobjType) {
3073 // Stash the old value. Also clear Old, so we don't clobber it later
3074 // if we're post-incrementing a complex.
3075 if (Old) {
3076 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003077 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003078 }
3079
3080 switch (Subobj.getKind()) {
3081 case APValue::Int:
3082 return found(Subobj.getInt(), SubobjType);
3083 case APValue::Float:
3084 return found(Subobj.getFloat(), SubobjType);
3085 case APValue::ComplexInt:
3086 return found(Subobj.getComplexIntReal(),
3087 SubobjType->castAs<ComplexType>()->getElementType()
3088 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3089 case APValue::ComplexFloat:
3090 return found(Subobj.getComplexFloatReal(),
3091 SubobjType->castAs<ComplexType>()->getElementType()
3092 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3093 case APValue::LValue:
3094 return foundPointer(Subobj, SubobjType);
3095 default:
3096 // FIXME: can this happen?
3097 Info.Diag(E);
3098 return false;
3099 }
3100 }
3101 bool found(APSInt &Value, QualType SubobjType) {
3102 if (!checkConst(SubobjType))
3103 return false;
3104
3105 if (!SubobjType->isIntegerType()) {
3106 // We don't support increment / decrement on integer-cast-to-pointer
3107 // values.
3108 Info.Diag(E);
3109 return false;
3110 }
3111
3112 if (Old) *Old = APValue(Value);
3113
3114 // bool arithmetic promotes to int, and the conversion back to bool
3115 // doesn't reduce mod 2^n, so special-case it.
3116 if (SubobjType->isBooleanType()) {
3117 if (AccessKind == AK_Increment)
3118 Value = 1;
3119 else
3120 Value = !Value;
3121 return true;
3122 }
3123
3124 bool WasNegative = Value.isNegative();
3125 if (AccessKind == AK_Increment) {
3126 ++Value;
3127
3128 if (!WasNegative && Value.isNegative() &&
3129 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3130 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003131 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003132 }
3133 } else {
3134 --Value;
3135
3136 if (WasNegative && !Value.isNegative() &&
3137 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3138 unsigned BitWidth = Value.getBitWidth();
3139 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3140 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003141 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003142 }
3143 }
3144 return true;
3145 }
3146 bool found(APFloat &Value, QualType SubobjType) {
3147 if (!checkConst(SubobjType))
3148 return false;
3149
3150 if (Old) *Old = APValue(Value);
3151
3152 APFloat One(Value.getSemantics(), 1);
3153 if (AccessKind == AK_Increment)
3154 Value.add(One, APFloat::rmNearestTiesToEven);
3155 else
3156 Value.subtract(One, APFloat::rmNearestTiesToEven);
3157 return true;
3158 }
3159 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3160 if (!checkConst(SubobjType))
3161 return false;
3162
3163 QualType PointeeType;
3164 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3165 PointeeType = PT->getPointeeType();
3166 else {
3167 Info.Diag(E);
3168 return false;
3169 }
3170
3171 LValue LVal;
3172 LVal.setFrom(Info.Ctx, Subobj);
3173 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3174 AccessKind == AK_Increment ? 1 : -1))
3175 return false;
3176 LVal.moveInto(Subobj);
3177 return true;
3178 }
3179 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3180 llvm_unreachable("shouldn't encounter string elements here");
3181 }
3182};
3183} // end anonymous namespace
3184
3185/// Perform an increment or decrement on LVal.
3186static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3187 QualType LValType, bool IsIncrement, APValue *Old) {
3188 if (LVal.Designator.Invalid)
3189 return false;
3190
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003191 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003192 Info.Diag(E);
3193 return false;
3194 }
3195
3196 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3197 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3198 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3199 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3200}
3201
Richard Smithe97cbd72011-11-11 04:05:33 +00003202/// Build an lvalue for the object argument of a member function call.
3203static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3204 LValue &This) {
3205 if (Object->getType()->isPointerType())
3206 return EvaluatePointer(Object, This, Info);
3207
3208 if (Object->isGLValue())
3209 return EvaluateLValue(Object, This, Info);
3210
Richard Smithd9f663b2013-04-22 15:31:51 +00003211 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003212 return EvaluateTemporary(Object, This, Info);
3213
Richard Smith3e79a572014-06-11 19:53:12 +00003214 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003215 return false;
3216}
3217
3218/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3219/// lvalue referring to the result.
3220///
3221/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003222/// \param LV - An lvalue referring to the base of the member pointer.
3223/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003224/// \param IncludeMember - Specifies whether the member itself is included in
3225/// the resulting LValue subobject designator. This is not possible when
3226/// creating a bound member function.
3227/// \return The field or method declaration to which the member pointer refers,
3228/// or 0 if evaluation fails.
3229static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003230 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003231 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003232 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003233 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003234 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003235 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003236 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003237
3238 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3239 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003240 if (!MemPtr.getDecl()) {
3241 // FIXME: Specific diagnostic.
3242 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003243 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003244 }
Richard Smith253c2a32012-01-27 01:14:48 +00003245
Richard Smith027bf112011-11-17 22:56:20 +00003246 if (MemPtr.isDerivedMember()) {
3247 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003248 // The end of the derived-to-base path for the base object must match the
3249 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003250 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003251 LV.Designator.Entries.size()) {
3252 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003253 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003254 }
Richard Smith027bf112011-11-17 22:56:20 +00003255 unsigned PathLengthToMember =
3256 LV.Designator.Entries.size() - MemPtr.Path.size();
3257 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3258 const CXXRecordDecl *LVDecl = getAsBaseClass(
3259 LV.Designator.Entries[PathLengthToMember + I]);
3260 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003261 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3262 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003263 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003264 }
Richard Smith027bf112011-11-17 22:56:20 +00003265 }
3266
3267 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003268 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003269 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003270 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003271 } else if (!MemPtr.Path.empty()) {
3272 // Extend the LValue path with the member pointer's path.
3273 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3274 MemPtr.Path.size() + IncludeMember);
3275
3276 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003277 if (const PointerType *PT = LVType->getAs<PointerType>())
3278 LVType = PT->getPointeeType();
3279 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3280 assert(RD && "member pointer access on non-class-type expression");
3281 // The first class in the path is that of the lvalue.
3282 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3283 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003284 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003285 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003286 RD = Base;
3287 }
3288 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003289 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3290 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003291 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003292 }
3293
3294 // Add the member. Note that we cannot build bound member functions here.
3295 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003296 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003297 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003298 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003299 } else if (const IndirectFieldDecl *IFD =
3300 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003301 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003302 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003303 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003304 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003305 }
Richard Smith027bf112011-11-17 22:56:20 +00003306 }
3307
3308 return MemPtr.getDecl();
3309}
3310
Richard Smith84401042013-06-03 05:03:02 +00003311static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3312 const BinaryOperator *BO,
3313 LValue &LV,
3314 bool IncludeMember = true) {
3315 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3316
3317 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003318 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003319 MemberPtr MemPtr;
3320 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3321 }
Craig Topper36250ad2014-05-12 05:36:57 +00003322 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003323 }
3324
3325 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3326 BO->getRHS(), IncludeMember);
3327}
3328
Richard Smith027bf112011-11-17 22:56:20 +00003329/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3330/// the provided lvalue, which currently refers to the base object.
3331static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3332 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003333 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003334 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003335 return false;
3336
Richard Smitha8105bc2012-01-06 16:39:00 +00003337 QualType TargetQT = E->getType();
3338 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3339 TargetQT = PT->getPointeeType();
3340
3341 // Check this cast lands within the final derived-to-base subobject path.
3342 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003343 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003344 << D.MostDerivedType << TargetQT;
3345 return false;
3346 }
3347
Richard Smith027bf112011-11-17 22:56:20 +00003348 // Check the type of the final cast. We don't need to check the path,
3349 // since a cast can only be formed if the path is unique.
3350 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003351 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3352 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003353 if (NewEntriesSize == D.MostDerivedPathLength)
3354 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3355 else
Richard Smith027bf112011-11-17 22:56:20 +00003356 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003357 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003358 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003359 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003360 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003361 }
Richard Smith027bf112011-11-17 22:56:20 +00003362
3363 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003364 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003365}
3366
Mike Stump876387b2009-10-27 22:09:17 +00003367namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003368enum EvalStmtResult {
3369 /// Evaluation failed.
3370 ESR_Failed,
3371 /// Hit a 'return' statement.
3372 ESR_Returned,
3373 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003374 ESR_Succeeded,
3375 /// Hit a 'continue' statement.
3376 ESR_Continue,
3377 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003378 ESR_Break,
3379 /// Still scanning for 'case' or 'default' statement.
3380 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003381};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003382}
Richard Smith254a73d2011-10-28 22:34:42 +00003383
Richard Smithd9f663b2013-04-22 15:31:51 +00003384static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3385 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3386 // We don't need to evaluate the initializer for a static local.
3387 if (!VD->hasLocalStorage())
3388 return true;
3389
3390 LValue Result;
3391 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003392 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003393
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003394 const Expr *InitE = VD->getInit();
3395 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003396 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3397 << false << VD->getType();
3398 Val = APValue();
3399 return false;
3400 }
3401
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003402 if (InitE->isValueDependent())
3403 return false;
3404
3405 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003406 // Wipe out any partially-computed value, to allow tracking that this
3407 // evaluation failed.
3408 Val = APValue();
3409 return false;
3410 }
3411 }
3412
3413 return true;
3414}
3415
Richard Smith4e18ca52013-05-06 05:56:11 +00003416/// Evaluate a condition (either a variable declaration or an expression).
3417static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3418 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003419 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003420 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3421 return false;
3422 return EvaluateAsBooleanCondition(Cond, Result, Info);
3423}
3424
Richard Smith89210072016-04-04 23:29:43 +00003425namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003426/// \brief A location where the result (returned value) of evaluating a
3427/// statement should be stored.
3428struct StmtResult {
3429 /// The APValue that should be filled in with the returned value.
3430 APValue &Value;
3431 /// The location containing the result, if any (used to support RVO).
3432 const LValue *Slot;
3433};
Richard Smith89210072016-04-04 23:29:43 +00003434}
Richard Smith52a980a2015-08-28 02:43:42 +00003435
3436static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003437 const Stmt *S,
3438 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003439
3440/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003441static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003442 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003443 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003444 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003445 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003446 case ESR_Break:
3447 return ESR_Succeeded;
3448 case ESR_Succeeded:
3449 case ESR_Continue:
3450 return ESR_Continue;
3451 case ESR_Failed:
3452 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003453 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003454 return ESR;
3455 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003456 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003457}
3458
Richard Smith496ddcf2013-05-12 17:32:42 +00003459/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003460static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003461 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003462 BlockScopeRAII Scope(Info);
3463
Richard Smith496ddcf2013-05-12 17:32:42 +00003464 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003465 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003466 {
3467 FullExpressionRAII Scope(Info);
3468 if (SS->getConditionVariable() &&
3469 !EvaluateDecl(Info, SS->getConditionVariable()))
3470 return ESR_Failed;
3471 if (!EvaluateInteger(SS->getCond(), Value, Info))
3472 return ESR_Failed;
3473 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003474
3475 // Find the switch case corresponding to the value of the condition.
3476 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003477 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003478 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3479 SC = SC->getNextSwitchCase()) {
3480 if (isa<DefaultStmt>(SC)) {
3481 Found = SC;
3482 continue;
3483 }
3484
3485 const CaseStmt *CS = cast<CaseStmt>(SC);
3486 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3487 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3488 : LHS;
3489 if (LHS <= Value && Value <= RHS) {
3490 Found = SC;
3491 break;
3492 }
3493 }
3494
3495 if (!Found)
3496 return ESR_Succeeded;
3497
3498 // Search the switch body for the switch case and evaluate it from there.
3499 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3500 case ESR_Break:
3501 return ESR_Succeeded;
3502 case ESR_Succeeded:
3503 case ESR_Continue:
3504 case ESR_Failed:
3505 case ESR_Returned:
3506 return ESR;
3507 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003508 // This can only happen if the switch case is nested within a statement
3509 // expression. We have no intention of supporting that.
3510 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3511 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003512 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003513 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003514}
3515
Richard Smith254a73d2011-10-28 22:34:42 +00003516// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003517static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003518 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003519 if (!Info.nextStep(S))
3520 return ESR_Failed;
3521
Richard Smith496ddcf2013-05-12 17:32:42 +00003522 // If we're hunting down a 'case' or 'default' label, recurse through
3523 // substatements until we hit the label.
3524 if (Case) {
3525 // FIXME: We don't start the lifetime of objects whose initialization we
3526 // jump over. However, such objects must be of class type with a trivial
3527 // default constructor that initialize all subobjects, so must be empty,
3528 // so this almost never matters.
3529 switch (S->getStmtClass()) {
3530 case Stmt::CompoundStmtClass:
3531 // FIXME: Precompute which substatement of a compound statement we
3532 // would jump to, and go straight there rather than performing a
3533 // linear scan each time.
3534 case Stmt::LabelStmtClass:
3535 case Stmt::AttributedStmtClass:
3536 case Stmt::DoStmtClass:
3537 break;
3538
3539 case Stmt::CaseStmtClass:
3540 case Stmt::DefaultStmtClass:
3541 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003542 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003543 break;
3544
3545 case Stmt::IfStmtClass: {
3546 // FIXME: Precompute which side of an 'if' we would jump to, and go
3547 // straight there rather than scanning both sides.
3548 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003549
3550 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3551 // preceded by our switch label.
3552 BlockScopeRAII Scope(Info);
3553
Richard Smith496ddcf2013-05-12 17:32:42 +00003554 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3555 if (ESR != ESR_CaseNotFound || !IS->getElse())
3556 return ESR;
3557 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3558 }
3559
3560 case Stmt::WhileStmtClass: {
3561 EvalStmtResult ESR =
3562 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3563 if (ESR != ESR_Continue)
3564 return ESR;
3565 break;
3566 }
3567
3568 case Stmt::ForStmtClass: {
3569 const ForStmt *FS = cast<ForStmt>(S);
3570 EvalStmtResult ESR =
3571 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3572 if (ESR != ESR_Continue)
3573 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003574 if (FS->getInc()) {
3575 FullExpressionRAII IncScope(Info);
3576 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3577 return ESR_Failed;
3578 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003579 break;
3580 }
3581
3582 case Stmt::DeclStmtClass:
3583 // FIXME: If the variable has initialization that can't be jumped over,
3584 // bail out of any immediately-surrounding compound-statement too.
3585 default:
3586 return ESR_CaseNotFound;
3587 }
3588 }
3589
Richard Smith254a73d2011-10-28 22:34:42 +00003590 switch (S->getStmtClass()) {
3591 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003592 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003593 // Don't bother evaluating beyond an expression-statement which couldn't
3594 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003595 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003596 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003597 return ESR_Failed;
3598 return ESR_Succeeded;
3599 }
3600
3601 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003602 return ESR_Failed;
3603
3604 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003605 return ESR_Succeeded;
3606
Richard Smithd9f663b2013-04-22 15:31:51 +00003607 case Stmt::DeclStmtClass: {
3608 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003609 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003610 // Each declaration initialization is its own full-expression.
3611 // FIXME: This isn't quite right; if we're performing aggregate
3612 // initialization, each braced subexpression is its own full-expression.
3613 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003614 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003615 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003616 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003617 return ESR_Succeeded;
3618 }
3619
Richard Smith357362d2011-12-13 06:39:58 +00003620 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003621 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003622 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003623 if (RetExpr &&
3624 !(Result.Slot
3625 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3626 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003627 return ESR_Failed;
3628 return ESR_Returned;
3629 }
Richard Smith254a73d2011-10-28 22:34:42 +00003630
3631 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003632 BlockScopeRAII Scope(Info);
3633
Richard Smith254a73d2011-10-28 22:34:42 +00003634 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003635 for (const auto *BI : CS->body()) {
3636 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003637 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003638 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003639 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003640 return ESR;
3641 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003642 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003643 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003644
3645 case Stmt::IfStmtClass: {
3646 const IfStmt *IS = cast<IfStmt>(S);
3647
3648 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003649 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003650 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003651 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003652 return ESR_Failed;
3653
3654 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3655 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3656 if (ESR != ESR_Succeeded)
3657 return ESR;
3658 }
3659 return ESR_Succeeded;
3660 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003661
3662 case Stmt::WhileStmtClass: {
3663 const WhileStmt *WS = cast<WhileStmt>(S);
3664 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003665 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003666 bool Continue;
3667 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3668 Continue))
3669 return ESR_Failed;
3670 if (!Continue)
3671 break;
3672
3673 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3674 if (ESR != ESR_Continue)
3675 return ESR;
3676 }
3677 return ESR_Succeeded;
3678 }
3679
3680 case Stmt::DoStmtClass: {
3681 const DoStmt *DS = cast<DoStmt>(S);
3682 bool Continue;
3683 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003684 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003685 if (ESR != ESR_Continue)
3686 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003687 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003688
Richard Smith08d6a2c2013-07-24 07:11:57 +00003689 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003690 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3691 return ESR_Failed;
3692 } while (Continue);
3693 return ESR_Succeeded;
3694 }
3695
3696 case Stmt::ForStmtClass: {
3697 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003698 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003699 if (FS->getInit()) {
3700 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3701 if (ESR != ESR_Succeeded)
3702 return ESR;
3703 }
3704 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003705 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003706 bool Continue = true;
3707 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3708 FS->getCond(), Continue))
3709 return ESR_Failed;
3710 if (!Continue)
3711 break;
3712
3713 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3714 if (ESR != ESR_Continue)
3715 return ESR;
3716
Richard Smith08d6a2c2013-07-24 07:11:57 +00003717 if (FS->getInc()) {
3718 FullExpressionRAII IncScope(Info);
3719 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3720 return ESR_Failed;
3721 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003722 }
3723 return ESR_Succeeded;
3724 }
3725
Richard Smith896e0d72013-05-06 06:51:17 +00003726 case Stmt::CXXForRangeStmtClass: {
3727 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003728 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003729
3730 // Initialize the __range variable.
3731 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3732 if (ESR != ESR_Succeeded)
3733 return ESR;
3734
3735 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003736 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3737 if (ESR != ESR_Succeeded)
3738 return ESR;
3739 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003740 if (ESR != ESR_Succeeded)
3741 return ESR;
3742
3743 while (true) {
3744 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003745 {
3746 bool Continue = true;
3747 FullExpressionRAII CondExpr(Info);
3748 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3749 return ESR_Failed;
3750 if (!Continue)
3751 break;
3752 }
Richard Smith896e0d72013-05-06 06:51:17 +00003753
3754 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003755 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003756 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3757 if (ESR != ESR_Succeeded)
3758 return ESR;
3759
3760 // Loop body.
3761 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3762 if (ESR != ESR_Continue)
3763 return ESR;
3764
3765 // Increment: ++__begin
3766 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3767 return ESR_Failed;
3768 }
3769
3770 return ESR_Succeeded;
3771 }
3772
Richard Smith496ddcf2013-05-12 17:32:42 +00003773 case Stmt::SwitchStmtClass:
3774 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3775
Richard Smith4e18ca52013-05-06 05:56:11 +00003776 case Stmt::ContinueStmtClass:
3777 return ESR_Continue;
3778
3779 case Stmt::BreakStmtClass:
3780 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003781
3782 case Stmt::LabelStmtClass:
3783 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3784
3785 case Stmt::AttributedStmtClass:
3786 // As a general principle, C++11 attributes can be ignored without
3787 // any semantic impact.
3788 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3789 Case);
3790
3791 case Stmt::CaseStmtClass:
3792 case Stmt::DefaultStmtClass:
3793 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003794 }
3795}
3796
Richard Smithcc36f692011-12-22 02:22:31 +00003797/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3798/// default constructor. If so, we'll fold it whether or not it's marked as
3799/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3800/// so we need special handling.
3801static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003802 const CXXConstructorDecl *CD,
3803 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003804 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3805 return false;
3806
Richard Smith66e05fe2012-01-18 05:21:49 +00003807 // Value-initialization does not call a trivial default constructor, so such a
3808 // call is a core constant expression whether or not the constructor is
3809 // constexpr.
3810 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003811 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003812 // FIXME: If DiagDecl is an implicitly-declared special member function,
3813 // we should be much more explicit about why it's not constexpr.
3814 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3815 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3816 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003817 } else {
3818 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3819 }
3820 }
3821 return true;
3822}
3823
Richard Smith357362d2011-12-13 06:39:58 +00003824/// CheckConstexprFunction - Check that a function can be called in a constant
3825/// expression.
3826static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3827 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003828 const FunctionDecl *Definition,
3829 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003830 // Potential constant expressions can contain calls to declared, but not yet
3831 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003832 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003833 Declaration->isConstexpr())
3834 return false;
3835
Richard Smith0838f3a2013-05-14 05:18:44 +00003836 // Bail out with no diagnostic if the function declaration itself is invalid.
3837 // We will have produced a relevant diagnostic while parsing it.
3838 if (Declaration->isInvalidDecl())
3839 return false;
3840
Richard Smith357362d2011-12-13 06:39:58 +00003841 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003842 if (Definition && Definition->isConstexpr() &&
3843 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003844 return true;
3845
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003846 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003847 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003848 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3849 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003850 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3851 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3852 << DiagDecl;
3853 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3854 } else {
3855 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3856 }
3857 return false;
3858}
3859
Richard Smithbe6dd812014-11-19 21:27:17 +00003860/// Determine if a class has any fields that might need to be copied by a
3861/// trivial copy or move operation.
3862static bool hasFields(const CXXRecordDecl *RD) {
3863 if (!RD || RD->isEmpty())
3864 return false;
3865 for (auto *FD : RD->fields()) {
3866 if (FD->isUnnamedBitfield())
3867 continue;
3868 return true;
3869 }
3870 for (auto &Base : RD->bases())
3871 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3872 return true;
3873 return false;
3874}
3875
Richard Smithd62306a2011-11-10 06:34:14 +00003876namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003877typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003878}
3879
3880/// EvaluateArgs - Evaluate the arguments to a function call.
3881static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3882 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003883 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003884 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003885 I != E; ++I) {
3886 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3887 // If we're checking for a potential constant expression, evaluate all
3888 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003889 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003890 return false;
3891 Success = false;
3892 }
3893 }
3894 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003895}
3896
Richard Smith254a73d2011-10-28 22:34:42 +00003897/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003898static bool HandleFunctionCall(SourceLocation CallLoc,
3899 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003900 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003901 EvalInfo &Info, APValue &Result,
3902 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003903 ArgVector ArgValues(Args.size());
3904 if (!EvaluateArgs(Args, ArgValues, Info))
3905 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003906
Richard Smith253c2a32012-01-27 01:14:48 +00003907 if (!Info.CheckCallLimit(CallLoc))
3908 return false;
3909
3910 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003911
3912 // For a trivial copy or move assignment, perform an APValue copy. This is
3913 // essential for unions, where the operations performed by the assignment
3914 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003915 //
3916 // Skip this for non-union classes with no fields; in that case, the defaulted
3917 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003918 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003919 if (MD && MD->isDefaulted() &&
3920 (MD->getParent()->isUnion() ||
3921 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003922 assert(This &&
3923 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3924 LValue RHS;
3925 RHS.setFrom(Info.Ctx, ArgValues[0]);
3926 APValue RHSValue;
3927 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3928 RHS, RHSValue))
3929 return false;
3930 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3931 RHSValue))
3932 return false;
3933 This->moveInto(Result);
3934 return true;
3935 }
3936
Richard Smith52a980a2015-08-28 02:43:42 +00003937 StmtResult Ret = {Result, ResultSlot};
3938 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003939 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003940 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003941 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003942 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003943 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003944 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003945}
3946
Richard Smithd62306a2011-11-10 06:34:14 +00003947/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003948static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003949 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003950 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003951 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003952 ArgVector ArgValues(Args.size());
3953 if (!EvaluateArgs(Args, ArgValues, Info))
3954 return false;
3955
Richard Smith253c2a32012-01-27 01:14:48 +00003956 if (!Info.CheckCallLimit(CallLoc))
3957 return false;
3958
Richard Smith3607ffe2012-02-13 03:54:03 +00003959 const CXXRecordDecl *RD = Definition->getParent();
3960 if (RD->getNumVBases()) {
3961 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3962 return false;
3963 }
3964
Richard Smith253c2a32012-01-27 01:14:48 +00003965 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003966
Richard Smith52a980a2015-08-28 02:43:42 +00003967 // FIXME: Creating an APValue just to hold a nonexistent return value is
3968 // wasteful.
3969 APValue RetVal;
3970 StmtResult Ret = {RetVal, nullptr};
3971
Richard Smithd62306a2011-11-10 06:34:14 +00003972 // If it's a delegating constructor, just delegate.
3973 if (Definition->isDelegatingConstructor()) {
3974 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003975 {
3976 FullExpressionRAII InitScope(Info);
3977 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3978 return false;
3979 }
Richard Smith52a980a2015-08-28 02:43:42 +00003980 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003981 }
3982
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003983 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003984 // essential for unions (or classes with anonymous union members), where the
3985 // operations performed by the constructor cannot be represented by
3986 // ctor-initializers.
3987 //
3988 // Skip this for empty non-union classes; we should not perform an
3989 // lvalue-to-rvalue conversion on them because their copy constructor does not
3990 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003991 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003992 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003993 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003994 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003995 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003996 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003997 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003998 }
3999
4000 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004001 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004002 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004003 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004004
John McCalld7bca762012-05-01 00:38:49 +00004005 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004006 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4007
Richard Smith08d6a2c2013-07-24 07:11:57 +00004008 // A scope for temporaries lifetime-extended by reference members.
4009 BlockScopeRAII LifetimeExtendedScope(Info);
4010
Richard Smith253c2a32012-01-27 01:14:48 +00004011 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004012 unsigned BasesSeen = 0;
4013#ifndef NDEBUG
4014 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4015#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004016 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004017 LValue Subobject = This;
4018 APValue *Value = &Result;
4019
4020 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004021 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004022 if (I->isBaseInitializer()) {
4023 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004024#ifndef NDEBUG
4025 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004026 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004027 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4028 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4029 "base class initializers not in expected order");
4030 ++BaseIt;
4031#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004032 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004033 BaseType->getAsCXXRecordDecl(), &Layout))
4034 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004035 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004036 } else if ((FD = I->getMember())) {
4037 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004038 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004039 if (RD->isUnion()) {
4040 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004041 Value = &Result.getUnionValue();
4042 } else {
4043 Value = &Result.getStructField(FD->getFieldIndex());
4044 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004045 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004046 // Walk the indirect field decl's chain to find the object to initialize,
4047 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004048 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004049 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004050 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4051 // Switch the union field if it differs. This happens if we had
4052 // preceding zero-initialization, and we're now initializing a union
4053 // subobject other than the first.
4054 // FIXME: In this case, the values of the other subobjects are
4055 // specified, since zero-initialization sets all padding bits to zero.
4056 if (Value->isUninit() ||
4057 (Value->isUnion() && Value->getUnionField() != FD)) {
4058 if (CD->isUnion())
4059 *Value = APValue(FD);
4060 else
4061 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004062 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004063 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004064 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004065 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004066 if (CD->isUnion())
4067 Value = &Value->getUnionValue();
4068 else
4069 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004070 }
Richard Smithd62306a2011-11-10 06:34:14 +00004071 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004072 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004073 }
Richard Smith253c2a32012-01-27 01:14:48 +00004074
Richard Smith08d6a2c2013-07-24 07:11:57 +00004075 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004076 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4077 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004078 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004079 // If we're checking for a potential constant expression, evaluate all
4080 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004081 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004082 return false;
4083 Success = false;
4084 }
Richard Smithd62306a2011-11-10 06:34:14 +00004085 }
4086
Richard Smithd9f663b2013-04-22 15:31:51 +00004087 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004088 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004089}
4090
Eli Friedman9a156e52008-11-12 09:44:48 +00004091//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004092// Generic Evaluation
4093//===----------------------------------------------------------------------===//
4094namespace {
4095
Aaron Ballman68af21c2014-01-03 19:26:43 +00004096template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004097class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004099private:
Richard Smith52a980a2015-08-28 02:43:42 +00004100 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004101 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004102 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004103 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004104 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004105 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004106 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004107
Richard Smith17100ba2012-02-16 02:46:34 +00004108 // Check whether a conditional operator with a non-constant condition is a
4109 // potential constant expression. If neither arm is a potential constant
4110 // expression, then the conditional operator is not either.
4111 template<typename ConditionalOperator>
4112 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004113 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004114
4115 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004116 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004117 {
Richard Smith17100ba2012-02-16 02:46:34 +00004118 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004119 StmtVisitorTy::Visit(E->getFalseExpr());
4120 if (Diag.empty())
4121 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004122 }
Richard Smith17100ba2012-02-16 02:46:34 +00004123
George Burgess IV8c892b52016-05-25 22:31:54 +00004124 {
4125 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004126 Diag.clear();
4127 StmtVisitorTy::Visit(E->getTrueExpr());
4128 if (Diag.empty())
4129 return;
4130 }
4131
4132 Error(E, diag::note_constexpr_conditional_never_const);
4133 }
4134
4135
4136 template<typename ConditionalOperator>
4137 bool HandleConditionalOperator(const ConditionalOperator *E) {
4138 bool BoolResult;
4139 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004140 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004141 CheckPotentialConstantConditional(E);
4142 return false;
4143 }
4144
4145 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4146 return StmtVisitorTy::Visit(EvalExpr);
4147 }
4148
Peter Collingbournee9200682011-05-13 03:29:01 +00004149protected:
4150 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004151 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004152 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4153
Richard Smith92b1ce02011-12-12 09:28:41 +00004154 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004155 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004156 }
4157
Aaron Ballman68af21c2014-01-03 19:26:43 +00004158 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004159
4160public:
4161 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4162
4163 EvalInfo &getEvalInfo() { return Info; }
4164
Richard Smithf57d8cb2011-12-09 22:58:01 +00004165 /// Report an evaluation error. This should only be called when an error is
4166 /// first discovered. When propagating an error, just return false.
4167 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004168 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004169 return false;
4170 }
4171 bool Error(const Expr *E) {
4172 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4173 }
4174
Aaron Ballman68af21c2014-01-03 19:26:43 +00004175 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004176 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004177 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004178 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004179 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004180 }
4181
Aaron Ballman68af21c2014-01-03 19:26:43 +00004182 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004183 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004184 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004185 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004186 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004187 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004188 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004189 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004190 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004191 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004192 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004193 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004194 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004195 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004196 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004197 // The initializer may not have been parsed yet, or might be erroneous.
4198 if (!E->getExpr())
4199 return Error(E);
4200 return StmtVisitorTy::Visit(E->getExpr());
4201 }
Richard Smith5894a912011-12-19 22:12:41 +00004202 // We cannot create any objects for which cleanups are required, so there is
4203 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004204 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004205 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004206
Aaron Ballman68af21c2014-01-03 19:26:43 +00004207 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004208 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4209 return static_cast<Derived*>(this)->VisitCastExpr(E);
4210 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004211 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004212 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4213 return static_cast<Derived*>(this)->VisitCastExpr(E);
4214 }
4215
Aaron Ballman68af21c2014-01-03 19:26:43 +00004216 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004217 switch (E->getOpcode()) {
4218 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004219 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004220
4221 case BO_Comma:
4222 VisitIgnoredValue(E->getLHS());
4223 return StmtVisitorTy::Visit(E->getRHS());
4224
4225 case BO_PtrMemD:
4226 case BO_PtrMemI: {
4227 LValue Obj;
4228 if (!HandleMemberPointerAccess(Info, E, Obj))
4229 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004230 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004231 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004232 return false;
4233 return DerivedSuccess(Result, E);
4234 }
4235 }
4236 }
4237
Aaron Ballman68af21c2014-01-03 19:26:43 +00004238 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004239 // Evaluate and cache the common expression. We treat it as a temporary,
4240 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004241 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004242 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004243 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004244
Richard Smith17100ba2012-02-16 02:46:34 +00004245 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004246 }
4247
Aaron Ballman68af21c2014-01-03 19:26:43 +00004248 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004249 bool IsBcpCall = false;
4250 // If the condition (ignoring parens) is a __builtin_constant_p call,
4251 // the result is a constant expression if it can be folded without
4252 // side-effects. This is an important GNU extension. See GCC PR38377
4253 // for discussion.
4254 if (const CallExpr *CallCE =
4255 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004256 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004257 IsBcpCall = true;
4258
4259 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4260 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004261 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004262 return false;
4263
Richard Smith6d4c6582013-11-05 22:18:15 +00004264 FoldConstant Fold(Info, IsBcpCall);
4265 if (!HandleConditionalOperator(E)) {
4266 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004267 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004268 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004269
4270 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004271 }
4272
Aaron Ballman68af21c2014-01-03 19:26:43 +00004273 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004274 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4275 return DerivedSuccess(*Value, E);
4276
4277 const Expr *Source = E->getSourceExpr();
4278 if (!Source)
4279 return Error(E);
4280 if (Source == E) { // sanity checking.
4281 assert(0 && "OpaqueValueExpr recursively refers to itself");
4282 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004283 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004284 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004285 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004286
Aaron Ballman68af21c2014-01-03 19:26:43 +00004287 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004288 APValue Result;
4289 if (!handleCallExpr(E, Result, nullptr))
4290 return false;
4291 return DerivedSuccess(Result, E);
4292 }
4293
4294 bool handleCallExpr(const CallExpr *E, APValue &Result,
4295 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004296 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004297 QualType CalleeType = Callee->getType();
4298
Craig Topper36250ad2014-05-12 05:36:57 +00004299 const FunctionDecl *FD = nullptr;
4300 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004301 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004302 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004303
Richard Smithe97cbd72011-11-11 04:05:33 +00004304 // Extract function decl and 'this' pointer from the callee.
4305 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004306 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004307 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4308 // Explicit bound member calls, such as x.f() or p->g();
4309 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004310 return false;
4311 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004312 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004313 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004314 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4315 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004316 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4317 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004318 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004319 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004320 return Error(Callee);
4321
4322 FD = dyn_cast<FunctionDecl>(Member);
4323 if (!FD)
4324 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004325 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004326 LValue Call;
4327 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004328 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004329
Richard Smitha8105bc2012-01-06 16:39:00 +00004330 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004331 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004332 FD = dyn_cast_or_null<FunctionDecl>(
4333 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004334 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004335 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004336
4337 // Overloaded operator calls to member functions are represented as normal
4338 // calls with '*this' as the first argument.
4339 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4340 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004341 // FIXME: When selecting an implicit conversion for an overloaded
4342 // operator delete, we sometimes try to evaluate calls to conversion
4343 // operators without a 'this' parameter!
4344 if (Args.empty())
4345 return Error(E);
4346
Richard Smithe97cbd72011-11-11 04:05:33 +00004347 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4348 return false;
4349 This = &ThisVal;
4350 Args = Args.slice(1);
4351 }
4352
4353 // Don't call function pointers which have been cast to some other type.
4354 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004355 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004356 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004357 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004358
Richard Smith47b34932012-02-01 02:39:43 +00004359 if (This && !This->checkSubobject(Info, E, CSK_This))
4360 return false;
4361
Richard Smith3607ffe2012-02-13 03:54:03 +00004362 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4363 // calls to such functions in constant expressions.
4364 if (This && !HasQualifier &&
4365 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4366 return Error(E, diag::note_constexpr_virtual_call);
4367
Craig Topper36250ad2014-05-12 05:36:57 +00004368 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004369 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004370
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004371 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004372 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4373 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004374 return false;
4375
Richard Smith52a980a2015-08-28 02:43:42 +00004376 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004377 }
4378
Aaron Ballman68af21c2014-01-03 19:26:43 +00004379 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004380 return StmtVisitorTy::Visit(E->getInitializer());
4381 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004382 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004383 if (E->getNumInits() == 0)
4384 return DerivedZeroInitialization(E);
4385 if (E->getNumInits() == 1)
4386 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004387 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004388 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004389 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004390 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004391 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004392 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004393 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004394 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004395 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004396 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004397 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004398
Richard Smithd62306a2011-11-10 06:34:14 +00004399 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004400 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004401 assert(!E->isArrow() && "missing call to bound member function?");
4402
Richard Smith2e312c82012-03-03 22:46:17 +00004403 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004404 if (!Evaluate(Val, Info, E->getBase()))
4405 return false;
4406
4407 QualType BaseTy = E->getBase()->getType();
4408
4409 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004410 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004411 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004412 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004413 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4414
Richard Smith3229b742013-05-05 21:17:10 +00004415 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004416 SubobjectDesignator Designator(BaseTy);
4417 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004418
Richard Smith3229b742013-05-05 21:17:10 +00004419 APValue Result;
4420 return extractSubobject(Info, E, Obj, Designator, Result) &&
4421 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004422 }
4423
Aaron Ballman68af21c2014-01-03 19:26:43 +00004424 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004425 switch (E->getCastKind()) {
4426 default:
4427 break;
4428
Richard Smitha23ab512013-05-23 00:30:41 +00004429 case CK_AtomicToNonAtomic: {
4430 APValue AtomicVal;
4431 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4432 return false;
4433 return DerivedSuccess(AtomicVal, E);
4434 }
4435
Richard Smith11562c52011-10-28 17:51:58 +00004436 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004437 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004438 return StmtVisitorTy::Visit(E->getSubExpr());
4439
4440 case CK_LValueToRValue: {
4441 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004442 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4443 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004444 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004445 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004446 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004447 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004448 return false;
4449 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004450 }
4451 }
4452
Richard Smithf57d8cb2011-12-09 22:58:01 +00004453 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004454 }
4455
Aaron Ballman68af21c2014-01-03 19:26:43 +00004456 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004457 return VisitUnaryPostIncDec(UO);
4458 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004459 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004460 return VisitUnaryPostIncDec(UO);
4461 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004463 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004464 return Error(UO);
4465
4466 LValue LVal;
4467 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4468 return false;
4469 APValue RVal;
4470 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4471 UO->isIncrementOp(), &RVal))
4472 return false;
4473 return DerivedSuccess(RVal, UO);
4474 }
4475
Aaron Ballman68af21c2014-01-03 19:26:43 +00004476 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004477 // We will have checked the full-expressions inside the statement expression
4478 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004479 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004480 return Error(E);
4481
Richard Smith08d6a2c2013-07-24 07:11:57 +00004482 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004483 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004484 if (CS->body_empty())
4485 return true;
4486
Richard Smith51f03172013-06-20 03:00:05 +00004487 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4488 BE = CS->body_end();
4489 /**/; ++BI) {
4490 if (BI + 1 == BE) {
4491 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4492 if (!FinalExpr) {
4493 Info.Diag((*BI)->getLocStart(),
4494 diag::note_constexpr_stmt_expr_unsupported);
4495 return false;
4496 }
4497 return this->Visit(FinalExpr);
4498 }
4499
4500 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004501 StmtResult Result = { ReturnValue, nullptr };
4502 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004503 if (ESR != ESR_Succeeded) {
4504 // FIXME: If the statement-expression terminated due to 'return',
4505 // 'break', or 'continue', it would be nice to propagate that to
4506 // the outer statement evaluation rather than bailing out.
4507 if (ESR != ESR_Failed)
4508 Info.Diag((*BI)->getLocStart(),
4509 diag::note_constexpr_stmt_expr_unsupported);
4510 return false;
4511 }
4512 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004513
4514 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004515 }
4516
Richard Smith4a678122011-10-24 18:44:57 +00004517 /// Visit a value which is evaluated, but whose value is ignored.
4518 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004519 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004520 }
David Majnemere9807b22016-02-26 04:23:19 +00004521
4522 /// Potentially visit a MemberExpr's base expression.
4523 void VisitIgnoredBaseExpression(const Expr *E) {
4524 // While MSVC doesn't evaluate the base expression, it does diagnose the
4525 // presence of side-effecting behavior.
4526 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4527 return;
4528 VisitIgnoredValue(E);
4529 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004530};
4531
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004532}
Peter Collingbournee9200682011-05-13 03:29:01 +00004533
4534//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004535// Common base class for lvalue and temporary evaluation.
4536//===----------------------------------------------------------------------===//
4537namespace {
4538template<class Derived>
4539class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004540 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004541protected:
4542 LValue &Result;
4543 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004544 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004545
4546 bool Success(APValue::LValueBase B) {
4547 Result.set(B);
4548 return true;
4549 }
4550
4551public:
4552 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4553 ExprEvaluatorBaseTy(Info), Result(Result) {}
4554
Richard Smith2e312c82012-03-03 22:46:17 +00004555 bool Success(const APValue &V, const Expr *E) {
4556 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004557 return true;
4558 }
Richard Smith027bf112011-11-17 22:56:20 +00004559
Richard Smith027bf112011-11-17 22:56:20 +00004560 bool VisitMemberExpr(const MemberExpr *E) {
4561 // Handle non-static data members.
4562 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004563 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004564 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004565 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004566 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004567 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004568 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004569 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004570 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004571 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004572 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004573 BaseTy = E->getBase()->getType();
4574 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004575 if (!EvalOK) {
4576 if (!this->Info.allowInvalidBaseExpr())
4577 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004578 Result.setInvalid(E);
4579 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004580 }
Richard Smith027bf112011-11-17 22:56:20 +00004581
Richard Smith1b78b3d2012-01-25 22:15:11 +00004582 const ValueDecl *MD = E->getMemberDecl();
4583 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4584 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4585 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4586 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004587 if (!HandleLValueMember(this->Info, E, Result, FD))
4588 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004589 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004590 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4591 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004592 } else
4593 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004594
Richard Smith1b78b3d2012-01-25 22:15:11 +00004595 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004596 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004597 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004598 RefValue))
4599 return false;
4600 return Success(RefValue, E);
4601 }
4602 return true;
4603 }
4604
4605 bool VisitBinaryOperator(const BinaryOperator *E) {
4606 switch (E->getOpcode()) {
4607 default:
4608 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4609
4610 case BO_PtrMemD:
4611 case BO_PtrMemI:
4612 return HandleMemberPointerAccess(this->Info, E, Result);
4613 }
4614 }
4615
4616 bool VisitCastExpr(const CastExpr *E) {
4617 switch (E->getCastKind()) {
4618 default:
4619 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4620
4621 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004622 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004623 if (!this->Visit(E->getSubExpr()))
4624 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004625
4626 // Now figure out the necessary offset to add to the base LV to get from
4627 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004628 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4629 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004630 }
4631 }
4632};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004633}
Richard Smith027bf112011-11-17 22:56:20 +00004634
4635//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004636// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004637//
4638// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4639// function designators (in C), decl references to void objects (in C), and
4640// temporaries (if building with -Wno-address-of-temporary).
4641//
4642// LValue evaluation produces values comprising a base expression of one of the
4643// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004644// - Declarations
4645// * VarDecl
4646// * FunctionDecl
4647// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004648// * CompoundLiteralExpr in C
4649// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004650// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004651// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004652// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004653// * ObjCEncodeExpr
4654// * AddrLabelExpr
4655// * BlockExpr
4656// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004657// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004658// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004659// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004660// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4661// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004662// * A MaterializeTemporaryExpr that has static storage duration, with no
4663// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004664// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004665//===----------------------------------------------------------------------===//
4666namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004667class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004668 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004669public:
Richard Smith027bf112011-11-17 22:56:20 +00004670 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4671 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004672
Richard Smith11562c52011-10-28 17:51:58 +00004673 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004674 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004675
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 bool VisitDeclRefExpr(const DeclRefExpr *E);
4677 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004678 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004679 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4680 bool VisitMemberExpr(const MemberExpr *E);
4681 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4682 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004683 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004684 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004685 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4686 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004687 bool VisitUnaryReal(const UnaryOperator *E);
4688 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004689 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4690 return VisitUnaryPreIncDec(UO);
4691 }
4692 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4693 return VisitUnaryPreIncDec(UO);
4694 }
Richard Smith3229b742013-05-05 21:17:10 +00004695 bool VisitBinAssign(const BinaryOperator *BO);
4696 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004697
Peter Collingbournee9200682011-05-13 03:29:01 +00004698 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004699 switch (E->getCastKind()) {
4700 default:
Richard Smith027bf112011-11-17 22:56:20 +00004701 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004702
Eli Friedmance3e02a2011-10-11 00:13:24 +00004703 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004704 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004705 if (!Visit(E->getSubExpr()))
4706 return false;
4707 Result.Designator.setInvalid();
4708 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004709
Richard Smith027bf112011-11-17 22:56:20 +00004710 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004711 if (!Visit(E->getSubExpr()))
4712 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004713 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004714 }
4715 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004716};
4717} // end anonymous namespace
4718
Richard Smith11562c52011-10-28 17:51:58 +00004719/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004720/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004721/// * function designators in C, and
4722/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004723/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004724static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4725 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004726 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004727 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004728}
4729
Peter Collingbournee9200682011-05-13 03:29:01 +00004730bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004731 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004732 return Success(FD);
4733 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004734 return VisitVarDecl(E, VD);
4735 return Error(E);
4736}
Richard Smith733237d2011-10-24 23:14:33 +00004737
Richard Smith11562c52011-10-28 17:51:58 +00004738bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004739 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004740 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4741 Frame = Info.CurrentCall;
4742
Richard Smithfec09922011-11-01 16:57:24 +00004743 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004744 if (Frame) {
4745 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004746 return true;
4747 }
Richard Smithce40ad62011-11-12 22:28:03 +00004748 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004749 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004750
Richard Smith3229b742013-05-05 21:17:10 +00004751 APValue *V;
4752 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004753 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004754 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004755 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004756 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4757 return false;
4758 }
Richard Smith3229b742013-05-05 21:17:10 +00004759 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004760}
4761
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004762bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4763 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004764 // Walk through the expression to find the materialized temporary itself.
4765 SmallVector<const Expr *, 2> CommaLHSs;
4766 SmallVector<SubobjectAdjustment, 2> Adjustments;
4767 const Expr *Inner = E->GetTemporaryExpr()->
4768 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004769
Richard Smith84401042013-06-03 05:03:02 +00004770 // If we passed any comma operators, evaluate their LHSs.
4771 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4772 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4773 return false;
4774
Richard Smithe6c01442013-06-05 00:46:14 +00004775 // A materialized temporary with static storage duration can appear within the
4776 // result of a constant expression evaluation, so we need to preserve its
4777 // value for use outside this evaluation.
4778 APValue *Value;
4779 if (E->getStorageDuration() == SD_Static) {
4780 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004781 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004782 Result.set(E);
4783 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004784 Value = &Info.CurrentCall->
4785 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004786 Result.set(E, Info.CurrentCall->Index);
4787 }
4788
Richard Smithea4ad5d2013-06-06 08:19:16 +00004789 QualType Type = Inner->getType();
4790
Richard Smith84401042013-06-03 05:03:02 +00004791 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004792 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4793 (E->getStorageDuration() == SD_Static &&
4794 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4795 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004796 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004797 }
Richard Smith84401042013-06-03 05:03:02 +00004798
4799 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004800 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4801 --I;
4802 switch (Adjustments[I].Kind) {
4803 case SubobjectAdjustment::DerivedToBaseAdjustment:
4804 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4805 Type, Result))
4806 return false;
4807 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4808 break;
4809
4810 case SubobjectAdjustment::FieldAdjustment:
4811 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4812 return false;
4813 Type = Adjustments[I].Field->getType();
4814 break;
4815
4816 case SubobjectAdjustment::MemberPointerAdjustment:
4817 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4818 Adjustments[I].Ptr.RHS))
4819 return false;
4820 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4821 break;
4822 }
4823 }
4824
4825 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004826}
4827
Peter Collingbournee9200682011-05-13 03:29:01 +00004828bool
4829LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004830 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4831 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4832 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004833 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004834}
4835
Richard Smith6e525142011-12-27 12:18:28 +00004836bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004837 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004838 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004839
4840 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4841 << E->getExprOperand()->getType()
4842 << E->getExprOperand()->getSourceRange();
4843 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004844}
4845
Francois Pichet0066db92012-04-16 04:08:35 +00004846bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4847 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004848}
Francois Pichet0066db92012-04-16 04:08:35 +00004849
Peter Collingbournee9200682011-05-13 03:29:01 +00004850bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004851 // Handle static data members.
4852 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004853 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004854 return VisitVarDecl(E, VD);
4855 }
4856
Richard Smith254a73d2011-10-28 22:34:42 +00004857 // Handle static member functions.
4858 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4859 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004860 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004861 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004862 }
4863 }
4864
Richard Smithd62306a2011-11-10 06:34:14 +00004865 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004866 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004867}
4868
Peter Collingbournee9200682011-05-13 03:29:01 +00004869bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004870 // FIXME: Deal with vectors as array subscript bases.
4871 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004872 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004873
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004874 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004875 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004876
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004877 APSInt Index;
4878 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004879 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004880
Richard Smith861b5b52013-05-07 23:34:45 +00004881 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4882 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004883}
Eli Friedman9a156e52008-11-12 09:44:48 +00004884
Peter Collingbournee9200682011-05-13 03:29:01 +00004885bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004886 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004887}
4888
Richard Smith66c96992012-02-18 22:04:06 +00004889bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4890 if (!Visit(E->getSubExpr()))
4891 return false;
4892 // __real is a no-op on scalar lvalues.
4893 if (E->getSubExpr()->getType()->isAnyComplexType())
4894 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4895 return true;
4896}
4897
4898bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4899 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4900 "lvalue __imag__ on scalar?");
4901 if (!Visit(E->getSubExpr()))
4902 return false;
4903 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4904 return true;
4905}
4906
Richard Smith243ef902013-05-05 23:31:59 +00004907bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004908 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004909 return Error(UO);
4910
4911 if (!this->Visit(UO->getSubExpr()))
4912 return false;
4913
Richard Smith243ef902013-05-05 23:31:59 +00004914 return handleIncDec(
4915 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004916 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004917}
4918
4919bool LValueExprEvaluator::VisitCompoundAssignOperator(
4920 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004921 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004922 return Error(CAO);
4923
Richard Smith3229b742013-05-05 21:17:10 +00004924 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004925
4926 // The overall lvalue result is the result of evaluating the LHS.
4927 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004928 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004929 Evaluate(RHS, this->Info, CAO->getRHS());
4930 return false;
4931 }
4932
Richard Smith3229b742013-05-05 21:17:10 +00004933 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4934 return false;
4935
Richard Smith43e77732013-05-07 04:50:00 +00004936 return handleCompoundAssignment(
4937 this->Info, CAO,
4938 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4939 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004940}
4941
4942bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004943 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004944 return Error(E);
4945
Richard Smith3229b742013-05-05 21:17:10 +00004946 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004947
4948 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004949 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004950 Evaluate(NewVal, this->Info, E->getRHS());
4951 return false;
4952 }
4953
Richard Smith3229b742013-05-05 21:17:10 +00004954 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4955 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004956
4957 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004958 NewVal);
4959}
4960
Eli Friedman9a156e52008-11-12 09:44:48 +00004961//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004962// Pointer Evaluation
4963//===----------------------------------------------------------------------===//
4964
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004965namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004966class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004967 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004968 LValue &Result;
4969
Peter Collingbournee9200682011-05-13 03:29:01 +00004970 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004971 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004972 return true;
4973 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004974public:
Mike Stump11289f42009-09-09 15:08:12 +00004975
John McCall45d55e42010-05-07 21:00:08 +00004976 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004977 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004978
Richard Smith2e312c82012-03-03 22:46:17 +00004979 bool Success(const APValue &V, const Expr *E) {
4980 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004981 return true;
4982 }
Richard Smithfddd3842011-12-30 21:15:51 +00004983 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004984 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004985 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004986
John McCall45d55e42010-05-07 21:00:08 +00004987 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004988 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004989 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004990 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004991 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004992 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004993 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004994 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004995 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004996 bool VisitCallExpr(const CallExpr *E);
4997 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004998 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004999 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005000 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005001 }
Richard Smithd62306a2011-11-10 06:34:14 +00005002 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005003 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005004 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005005 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005006 if (!Info.CurrentCall->This) {
5007 if (Info.getLangOpts().CPlusPlus11)
5008 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
5009 else
5010 Info.Diag(E);
5011 return false;
5012 }
Richard Smithd62306a2011-11-10 06:34:14 +00005013 Result = *Info.CurrentCall->This;
5014 return true;
5015 }
John McCallc07a0c72011-02-17 10:25:35 +00005016
Eli Friedman449fe542009-03-23 04:56:01 +00005017 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005018};
Chris Lattner05706e882008-07-11 18:11:29 +00005019} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005020
John McCall45d55e42010-05-07 21:00:08 +00005021static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005022 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005023 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005024}
5025
John McCall45d55e42010-05-07 21:00:08 +00005026bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005027 if (E->getOpcode() != BO_Add &&
5028 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005029 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005030
Chris Lattner05706e882008-07-11 18:11:29 +00005031 const Expr *PExp = E->getLHS();
5032 const Expr *IExp = E->getRHS();
5033 if (IExp->getType()->isPointerType())
5034 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005035
Richard Smith253c2a32012-01-27 01:14:48 +00005036 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005037 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005038 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005039
John McCall45d55e42010-05-07 21:00:08 +00005040 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005041 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005042 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005043
5044 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005045 if (E->getOpcode() == BO_Sub)
5046 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005047
Ted Kremenek28831752012-08-23 20:46:57 +00005048 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005049 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5050 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005051}
Eli Friedman9a156e52008-11-12 09:44:48 +00005052
John McCall45d55e42010-05-07 21:00:08 +00005053bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5054 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005055}
Mike Stump11289f42009-09-09 15:08:12 +00005056
Peter Collingbournee9200682011-05-13 03:29:01 +00005057bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5058 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005059
Eli Friedman847a2bc2009-12-27 05:43:15 +00005060 switch (E->getCastKind()) {
5061 default:
5062 break;
5063
John McCalle3027922010-08-25 11:45:40 +00005064 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005065 case CK_CPointerToObjCPointerCast:
5066 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005067 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005068 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005069 if (!Visit(SubExpr))
5070 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005071 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5072 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5073 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005074 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005075 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005076 if (SubExpr->getType()->isVoidPointerType())
5077 CCEDiag(E, diag::note_constexpr_invalid_cast)
5078 << 3 << SubExpr->getType();
5079 else
5080 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5081 }
Richard Smith96e0c102011-11-04 02:25:55 +00005082 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005083
Anders Carlsson18275092010-10-31 20:41:46 +00005084 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005085 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005086 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005087 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005088 if (!Result.Base && Result.Offset.isZero())
5089 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005090
Richard Smithd62306a2011-11-10 06:34:14 +00005091 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005092 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005093 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5094 castAs<PointerType>()->getPointeeType(),
5095 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005096
Richard Smith027bf112011-11-17 22:56:20 +00005097 case CK_BaseToDerived:
5098 if (!Visit(E->getSubExpr()))
5099 return false;
5100 if (!Result.Base && Result.Offset.isZero())
5101 return true;
5102 return HandleBaseToDerivedCast(Info, E, Result);
5103
Richard Smith0b0a0b62011-10-29 20:57:55 +00005104 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005105 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005106 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005107
John McCalle3027922010-08-25 11:45:40 +00005108 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005109 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5110
Richard Smith2e312c82012-03-03 22:46:17 +00005111 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005112 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005113 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005114
John McCall45d55e42010-05-07 21:00:08 +00005115 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005116 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5117 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005118 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005119 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005120 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005121 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005122 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005123 return true;
5124 } else {
5125 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005126 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005127 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005128 }
5129 }
John McCalle3027922010-08-25 11:45:40 +00005130 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005131 if (SubExpr->isGLValue()) {
5132 if (!EvaluateLValue(SubExpr, Result, Info))
5133 return false;
5134 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005135 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005136 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005137 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005138 return false;
5139 }
Richard Smith96e0c102011-11-04 02:25:55 +00005140 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005141 if (const ConstantArrayType *CAT
5142 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5143 Result.addArray(Info, E, CAT);
5144 else
5145 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005146 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005147
John McCalle3027922010-08-25 11:45:40 +00005148 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005149 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005150 }
5151
Richard Smith11562c52011-10-28 17:51:58 +00005152 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005153}
Chris Lattner05706e882008-07-11 18:11:29 +00005154
Hal Finkel0dd05d42014-10-03 17:18:37 +00005155static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5156 // C++ [expr.alignof]p3:
5157 // When alignof is applied to a reference type, the result is the
5158 // alignment of the referenced type.
5159 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5160 T = Ref->getPointeeType();
5161
5162 // __alignof is defined to return the preferred alignment.
5163 return Info.Ctx.toCharUnitsFromBits(
5164 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5165}
5166
5167static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5168 E = E->IgnoreParens();
5169
5170 // The kinds of expressions that we have special-case logic here for
5171 // should be kept up to date with the special checks for those
5172 // expressions in Sema.
5173
5174 // alignof decl is always accepted, even if it doesn't make sense: we default
5175 // to 1 in those cases.
5176 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5177 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5178 /*RefAsPointee*/true);
5179
5180 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5181 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5182 /*RefAsPointee*/true);
5183
5184 return GetAlignOfType(Info, E->getType());
5185}
5186
Peter Collingbournee9200682011-05-13 03:29:01 +00005187bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005188 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005189 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005190
Alp Tokera724cff2013-12-28 21:59:02 +00005191 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005192 case Builtin::BI__builtin_addressof:
5193 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005194 case Builtin::BI__builtin_assume_aligned: {
5195 // We need to be very careful here because: if the pointer does not have the
5196 // asserted alignment, then the behavior is undefined, and undefined
5197 // behavior is non-constant.
5198 if (!EvaluatePointer(E->getArg(0), Result, Info))
5199 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005200
Hal Finkel0dd05d42014-10-03 17:18:37 +00005201 LValue OffsetResult(Result);
5202 APSInt Alignment;
5203 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5204 return false;
5205 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5206
5207 if (E->getNumArgs() > 2) {
5208 APSInt Offset;
5209 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5210 return false;
5211
5212 int64_t AdditionalOffset = -getExtValue(Offset);
5213 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5214 }
5215
5216 // If there is a base object, then it must have the correct alignment.
5217 if (OffsetResult.Base) {
5218 CharUnits BaseAlignment;
5219 if (const ValueDecl *VD =
5220 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5221 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5222 } else {
5223 BaseAlignment =
5224 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5225 }
5226
5227 if (BaseAlignment < Align) {
5228 Result.Designator.setInvalid();
5229 // FIXME: Quantities here cast to integers because the plural modifier
5230 // does not work on APSInts yet.
5231 CCEDiag(E->getArg(0),
5232 diag::note_constexpr_baa_insufficient_alignment) << 0
5233 << (int) BaseAlignment.getQuantity()
5234 << (unsigned) getExtValue(Alignment);
5235 return false;
5236 }
5237 }
5238
5239 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005240 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005241 Result.Designator.setInvalid();
5242 APSInt Offset(64, false);
5243 Offset = OffsetResult.Offset.getQuantity();
5244
5245 if (OffsetResult.Base)
5246 CCEDiag(E->getArg(0),
5247 diag::note_constexpr_baa_insufficient_alignment) << 1
5248 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5249 else
5250 CCEDiag(E->getArg(0),
5251 diag::note_constexpr_baa_value_insufficient_alignment)
5252 << Offset << (unsigned) getExtValue(Alignment);
5253
5254 return false;
5255 }
5256
5257 return true;
5258 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005259 default:
5260 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5261 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005262}
Chris Lattner05706e882008-07-11 18:11:29 +00005263
5264//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005265// Member Pointer Evaluation
5266//===----------------------------------------------------------------------===//
5267
5268namespace {
5269class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005270 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005271 MemberPtr &Result;
5272
5273 bool Success(const ValueDecl *D) {
5274 Result = MemberPtr(D);
5275 return true;
5276 }
5277public:
5278
5279 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5280 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5281
Richard Smith2e312c82012-03-03 22:46:17 +00005282 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005283 Result.setFrom(V);
5284 return true;
5285 }
Richard Smithfddd3842011-12-30 21:15:51 +00005286 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005287 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005288 }
5289
5290 bool VisitCastExpr(const CastExpr *E);
5291 bool VisitUnaryAddrOf(const UnaryOperator *E);
5292};
5293} // end anonymous namespace
5294
5295static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5296 EvalInfo &Info) {
5297 assert(E->isRValue() && E->getType()->isMemberPointerType());
5298 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5299}
5300
5301bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5302 switch (E->getCastKind()) {
5303 default:
5304 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5305
5306 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005307 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005308 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005309
5310 case CK_BaseToDerivedMemberPointer: {
5311 if (!Visit(E->getSubExpr()))
5312 return false;
5313 if (E->path_empty())
5314 return true;
5315 // Base-to-derived member pointer casts store the path in derived-to-base
5316 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5317 // the wrong end of the derived->base arc, so stagger the path by one class.
5318 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5319 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5320 PathI != PathE; ++PathI) {
5321 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5322 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5323 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005324 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005325 }
5326 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5327 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005328 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005329 return true;
5330 }
5331
5332 case CK_DerivedToBaseMemberPointer:
5333 if (!Visit(E->getSubExpr()))
5334 return false;
5335 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5336 PathE = E->path_end(); PathI != PathE; ++PathI) {
5337 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5338 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5339 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005340 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005341 }
5342 return true;
5343 }
5344}
5345
5346bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5347 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5348 // member can be formed.
5349 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5350}
5351
5352//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005353// Record Evaluation
5354//===----------------------------------------------------------------------===//
5355
5356namespace {
5357 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005358 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005359 const LValue &This;
5360 APValue &Result;
5361 public:
5362
5363 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5364 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5365
Richard Smith2e312c82012-03-03 22:46:17 +00005366 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005367 Result = V;
5368 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005369 }
Richard Smithb8348f52016-05-12 22:16:28 +00005370 bool ZeroInitialization(const Expr *E) {
5371 return ZeroInitialization(E, E->getType());
5372 }
5373 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005374
Richard Smith52a980a2015-08-28 02:43:42 +00005375 bool VisitCallExpr(const CallExpr *E) {
5376 return handleCallExpr(E, Result, &This);
5377 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005378 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005379 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005380 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5381 return VisitCXXConstructExpr(E, E->getType());
5382 }
5383 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005384 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005385 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005386}
Richard Smithd62306a2011-11-10 06:34:14 +00005387
Richard Smithfddd3842011-12-30 21:15:51 +00005388/// Perform zero-initialization on an object of non-union class type.
5389/// C++11 [dcl.init]p5:
5390/// To zero-initialize an object or reference of type T means:
5391/// [...]
5392/// -- if T is a (possibly cv-qualified) non-union class type,
5393/// each non-static data member and each base-class subobject is
5394/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005395static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5396 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005397 const LValue &This, APValue &Result) {
5398 assert(!RD->isUnion() && "Expected non-union class type");
5399 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5400 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005401 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005402
John McCalld7bca762012-05-01 00:38:49 +00005403 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005404 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5405
5406 if (CD) {
5407 unsigned Index = 0;
5408 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005409 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005410 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5411 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005412 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5413 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005414 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005415 Result.getStructBase(Index)))
5416 return false;
5417 }
5418 }
5419
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005420 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005421 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005422 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005423 continue;
5424
5425 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005426 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005427 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005428
David Blaikie2d7c57e2012-04-30 02:36:29 +00005429 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005430 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005431 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005432 return false;
5433 }
5434
5435 return true;
5436}
5437
Richard Smithb8348f52016-05-12 22:16:28 +00005438bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5439 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005440 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005441 if (RD->isUnion()) {
5442 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5443 // object's first non-static named data member is zero-initialized
5444 RecordDecl::field_iterator I = RD->field_begin();
5445 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005446 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005447 return true;
5448 }
5449
5450 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005451 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005452 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005453 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005454 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005455 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005456 }
5457
Richard Smith5d108602012-02-17 00:44:16 +00005458 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005459 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005460 return false;
5461 }
5462
Richard Smitha8105bc2012-01-06 16:39:00 +00005463 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005464}
5465
Richard Smithe97cbd72011-11-11 04:05:33 +00005466bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5467 switch (E->getCastKind()) {
5468 default:
5469 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5470
5471 case CK_ConstructorConversion:
5472 return Visit(E->getSubExpr());
5473
5474 case CK_DerivedToBase:
5475 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005476 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005477 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005478 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005479 if (!DerivedObject.isStruct())
5480 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005481
5482 // Derived-to-base rvalue conversion: just slice off the derived part.
5483 APValue *Value = &DerivedObject;
5484 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5485 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5486 PathE = E->path_end(); PathI != PathE; ++PathI) {
5487 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5488 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5489 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5490 RD = Base;
5491 }
5492 Result = *Value;
5493 return true;
5494 }
5495 }
5496}
5497
Richard Smithd62306a2011-11-10 06:34:14 +00005498bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5499 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005500 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005501 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5502
5503 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005504 const FieldDecl *Field = E->getInitializedFieldInUnion();
5505 Result = APValue(Field);
5506 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005507 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005508
5509 // If the initializer list for a union does not contain any elements, the
5510 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005511 // FIXME: The element should be initialized from an initializer list.
5512 // Is this difference ever observable for initializer lists which
5513 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005514 ImplicitValueInitExpr VIE(Field->getType());
5515 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5516
Richard Smithd62306a2011-11-10 06:34:14 +00005517 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005518 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5519 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005520
5521 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5522 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5523 isa<CXXDefaultInitExpr>(InitExpr));
5524
Richard Smithb228a862012-02-15 02:18:13 +00005525 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005526 }
5527
Richard Smith872307e2016-03-08 22:17:41 +00005528 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005529 if (Result.isUninit())
5530 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5531 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005532 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005533 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005534
5535 // Initialize base classes.
5536 if (CXXRD) {
5537 for (const auto &Base : CXXRD->bases()) {
5538 assert(ElementNo < E->getNumInits() && "missing init for base class");
5539 const Expr *Init = E->getInit(ElementNo);
5540
5541 LValue Subobject = This;
5542 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5543 return false;
5544
5545 APValue &FieldVal = Result.getStructBase(ElementNo);
5546 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005547 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005548 return false;
5549 Success = false;
5550 }
5551 ++ElementNo;
5552 }
5553 }
5554
5555 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005556 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005557 // Anonymous bit-fields are not considered members of the class for
5558 // purposes of aggregate initialization.
5559 if (Field->isUnnamedBitfield())
5560 continue;
5561
5562 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005563
Richard Smith253c2a32012-01-27 01:14:48 +00005564 bool HaveInit = ElementNo < E->getNumInits();
5565
5566 // FIXME: Diagnostics here should point to the end of the initializer
5567 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005568 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005569 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005570 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005571
5572 // Perform an implicit value-initialization for members beyond the end of
5573 // the initializer list.
5574 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005575 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005576
Richard Smith852c9db2013-04-20 22:23:05 +00005577 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5578 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5579 isa<CXXDefaultInitExpr>(Init));
5580
Richard Smith49ca8aa2013-08-06 07:09:20 +00005581 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5582 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5583 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005584 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005585 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005586 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005587 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005588 }
5589 }
5590
Richard Smith253c2a32012-01-27 01:14:48 +00005591 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005592}
5593
Richard Smithb8348f52016-05-12 22:16:28 +00005594bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5595 QualType T) {
5596 // Note that E's type is not necessarily the type of our class here; we might
5597 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005598 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005599 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5600
Richard Smithfddd3842011-12-30 21:15:51 +00005601 bool ZeroInit = E->requiresZeroInitialization();
5602 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005603 // If we've already performed zero-initialization, we're already done.
5604 if (!Result.isUninit())
5605 return true;
5606
Richard Smithda3f4fd2014-03-05 23:32:50 +00005607 // We can get here in two different ways:
5608 // 1) We're performing value-initialization, and should zero-initialize
5609 // the object, or
5610 // 2) We're performing default-initialization of an object with a trivial
5611 // constexpr default constructor, in which case we should start the
5612 // lifetimes of all the base subobjects (there can be no data member
5613 // subobjects in this case) per [basic.life]p1.
5614 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005615 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005616 }
5617
Craig Topper36250ad2014-05-12 05:36:57 +00005618 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005619 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005620
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005621 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005622 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005623
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005624 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005625 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005626 if (const MaterializeTemporaryExpr *ME
5627 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5628 return Visit(ME->GetTemporaryExpr());
5629
Richard Smithb8348f52016-05-12 22:16:28 +00005630 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005631 return false;
5632
Craig Topper5fc8fc22014-08-27 06:28:36 +00005633 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005634 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005635 cast<CXXConstructorDecl>(Definition), Info,
5636 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005637}
5638
Richard Smithcc1b96d2013-06-12 22:31:48 +00005639bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5640 const CXXStdInitializerListExpr *E) {
5641 const ConstantArrayType *ArrayType =
5642 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5643
5644 LValue Array;
5645 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5646 return false;
5647
5648 // Get a pointer to the first element of the array.
5649 Array.addArray(Info, E, ArrayType);
5650
5651 // FIXME: Perform the checks on the field types in SemaInit.
5652 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5653 RecordDecl::field_iterator Field = Record->field_begin();
5654 if (Field == Record->field_end())
5655 return Error(E);
5656
5657 // Start pointer.
5658 if (!Field->getType()->isPointerType() ||
5659 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5660 ArrayType->getElementType()))
5661 return Error(E);
5662
5663 // FIXME: What if the initializer_list type has base classes, etc?
5664 Result = APValue(APValue::UninitStruct(), 0, 2);
5665 Array.moveInto(Result.getStructField(0));
5666
5667 if (++Field == Record->field_end())
5668 return Error(E);
5669
5670 if (Field->getType()->isPointerType() &&
5671 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5672 ArrayType->getElementType())) {
5673 // End pointer.
5674 if (!HandleLValueArrayAdjustment(Info, E, Array,
5675 ArrayType->getElementType(),
5676 ArrayType->getSize().getZExtValue()))
5677 return false;
5678 Array.moveInto(Result.getStructField(1));
5679 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5680 // Length.
5681 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5682 else
5683 return Error(E);
5684
5685 if (++Field != Record->field_end())
5686 return Error(E);
5687
5688 return true;
5689}
5690
Richard Smithd62306a2011-11-10 06:34:14 +00005691static bool EvaluateRecord(const Expr *E, const LValue &This,
5692 APValue &Result, EvalInfo &Info) {
5693 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005694 "can't evaluate expression as a record rvalue");
5695 return RecordExprEvaluator(Info, This, Result).Visit(E);
5696}
5697
5698//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005699// Temporary Evaluation
5700//
5701// Temporaries are represented in the AST as rvalues, but generally behave like
5702// lvalues. The full-object of which the temporary is a subobject is implicitly
5703// materialized so that a reference can bind to it.
5704//===----------------------------------------------------------------------===//
5705namespace {
5706class TemporaryExprEvaluator
5707 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5708public:
5709 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5710 LValueExprEvaluatorBaseTy(Info, Result) {}
5711
5712 /// Visit an expression which constructs the value of this temporary.
5713 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005714 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005715 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5716 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005717 }
5718
5719 bool VisitCastExpr(const CastExpr *E) {
5720 switch (E->getCastKind()) {
5721 default:
5722 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5723
5724 case CK_ConstructorConversion:
5725 return VisitConstructExpr(E->getSubExpr());
5726 }
5727 }
5728 bool VisitInitListExpr(const InitListExpr *E) {
5729 return VisitConstructExpr(E);
5730 }
5731 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5732 return VisitConstructExpr(E);
5733 }
5734 bool VisitCallExpr(const CallExpr *E) {
5735 return VisitConstructExpr(E);
5736 }
Richard Smith513955c2014-12-17 19:24:30 +00005737 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5738 return VisitConstructExpr(E);
5739 }
Richard Smith027bf112011-11-17 22:56:20 +00005740};
5741} // end anonymous namespace
5742
5743/// Evaluate an expression of record type as a temporary.
5744static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005745 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005746 return TemporaryExprEvaluator(Info, Result).Visit(E);
5747}
5748
5749//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005750// Vector Evaluation
5751//===----------------------------------------------------------------------===//
5752
5753namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005754 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005755 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005756 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005757 public:
Mike Stump11289f42009-09-09 15:08:12 +00005758
Richard Smith2d406342011-10-22 21:10:00 +00005759 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5760 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005761
Craig Topper9798b932015-09-29 04:30:05 +00005762 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005763 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5764 // FIXME: remove this APValue copy.
5765 Result = APValue(V.data(), V.size());
5766 return true;
5767 }
Richard Smith2e312c82012-03-03 22:46:17 +00005768 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005769 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005770 Result = V;
5771 return true;
5772 }
Richard Smithfddd3842011-12-30 21:15:51 +00005773 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005774
Richard Smith2d406342011-10-22 21:10:00 +00005775 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005776 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005777 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005778 bool VisitInitListExpr(const InitListExpr *E);
5779 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005780 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005781 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005782 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005783 };
5784} // end anonymous namespace
5785
5786static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005787 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005788 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005789}
5790
George Burgess IV533ff002015-12-11 00:23:35 +00005791bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005792 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005793 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005794
Richard Smith161f09a2011-12-06 22:44:34 +00005795 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005796 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005797
Eli Friedmanc757de22011-03-25 00:43:55 +00005798 switch (E->getCastKind()) {
5799 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005800 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005801 if (SETy->isIntegerType()) {
5802 APSInt IntResult;
5803 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005804 return false;
5805 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005806 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005807 APFloat FloatResult(0.0);
5808 if (!EvaluateFloat(SE, FloatResult, Info))
5809 return false;
5810 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005811 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005812 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005813 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005814
5815 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005816 SmallVector<APValue, 4> Elts(NElts, Val);
5817 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005818 }
Eli Friedman803acb32011-12-22 03:51:45 +00005819 case CK_BitCast: {
5820 // Evaluate the operand into an APInt we can extract from.
5821 llvm::APInt SValInt;
5822 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5823 return false;
5824 // Extract the elements
5825 QualType EltTy = VTy->getElementType();
5826 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5827 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5828 SmallVector<APValue, 4> Elts;
5829 if (EltTy->isRealFloatingType()) {
5830 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005831 unsigned FloatEltSize = EltSize;
5832 if (&Sem == &APFloat::x87DoubleExtended)
5833 FloatEltSize = 80;
5834 for (unsigned i = 0; i < NElts; i++) {
5835 llvm::APInt Elt;
5836 if (BigEndian)
5837 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5838 else
5839 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005840 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005841 }
5842 } else if (EltTy->isIntegerType()) {
5843 for (unsigned i = 0; i < NElts; i++) {
5844 llvm::APInt Elt;
5845 if (BigEndian)
5846 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5847 else
5848 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5849 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5850 }
5851 } else {
5852 return Error(E);
5853 }
5854 return Success(Elts, E);
5855 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005856 default:
Richard Smith11562c52011-10-28 17:51:58 +00005857 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005858 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005859}
5860
Richard Smith2d406342011-10-22 21:10:00 +00005861bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005862VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005863 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005864 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005865 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005866
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005867 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005868 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005869
Eli Friedmanb9c71292012-01-03 23:24:20 +00005870 // The number of initializers can be less than the number of
5871 // vector elements. For OpenCL, this can be due to nested vector
5872 // initialization. For GCC compatibility, missing trailing elements
5873 // should be initialized with zeroes.
5874 unsigned CountInits = 0, CountElts = 0;
5875 while (CountElts < NumElements) {
5876 // Handle nested vector initialization.
5877 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005878 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005879 APValue v;
5880 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5881 return Error(E);
5882 unsigned vlen = v.getVectorLength();
5883 for (unsigned j = 0; j < vlen; j++)
5884 Elements.push_back(v.getVectorElt(j));
5885 CountElts += vlen;
5886 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005887 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005888 if (CountInits < NumInits) {
5889 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005890 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005891 } else // trailing integer zero.
5892 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5893 Elements.push_back(APValue(sInt));
5894 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005895 } else {
5896 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005897 if (CountInits < NumInits) {
5898 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005899 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005900 } else // trailing float zero.
5901 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5902 Elements.push_back(APValue(f));
5903 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005904 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005905 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005906 }
Richard Smith2d406342011-10-22 21:10:00 +00005907 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005908}
5909
Richard Smith2d406342011-10-22 21:10:00 +00005910bool
Richard Smithfddd3842011-12-30 21:15:51 +00005911VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005912 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005913 QualType EltTy = VT->getElementType();
5914 APValue ZeroElement;
5915 if (EltTy->isIntegerType())
5916 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5917 else
5918 ZeroElement =
5919 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5920
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005921 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005922 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005923}
5924
Richard Smith2d406342011-10-22 21:10:00 +00005925bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005926 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005927 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005928}
5929
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005930//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005931// Array Evaluation
5932//===----------------------------------------------------------------------===//
5933
5934namespace {
5935 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005936 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005937 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005938 APValue &Result;
5939 public:
5940
Richard Smithd62306a2011-11-10 06:34:14 +00005941 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5942 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005943
5944 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005945 assert((V.isArray() || V.isLValue()) &&
5946 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005947 Result = V;
5948 return true;
5949 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005950
Richard Smithfddd3842011-12-30 21:15:51 +00005951 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005952 const ConstantArrayType *CAT =
5953 Info.Ctx.getAsConstantArrayType(E->getType());
5954 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005955 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005956
5957 Result = APValue(APValue::UninitArray(), 0,
5958 CAT->getSize().getZExtValue());
5959 if (!Result.hasArrayFiller()) return true;
5960
Richard Smithfddd3842011-12-30 21:15:51 +00005961 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005962 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005963 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005964 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005965 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005966 }
5967
Richard Smith52a980a2015-08-28 02:43:42 +00005968 bool VisitCallExpr(const CallExpr *E) {
5969 return handleCallExpr(E, Result, &This);
5970 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005971 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005972 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005973 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5974 const LValue &Subobject,
5975 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005976 };
5977} // end anonymous namespace
5978
Richard Smithd62306a2011-11-10 06:34:14 +00005979static bool EvaluateArray(const Expr *E, const LValue &This,
5980 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005981 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005982 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005983}
5984
5985bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5986 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5987 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005988 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005989
Richard Smithca2cfbf2011-12-22 01:07:19 +00005990 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5991 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005992 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005993 LValue LV;
5994 if (!EvaluateLValue(E->getInit(0), LV, Info))
5995 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005996 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005997 LV.moveInto(Val);
5998 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005999 }
6000
Richard Smith253c2a32012-01-27 01:14:48 +00006001 bool Success = true;
6002
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006003 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6004 "zero-initialized array shouldn't have any initialized elts");
6005 APValue Filler;
6006 if (Result.isArray() && Result.hasArrayFiller())
6007 Filler = Result.getArrayFiller();
6008
Richard Smith9543c5e2013-04-22 14:44:29 +00006009 unsigned NumEltsToInit = E->getNumInits();
6010 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006011 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006012
6013 // If the initializer might depend on the array index, run it for each
6014 // array element. For now, just whitelist non-class value-initialization.
6015 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6016 NumEltsToInit = NumElts;
6017
6018 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006019
6020 // If the array was previously zero-initialized, preserve the
6021 // zero-initialized values.
6022 if (!Filler.isUninit()) {
6023 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6024 Result.getArrayInitializedElt(I) = Filler;
6025 if (Result.hasArrayFiller())
6026 Result.getArrayFiller() = Filler;
6027 }
6028
Richard Smithd62306a2011-11-10 06:34:14 +00006029 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006030 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006031 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6032 const Expr *Init =
6033 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006034 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006035 Info, Subobject, Init) ||
6036 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006037 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006038 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006039 return false;
6040 Success = false;
6041 }
Richard Smithd62306a2011-11-10 06:34:14 +00006042 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006043
Richard Smith9543c5e2013-04-22 14:44:29 +00006044 if (!Result.hasArrayFiller())
6045 return Success;
6046
6047 // If we get here, we have a trivial filler, which we can just evaluate
6048 // once and splat over the rest of the array elements.
6049 assert(FillerExpr && "no array filler for incomplete init list");
6050 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6051 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006052}
6053
Richard Smith027bf112011-11-17 22:56:20 +00006054bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006055 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6056}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006057
Richard Smith9543c5e2013-04-22 14:44:29 +00006058bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6059 const LValue &Subobject,
6060 APValue *Value,
6061 QualType Type) {
6062 bool HadZeroInit = !Value->isUninit();
6063
6064 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6065 unsigned N = CAT->getSize().getZExtValue();
6066
6067 // Preserve the array filler if we had prior zero-initialization.
6068 APValue Filler =
6069 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6070 : APValue();
6071
6072 *Value = APValue(APValue::UninitArray(), N, N);
6073
6074 if (HadZeroInit)
6075 for (unsigned I = 0; I != N; ++I)
6076 Value->getArrayInitializedElt(I) = Filler;
6077
6078 // Initialize the elements.
6079 LValue ArrayElt = Subobject;
6080 ArrayElt.addArray(Info, E, CAT);
6081 for (unsigned I = 0; I != N; ++I)
6082 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6083 CAT->getElementType()) ||
6084 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6085 CAT->getElementType(), 1))
6086 return false;
6087
6088 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006089 }
Richard Smith027bf112011-11-17 22:56:20 +00006090
Richard Smith9543c5e2013-04-22 14:44:29 +00006091 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006092 return Error(E);
6093
Richard Smithb8348f52016-05-12 22:16:28 +00006094 return RecordExprEvaluator(Info, Subobject, *Value)
6095 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006096}
6097
Richard Smithf3e9e432011-11-07 09:22:26 +00006098//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006099// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006100//
6101// As a GNU extension, we support casting pointers to sufficiently-wide integer
6102// types and back in constant folding. Integer values are thus represented
6103// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006104//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006105
6106namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006107class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006108 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006109 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006110public:
Richard Smith2e312c82012-03-03 22:46:17 +00006111 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006112 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006113
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006114 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006115 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006116 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006117 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006118 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006119 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006120 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006121 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006122 return true;
6123 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006124 bool Success(const llvm::APSInt &SI, const Expr *E) {
6125 return Success(SI, E, Result);
6126 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006127
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006128 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006129 assert(E->getType()->isIntegralOrEnumerationType() &&
6130 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006131 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006132 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006133 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006134 Result.getInt().setIsUnsigned(
6135 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006136 return true;
6137 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006138 bool Success(const llvm::APInt &I, const Expr *E) {
6139 return Success(I, E, Result);
6140 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006141
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006142 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006143 assert(E->getType()->isIntegralOrEnumerationType() &&
6144 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006145 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006146 return true;
6147 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006148 bool Success(uint64_t Value, const Expr *E) {
6149 return Success(Value, E, Result);
6150 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006151
Ken Dyckdbc01912011-03-11 02:13:43 +00006152 bool Success(CharUnits Size, const Expr *E) {
6153 return Success(Size.getQuantity(), E);
6154 }
6155
Richard Smith2e312c82012-03-03 22:46:17 +00006156 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006157 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006158 Result = V;
6159 return true;
6160 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006161 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006162 }
Mike Stump11289f42009-09-09 15:08:12 +00006163
Richard Smithfddd3842011-12-30 21:15:51 +00006164 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006165
Peter Collingbournee9200682011-05-13 03:29:01 +00006166 //===--------------------------------------------------------------------===//
6167 // Visitor Methods
6168 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006169
Chris Lattner7174bf32008-07-12 00:38:25 +00006170 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006171 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006172 }
6173 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006174 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006175 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006176
6177 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6178 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006179 if (CheckReferencedDecl(E, E->getDecl()))
6180 return true;
6181
6182 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006183 }
6184 bool VisitMemberExpr(const MemberExpr *E) {
6185 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006186 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006187 return true;
6188 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006189
6190 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006191 }
6192
Peter Collingbournee9200682011-05-13 03:29:01 +00006193 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006194 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006195 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006196 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006197
Peter Collingbournee9200682011-05-13 03:29:01 +00006198 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006199 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006200
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006201 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006202 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006203 }
Mike Stump11289f42009-09-09 15:08:12 +00006204
Ted Kremeneke65b0862012-03-06 20:05:56 +00006205 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6206 return Success(E->getValue(), E);
6207 }
6208
Richard Smith4ce706a2011-10-11 21:43:33 +00006209 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006210 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006211 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006212 }
6213
Douglas Gregor29c42f22012-02-24 07:38:34 +00006214 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6215 return Success(E->getValue(), E);
6216 }
6217
John Wiegley6242b6a2011-04-28 00:16:57 +00006218 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6219 return Success(E->getValue(), E);
6220 }
6221
John Wiegleyf9f65842011-04-25 06:54:41 +00006222 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6223 return Success(E->getValue(), E);
6224 }
6225
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006226 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006227 bool VisitUnaryImag(const UnaryOperator *E);
6228
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006229 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006230 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006231
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006232private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006233 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006234 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006235};
Chris Lattner05706e882008-07-11 18:11:29 +00006236} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006237
Richard Smith11562c52011-10-28 17:51:58 +00006238/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6239/// produce either the integer value or a pointer.
6240///
6241/// GCC has a heinous extension which folds casts between pointer types and
6242/// pointer-sized integral types. We support this by allowing the evaluation of
6243/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6244/// Some simple arithmetic on such values is supported (they are treated much
6245/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006246static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006247 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006248 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006249 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006250}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006251
Richard Smithf57d8cb2011-12-09 22:58:01 +00006252static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006253 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006254 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006255 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006256 if (!Val.isInt()) {
6257 // FIXME: It would be better to produce the diagnostic for casting
6258 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006259 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006260 return false;
6261 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006262 Result = Val.getInt();
6263 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006264}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006265
Richard Smithf57d8cb2011-12-09 22:58:01 +00006266/// Check whether the given declaration can be directly converted to an integral
6267/// rvalue. If not, no diagnostic is produced; there are other things we can
6268/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006269bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006270 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006271 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006272 // Check for signedness/width mismatches between E type and ECD value.
6273 bool SameSign = (ECD->getInitVal().isSigned()
6274 == E->getType()->isSignedIntegerOrEnumerationType());
6275 bool SameWidth = (ECD->getInitVal().getBitWidth()
6276 == Info.Ctx.getIntWidth(E->getType()));
6277 if (SameSign && SameWidth)
6278 return Success(ECD->getInitVal(), E);
6279 else {
6280 // Get rid of mismatch (otherwise Success assertions will fail)
6281 // by computing a new value matching the type of E.
6282 llvm::APSInt Val = ECD->getInitVal();
6283 if (!SameSign)
6284 Val.setIsSigned(!ECD->getInitVal().isSigned());
6285 if (!SameWidth)
6286 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6287 return Success(Val, E);
6288 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006289 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006290 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006291}
6292
Chris Lattner86ee2862008-10-06 06:40:35 +00006293/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6294/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006295static int EvaluateBuiltinClassifyType(const CallExpr *E,
6296 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006297 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006298 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006299 enum gcc_type_class {
6300 no_type_class = -1,
6301 void_type_class, integer_type_class, char_type_class,
6302 enumeral_type_class, boolean_type_class,
6303 pointer_type_class, reference_type_class, offset_type_class,
6304 real_type_class, complex_type_class,
6305 function_type_class, method_type_class,
6306 record_type_class, union_type_class,
6307 array_type_class, string_type_class,
6308 lang_type_class
6309 };
Mike Stump11289f42009-09-09 15:08:12 +00006310
6311 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006312 // ideal, however it is what gcc does.
6313 if (E->getNumArgs() == 0)
6314 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006315
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006316 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6317 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6318
6319 switch (CanTy->getTypeClass()) {
6320#define TYPE(ID, BASE)
6321#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6322#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6323#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6324#include "clang/AST/TypeNodes.def"
6325 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6326
6327 case Type::Builtin:
6328 switch (BT->getKind()) {
6329#define BUILTIN_TYPE(ID, SINGLETON_ID)
6330#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6331#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6332#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6333#include "clang/AST/BuiltinTypes.def"
6334 case BuiltinType::Void:
6335 return void_type_class;
6336
6337 case BuiltinType::Bool:
6338 return boolean_type_class;
6339
6340 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6341 case BuiltinType::UChar:
6342 case BuiltinType::UShort:
6343 case BuiltinType::UInt:
6344 case BuiltinType::ULong:
6345 case BuiltinType::ULongLong:
6346 case BuiltinType::UInt128:
6347 return integer_type_class;
6348
6349 case BuiltinType::NullPtr:
6350 return pointer_type_class;
6351
6352 case BuiltinType::WChar_U:
6353 case BuiltinType::Char16:
6354 case BuiltinType::Char32:
6355 case BuiltinType::ObjCId:
6356 case BuiltinType::ObjCClass:
6357 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006358#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6359 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006360#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006361 case BuiltinType::OCLSampler:
6362 case BuiltinType::OCLEvent:
6363 case BuiltinType::OCLClkEvent:
6364 case BuiltinType::OCLQueue:
6365 case BuiltinType::OCLNDRange:
6366 case BuiltinType::OCLReserveID:
6367 case BuiltinType::Dependent:
6368 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6369 };
6370
6371 case Type::Enum:
6372 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6373 break;
6374
6375 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006376 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006377 break;
6378
6379 case Type::MemberPointer:
6380 if (CanTy->isMemberDataPointerType())
6381 return offset_type_class;
6382 else {
6383 // We expect member pointers to be either data or function pointers,
6384 // nothing else.
6385 assert(CanTy->isMemberFunctionPointerType());
6386 return method_type_class;
6387 }
6388
6389 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006390 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006391
6392 case Type::FunctionNoProto:
6393 case Type::FunctionProto:
6394 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6395
6396 case Type::Record:
6397 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6398 switch (RT->getDecl()->getTagKind()) {
6399 case TagTypeKind::TTK_Struct:
6400 case TagTypeKind::TTK_Class:
6401 case TagTypeKind::TTK_Interface:
6402 return record_type_class;
6403
6404 case TagTypeKind::TTK_Enum:
6405 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6406
6407 case TagTypeKind::TTK_Union:
6408 return union_type_class;
6409 }
6410 }
David Blaikie83d382b2011-09-23 05:06:16 +00006411 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006412
6413 case Type::ConstantArray:
6414 case Type::VariableArray:
6415 case Type::IncompleteArray:
6416 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6417
6418 case Type::BlockPointer:
6419 case Type::LValueReference:
6420 case Type::RValueReference:
6421 case Type::Vector:
6422 case Type::ExtVector:
6423 case Type::Auto:
6424 case Type::ObjCObject:
6425 case Type::ObjCInterface:
6426 case Type::ObjCObjectPointer:
6427 case Type::Pipe:
6428 case Type::Atomic:
6429 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6430 }
6431
6432 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006433}
6434
Richard Smith5fab0c92011-12-28 19:48:30 +00006435/// EvaluateBuiltinConstantPForLValue - Determine the result of
6436/// __builtin_constant_p when applied to the given lvalue.
6437///
6438/// An lvalue is only "constant" if it is a pointer or reference to the first
6439/// character of a string literal.
6440template<typename LValue>
6441static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006442 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006443 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6444}
6445
6446/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6447/// GCC as we can manage.
6448static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6449 QualType ArgType = Arg->getType();
6450
6451 // __builtin_constant_p always has one operand. The rules which gcc follows
6452 // are not precisely documented, but are as follows:
6453 //
6454 // - If the operand is of integral, floating, complex or enumeration type,
6455 // and can be folded to a known value of that type, it returns 1.
6456 // - If the operand and can be folded to a pointer to the first character
6457 // of a string literal (or such a pointer cast to an integral type), it
6458 // returns 1.
6459 //
6460 // Otherwise, it returns 0.
6461 //
6462 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6463 // its support for this does not currently work.
6464 if (ArgType->isIntegralOrEnumerationType()) {
6465 Expr::EvalResult Result;
6466 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6467 return false;
6468
6469 APValue &V = Result.Val;
6470 if (V.getKind() == APValue::Int)
6471 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006472 if (V.getKind() == APValue::LValue)
6473 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006474 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6475 return Arg->isEvaluatable(Ctx);
6476 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6477 LValue LV;
6478 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006479 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006480 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6481 : EvaluatePointer(Arg, LV, Info)) &&
6482 !Status.HasSideEffects)
6483 return EvaluateBuiltinConstantPForLValue(LV);
6484 }
6485
6486 // Anything else isn't considered to be sufficiently constant.
6487 return false;
6488}
6489
John McCall95007602010-05-10 23:27:23 +00006490/// Retrieves the "underlying object type" of the given expression,
6491/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006492static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006493 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6494 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006495 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006496 } else if (const Expr *E = B.get<const Expr*>()) {
6497 if (isa<CompoundLiteralExpr>(E))
6498 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006499 }
6500
6501 return QualType();
6502}
6503
George Burgess IV3a03fab2015-09-04 21:28:13 +00006504/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006505/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6506/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006507/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6508///
6509/// Always returns an RValue with a pointer representation.
6510static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6511 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6512
6513 auto *NoParens = E->IgnoreParens();
6514 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006515 if (Cast == nullptr)
6516 return NoParens;
6517
6518 // We only conservatively allow a few kinds of casts, because this code is
6519 // inherently a simple solution that seeks to support the common case.
6520 auto CastKind = Cast->getCastKind();
6521 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6522 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006523 return NoParens;
6524
6525 auto *SubExpr = Cast->getSubExpr();
6526 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6527 return NoParens;
6528 return ignorePointerCastsAndParens(SubExpr);
6529}
6530
George Burgess IVa51c4072015-10-16 01:49:01 +00006531/// Checks to see if the given LValue's Designator is at the end of the LValue's
6532/// record layout. e.g.
6533/// struct { struct { int a, b; } fst, snd; } obj;
6534/// obj.fst // no
6535/// obj.snd // yes
6536/// obj.fst.a // no
6537/// obj.fst.b // no
6538/// obj.snd.a // no
6539/// obj.snd.b // yes
6540///
6541/// Please note: this function is specialized for how __builtin_object_size
6542/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006543///
6544/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006545static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6546 assert(!LVal.Designator.Invalid);
6547
George Burgess IV4168d752016-06-27 19:40:41 +00006548 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6549 const RecordDecl *Parent = FD->getParent();
6550 Invalid = Parent->isInvalidDecl();
6551 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006552 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006553 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006554 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6555 };
6556
6557 auto &Base = LVal.getLValueBase();
6558 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6559 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006560 bool Invalid;
6561 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6562 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006563 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006564 for (auto *FD : IFD->chain()) {
6565 bool Invalid;
6566 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6567 return Invalid;
6568 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006569 }
6570 }
6571
6572 QualType BaseType = getType(Base);
6573 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6574 if (BaseType->isArrayType()) {
6575 // Because __builtin_object_size treats arrays as objects, we can ignore
6576 // the index iff this is the last array in the Designator.
6577 if (I + 1 == E)
6578 return true;
6579 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6580 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6581 if (Index + 1 != CAT->getSize())
6582 return false;
6583 BaseType = CAT->getElementType();
6584 } else if (BaseType->isAnyComplexType()) {
6585 auto *CT = BaseType->castAs<ComplexType>();
6586 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6587 if (Index != 1)
6588 return false;
6589 BaseType = CT->getElementType();
6590 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006591 bool Invalid;
6592 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6593 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006594 BaseType = FD->getType();
6595 } else {
6596 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6597 "Expecting cast to a base class");
6598 return false;
6599 }
6600 }
6601 return true;
6602}
6603
6604/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6605static bool refersToCompleteObject(const LValue &LVal) {
6606 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6607 return false;
6608
6609 if (!LVal.InvalidBase)
6610 return true;
6611
6612 auto *E = LVal.Base.dyn_cast<const Expr *>();
6613 (void)E;
6614 assert(E != nullptr && isa<MemberExpr>(E));
6615 return false;
6616}
6617
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006618/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6619/// true and stores the result in @p Size.
6620///
6621/// If @p WasError is non-null, this will report whether the failure to evaluate
6622/// is to be treated as an Error in IntExprEvaluator.
6623static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6624 EvalInfo &Info, uint64_t &Size,
6625 bool *WasError = nullptr) {
6626 if (WasError != nullptr)
6627 *WasError = false;
6628
6629 auto Error = [&](const Expr *E) {
6630 if (WasError != nullptr)
6631 *WasError = true;
6632 return false;
6633 };
6634
6635 auto Success = [&](uint64_t S, const Expr *E) {
6636 Size = S;
6637 return true;
6638 };
6639
George Burgess IVbdb5b262015-08-19 02:19:07 +00006640 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006641 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006642 {
6643 // The operand of __builtin_object_size is never evaluated for side-effects.
6644 // If there are any, but we can determine the pointed-to object anyway, then
6645 // ignore the side-effects.
6646 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006647 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006648
6649 if (E->isGLValue()) {
6650 // It's possible for us to be given GLValues if we're called via
6651 // Expr::tryEvaluateObjectSize.
6652 APValue RVal;
6653 if (!EvaluateAsRValue(Info, E, RVal))
6654 return false;
6655 Base.setFrom(Info.Ctx, RVal);
6656 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006657 return false;
6658 }
John McCall95007602010-05-10 23:27:23 +00006659
George Burgess IVbdb5b262015-08-19 02:19:07 +00006660 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006661 // If we point to before the start of the object, there are no accessible
6662 // bytes.
6663 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006664 return Success(0, E);
6665
George Burgess IV3a03fab2015-09-04 21:28:13 +00006666 // In the case where we're not dealing with a subobject, we discard the
6667 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006668 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006669
6670 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6671 // exist. If we can't verify the base, then we can't do that.
6672 //
6673 // As a special case, we produce a valid object size for an unknown object
6674 // with a known designator if Type & 1 is 1. For instance:
6675 //
6676 // extern struct X { char buff[32]; int a, b, c; } *p;
6677 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6678 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6679 //
6680 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006681 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006682 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006683
George Burgess IVa51c4072015-10-16 01:49:01 +00006684 // If we're not examining only the subobject, then we reset to a complete
6685 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006686 //
6687 // If Type is 1 and we've lost track of the subobject, just find the complete
6688 // object instead. (If Type is 3, that's not correct behavior and we should
6689 // return 0 instead.)
6690 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006691 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006692 QualType T = getObjectType(End.getLValueBase());
6693 if (T.isNull())
6694 End.Designator.setInvalid();
6695 else {
6696 End.Designator = SubobjectDesignator(T);
6697 End.Offset = CharUnits::Zero();
6698 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006699 }
John McCall95007602010-05-10 23:27:23 +00006700
George Burgess IVbdb5b262015-08-19 02:19:07 +00006701 // If it is not possible to determine which objects ptr points to at compile
6702 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6703 // and (size_t) 0 for type 2 or 3.
6704 if (End.Designator.Invalid)
6705 return false;
6706
6707 // According to the GCC documentation, we want the size of the subobject
6708 // denoted by the pointer. But that's not quite right -- what we actually
6709 // want is the size of the immediately-enclosing array, if there is one.
6710 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006711 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006712 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6713 // We got a pointer to an array. Step to its end.
6714 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006715 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006716 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006717 // We're already pointing at the end of the object.
6718 AmountToAdd = 0;
6719 }
6720
George Burgess IV3a03fab2015-09-04 21:28:13 +00006721 QualType PointeeType = End.Designator.MostDerivedType;
6722 assert(!PointeeType.isNull());
6723 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006724 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006725
George Burgess IVbdb5b262015-08-19 02:19:07 +00006726 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6727 AmountToAdd))
6728 return false;
John McCall95007602010-05-10 23:27:23 +00006729
George Burgess IVbdb5b262015-08-19 02:19:07 +00006730 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006731
6732 // The following is a moderately common idiom in C:
6733 //
6734 // struct Foo { int a; char c[1]; };
6735 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6736 // strcpy(&F->c[0], Bar);
6737 //
6738 // So, if we see that we're examining a 1-length (or 0-length) array at the
6739 // end of a struct with an unknown base, we give up instead of breaking code
6740 // that behaves this way. Note that we only do this when Type=1, because
6741 // Type=3 is a lower bound, so answering conservatively is fine.
6742 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6743 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6744 End.Designator.MostDerivedIsArrayElement &&
6745 End.Designator.MostDerivedArraySize < 2 &&
6746 isDesignatorAtObjectEnd(Info.Ctx, End))
6747 return false;
6748
George Burgess IVbdb5b262015-08-19 02:19:07 +00006749 if (BaseOffset > EndOffset)
6750 return Success(0, E);
6751
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006752 return Success((EndOffset - BaseOffset).getQuantity(), E);
6753}
6754
6755bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6756 unsigned Type) {
6757 uint64_t Size;
6758 bool WasError;
6759 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6760 return Success(Size, E);
6761 if (WasError)
6762 return Error(E);
6763 return false;
John McCall95007602010-05-10 23:27:23 +00006764}
6765
Peter Collingbournee9200682011-05-13 03:29:01 +00006766bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006767 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006768 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006769 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006770
6771 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006772 // The type was checked when we built the expression.
6773 unsigned Type =
6774 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6775 assert(Type <= 3 && "unexpected type");
6776
6777 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006778 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006779
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006780 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006781 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006782
Richard Smith01ade172012-05-23 04:13:20 +00006783 // Expression had no side effects, but we couldn't statically determine the
6784 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006785 switch (Info.EvalMode) {
6786 case EvalInfo::EM_ConstantExpression:
6787 case EvalInfo::EM_PotentialConstantExpression:
6788 case EvalInfo::EM_ConstantFold:
6789 case EvalInfo::EM_EvaluateForOverflow:
6790 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006791 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006792 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006793 return Error(E);
6794 case EvalInfo::EM_ConstantExpressionUnevaluated:
6795 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006796 // Reduce it to a constant now.
6797 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006798 }
Mike Stump722cedf2009-10-26 18:35:08 +00006799 }
6800
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006801 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006802 case Builtin::BI__builtin_bswap32:
6803 case Builtin::BI__builtin_bswap64: {
6804 APSInt Val;
6805 if (!EvaluateInteger(E->getArg(0), Val, Info))
6806 return false;
6807
6808 return Success(Val.byteSwap(), E);
6809 }
6810
Richard Smith8889a3d2013-06-13 06:26:32 +00006811 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006812 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006813
6814 // FIXME: BI__builtin_clrsb
6815 // FIXME: BI__builtin_clrsbl
6816 // FIXME: BI__builtin_clrsbll
6817
Richard Smith80b3c8e2013-06-13 05:04:16 +00006818 case Builtin::BI__builtin_clz:
6819 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006820 case Builtin::BI__builtin_clzll:
6821 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006822 APSInt Val;
6823 if (!EvaluateInteger(E->getArg(0), Val, Info))
6824 return false;
6825 if (!Val)
6826 return Error(E);
6827
6828 return Success(Val.countLeadingZeros(), E);
6829 }
6830
Richard Smith8889a3d2013-06-13 06:26:32 +00006831 case Builtin::BI__builtin_constant_p:
6832 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6833
Richard Smith80b3c8e2013-06-13 05:04:16 +00006834 case Builtin::BI__builtin_ctz:
6835 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006836 case Builtin::BI__builtin_ctzll:
6837 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006838 APSInt Val;
6839 if (!EvaluateInteger(E->getArg(0), Val, Info))
6840 return false;
6841 if (!Val)
6842 return Error(E);
6843
6844 return Success(Val.countTrailingZeros(), E);
6845 }
6846
Richard Smith8889a3d2013-06-13 06:26:32 +00006847 case Builtin::BI__builtin_eh_return_data_regno: {
6848 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6849 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6850 return Success(Operand, E);
6851 }
6852
6853 case Builtin::BI__builtin_expect:
6854 return Visit(E->getArg(0));
6855
6856 case Builtin::BI__builtin_ffs:
6857 case Builtin::BI__builtin_ffsl:
6858 case Builtin::BI__builtin_ffsll: {
6859 APSInt Val;
6860 if (!EvaluateInteger(E->getArg(0), Val, Info))
6861 return false;
6862
6863 unsigned N = Val.countTrailingZeros();
6864 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6865 }
6866
6867 case Builtin::BI__builtin_fpclassify: {
6868 APFloat Val(0.0);
6869 if (!EvaluateFloat(E->getArg(5), Val, Info))
6870 return false;
6871 unsigned Arg;
6872 switch (Val.getCategory()) {
6873 case APFloat::fcNaN: Arg = 0; break;
6874 case APFloat::fcInfinity: Arg = 1; break;
6875 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6876 case APFloat::fcZero: Arg = 4; break;
6877 }
6878 return Visit(E->getArg(Arg));
6879 }
6880
6881 case Builtin::BI__builtin_isinf_sign: {
6882 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006883 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006884 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6885 }
6886
Richard Smithea3019d2013-10-15 19:07:14 +00006887 case Builtin::BI__builtin_isinf: {
6888 APFloat Val(0.0);
6889 return EvaluateFloat(E->getArg(0), Val, Info) &&
6890 Success(Val.isInfinity() ? 1 : 0, E);
6891 }
6892
6893 case Builtin::BI__builtin_isfinite: {
6894 APFloat Val(0.0);
6895 return EvaluateFloat(E->getArg(0), Val, Info) &&
6896 Success(Val.isFinite() ? 1 : 0, E);
6897 }
6898
6899 case Builtin::BI__builtin_isnan: {
6900 APFloat Val(0.0);
6901 return EvaluateFloat(E->getArg(0), Val, Info) &&
6902 Success(Val.isNaN() ? 1 : 0, E);
6903 }
6904
6905 case Builtin::BI__builtin_isnormal: {
6906 APFloat Val(0.0);
6907 return EvaluateFloat(E->getArg(0), Val, Info) &&
6908 Success(Val.isNormal() ? 1 : 0, E);
6909 }
6910
Richard Smith8889a3d2013-06-13 06:26:32 +00006911 case Builtin::BI__builtin_parity:
6912 case Builtin::BI__builtin_parityl:
6913 case Builtin::BI__builtin_parityll: {
6914 APSInt Val;
6915 if (!EvaluateInteger(E->getArg(0), Val, Info))
6916 return false;
6917
6918 return Success(Val.countPopulation() % 2, E);
6919 }
6920
Richard Smith80b3c8e2013-06-13 05:04:16 +00006921 case Builtin::BI__builtin_popcount:
6922 case Builtin::BI__builtin_popcountl:
6923 case Builtin::BI__builtin_popcountll: {
6924 APSInt Val;
6925 if (!EvaluateInteger(E->getArg(0), Val, Info))
6926 return false;
6927
6928 return Success(Val.countPopulation(), E);
6929 }
6930
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006931 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006932 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006933 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006934 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006935 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6936 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006937 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006938 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006939 case Builtin::BI__builtin_strlen: {
6940 // As an extension, we support __builtin_strlen() as a constant expression,
6941 // and support folding strlen() to a constant.
6942 LValue String;
6943 if (!EvaluatePointer(E->getArg(0), String, Info))
6944 return false;
6945
6946 // Fast path: if it's a string literal, search the string value.
6947 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6948 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006949 // The string literal may have embedded null characters. Find the first
6950 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006951 StringRef Str = S->getBytes();
6952 int64_t Off = String.Offset.getQuantity();
6953 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6954 S->getCharByteWidth() == 1) {
6955 Str = Str.substr(Off);
6956
6957 StringRef::size_type Pos = Str.find(0);
6958 if (Pos != StringRef::npos)
6959 Str = Str.substr(0, Pos);
6960
6961 return Success(Str.size(), E);
6962 }
6963
6964 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006965 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006966
6967 // Slow path: scan the bytes of the string looking for the terminating 0.
6968 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6969 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6970 APValue Char;
6971 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6972 !Char.isInt())
6973 return false;
6974 if (!Char.getInt())
6975 return Success(Strlen, E);
6976 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6977 return false;
6978 }
6979 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006980
Richard Smith01ba47d2012-04-13 00:45:38 +00006981 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006982 case Builtin::BI__atomic_is_lock_free:
6983 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006984 APSInt SizeVal;
6985 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6986 return false;
6987
6988 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6989 // of two less than the maximum inline atomic width, we know it is
6990 // lock-free. If the size isn't a power of two, or greater than the
6991 // maximum alignment where we promote atomics, we know it is not lock-free
6992 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6993 // the answer can only be determined at runtime; for example, 16-byte
6994 // atomics have lock-free implementations on some, but not all,
6995 // x86-64 processors.
6996
6997 // Check power-of-two.
6998 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006999 if (Size.isPowerOfTwo()) {
7000 // Check against inlining width.
7001 unsigned InlineWidthBits =
7002 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7003 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7004 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7005 Size == CharUnits::One() ||
7006 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7007 Expr::NPC_NeverValueDependent))
7008 // OK, we will inline appropriately-aligned operations of this size,
7009 // and _Atomic(T) is appropriately-aligned.
7010 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007011
Richard Smith01ba47d2012-04-13 00:45:38 +00007012 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7013 castAs<PointerType>()->getPointeeType();
7014 if (!PointeeType->isIncompleteType() &&
7015 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7016 // OK, we will inline operations on this object.
7017 return Success(1, E);
7018 }
7019 }
7020 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007021
Richard Smith01ba47d2012-04-13 00:45:38 +00007022 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7023 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007024 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007025 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007026}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007027
Richard Smith8b3497e2011-10-31 01:37:14 +00007028static bool HasSameBase(const LValue &A, const LValue &B) {
7029 if (!A.getLValueBase())
7030 return !B.getLValueBase();
7031 if (!B.getLValueBase())
7032 return false;
7033
Richard Smithce40ad62011-11-12 22:28:03 +00007034 if (A.getLValueBase().getOpaqueValue() !=
7035 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007036 const Decl *ADecl = GetLValueBaseDecl(A);
7037 if (!ADecl)
7038 return false;
7039 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007040 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007041 return false;
7042 }
7043
7044 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007045 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007046}
7047
Richard Smithd20f1e62014-10-21 23:01:04 +00007048/// \brief Determine whether this is a pointer past the end of the complete
7049/// object referred to by the lvalue.
7050static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7051 const LValue &LV) {
7052 // A null pointer can be viewed as being "past the end" but we don't
7053 // choose to look at it that way here.
7054 if (!LV.getLValueBase())
7055 return false;
7056
7057 // If the designator is valid and refers to a subobject, we're not pointing
7058 // past the end.
7059 if (!LV.getLValueDesignator().Invalid &&
7060 !LV.getLValueDesignator().isOnePastTheEnd())
7061 return false;
7062
David Majnemerc378ca52015-08-29 08:32:55 +00007063 // A pointer to an incomplete type might be past-the-end if the type's size is
7064 // zero. We cannot tell because the type is incomplete.
7065 QualType Ty = getType(LV.getLValueBase());
7066 if (Ty->isIncompleteType())
7067 return true;
7068
Richard Smithd20f1e62014-10-21 23:01:04 +00007069 // We're a past-the-end pointer if we point to the byte after the object,
7070 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007071 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007072 return LV.getLValueOffset() == Size;
7073}
7074
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007075namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007076
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007077/// \brief Data recursive integer evaluator of certain binary operators.
7078///
7079/// We use a data recursive algorithm for binary operators so that we are able
7080/// to handle extreme cases of chained binary operators without causing stack
7081/// overflow.
7082class DataRecursiveIntBinOpEvaluator {
7083 struct EvalResult {
7084 APValue Val;
7085 bool Failed;
7086
7087 EvalResult() : Failed(false) { }
7088
7089 void swap(EvalResult &RHS) {
7090 Val.swap(RHS.Val);
7091 Failed = RHS.Failed;
7092 RHS.Failed = false;
7093 }
7094 };
7095
7096 struct Job {
7097 const Expr *E;
7098 EvalResult LHSResult; // meaningful only for binary operator expression.
7099 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007100
David Blaikie73726062015-08-12 23:09:24 +00007101 Job() = default;
7102 Job(Job &&J)
7103 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
George Burgess IV8c892b52016-05-25 22:31:54 +00007104 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
David Blaikie73726062015-08-12 23:09:24 +00007105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007106 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007107 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007108 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007109
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007110 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007111 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007112 };
7113
7114 SmallVector<Job, 16> Queue;
7115
7116 IntExprEvaluator &IntEval;
7117 EvalInfo &Info;
7118 APValue &FinalResult;
7119
7120public:
7121 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7122 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7123
7124 /// \brief True if \param E is a binary operator that we are going to handle
7125 /// data recursively.
7126 /// We handle binary operators that are comma, logical, or that have operands
7127 /// with integral or enumeration type.
7128 static bool shouldEnqueue(const BinaryOperator *E) {
7129 return E->getOpcode() == BO_Comma ||
7130 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007131 (E->isRValue() &&
7132 E->getType()->isIntegralOrEnumerationType() &&
7133 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007134 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007135 }
7136
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007137 bool Traverse(const BinaryOperator *E) {
7138 enqueue(E);
7139 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007140 while (!Queue.empty())
7141 process(PrevResult);
7142
7143 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007144
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007145 FinalResult.swap(PrevResult.Val);
7146 return true;
7147 }
7148
7149private:
7150 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7151 return IntEval.Success(Value, E, Result);
7152 }
7153 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7154 return IntEval.Success(Value, E, Result);
7155 }
7156 bool Error(const Expr *E) {
7157 return IntEval.Error(E);
7158 }
7159 bool Error(const Expr *E, diag::kind D) {
7160 return IntEval.Error(E, D);
7161 }
7162
7163 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7164 return Info.CCEDiag(E, D);
7165 }
7166
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007167 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7168 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007169 bool &SuppressRHSDiags);
7170
7171 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7172 const BinaryOperator *E, APValue &Result);
7173
7174 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7175 Result.Failed = !Evaluate(Result.Val, Info, E);
7176 if (Result.Failed)
7177 Result.Val = APValue();
7178 }
7179
Richard Trieuba4d0872012-03-21 23:30:30 +00007180 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007181
7182 void enqueue(const Expr *E) {
7183 E = E->IgnoreParens();
7184 Queue.resize(Queue.size()+1);
7185 Queue.back().E = E;
7186 Queue.back().Kind = Job::AnyExprKind;
7187 }
7188};
7189
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007190}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007191
7192bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007193 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007194 bool &SuppressRHSDiags) {
7195 if (E->getOpcode() == BO_Comma) {
7196 // Ignore LHS but note if we could not evaluate it.
7197 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007198 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007199 return true;
7200 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007201
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007202 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007203 bool LHSAsBool;
7204 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007205 // We were able to evaluate the LHS, see if we can get away with not
7206 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007207 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7208 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007209 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007210 }
7211 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007212 LHSResult.Failed = true;
7213
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007214 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007215 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007216 if (!Info.noteSideEffect())
7217 return false;
7218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007219 // We can't evaluate the LHS; however, sometimes the result
7220 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7221 // Don't ignore RHS and suppress diagnostics from this arm.
7222 SuppressRHSDiags = true;
7223 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007224
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007225 return true;
7226 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007227
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007228 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7229 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007230
George Burgess IVa145e252016-05-25 22:38:36 +00007231 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007232 return false; // Ignore RHS;
7233
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007234 return true;
7235}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007236
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007237bool DataRecursiveIntBinOpEvaluator::
7238 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7239 const BinaryOperator *E, APValue &Result) {
7240 if (E->getOpcode() == BO_Comma) {
7241 if (RHSResult.Failed)
7242 return false;
7243 Result = RHSResult.Val;
7244 return true;
7245 }
7246
7247 if (E->isLogicalOp()) {
7248 bool lhsResult, rhsResult;
7249 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7250 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7251
7252 if (LHSIsOK) {
7253 if (RHSIsOK) {
7254 if (E->getOpcode() == BO_LOr)
7255 return Success(lhsResult || rhsResult, E, Result);
7256 else
7257 return Success(lhsResult && rhsResult, E, Result);
7258 }
7259 } else {
7260 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007261 // We can't evaluate the LHS; however, sometimes the result
7262 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7263 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007264 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007265 }
7266 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007267
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007268 return false;
7269 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007270
7271 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7272 E->getRHS()->getType()->isIntegralOrEnumerationType());
7273
7274 if (LHSResult.Failed || RHSResult.Failed)
7275 return false;
7276
7277 const APValue &LHSVal = LHSResult.Val;
7278 const APValue &RHSVal = RHSResult.Val;
7279
7280 // Handle cases like (unsigned long)&a + 4.
7281 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7282 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007283 CharUnits AdditionalOffset =
7284 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007285 if (E->getOpcode() == BO_Add)
7286 Result.getLValueOffset() += AdditionalOffset;
7287 else
7288 Result.getLValueOffset() -= AdditionalOffset;
7289 return true;
7290 }
7291
7292 // Handle cases like 4 + (unsigned long)&a
7293 if (E->getOpcode() == BO_Add &&
7294 RHSVal.isLValue() && LHSVal.isInt()) {
7295 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007296 Result.getLValueOffset() +=
7297 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007298 return true;
7299 }
7300
7301 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7302 // Handle (intptr_t)&&A - (intptr_t)&&B.
7303 if (!LHSVal.getLValueOffset().isZero() ||
7304 !RHSVal.getLValueOffset().isZero())
7305 return false;
7306 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7307 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7308 if (!LHSExpr || !RHSExpr)
7309 return false;
7310 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7311 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7312 if (!LHSAddrExpr || !RHSAddrExpr)
7313 return false;
7314 // Make sure both labels come from the same function.
7315 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7316 RHSAddrExpr->getLabel()->getDeclContext())
7317 return false;
7318 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7319 return true;
7320 }
Richard Smith43e77732013-05-07 04:50:00 +00007321
7322 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007323 if (!LHSVal.isInt() || !RHSVal.isInt())
7324 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007325
7326 // Set up the width and signedness manually, in case it can't be deduced
7327 // from the operation we're performing.
7328 // FIXME: Don't do this in the cases where we can deduce it.
7329 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7330 E->getType()->isUnsignedIntegerOrEnumerationType());
7331 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7332 RHSVal.getInt(), Value))
7333 return false;
7334 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007335}
7336
Richard Trieuba4d0872012-03-21 23:30:30 +00007337void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007338 Job &job = Queue.back();
7339
7340 switch (job.Kind) {
7341 case Job::AnyExprKind: {
7342 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7343 if (shouldEnqueue(Bop)) {
7344 job.Kind = Job::BinOpKind;
7345 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007346 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007347 }
7348 }
7349
7350 EvaluateExpr(job.E, Result);
7351 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007352 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007353 }
7354
7355 case Job::BinOpKind: {
7356 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007357 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007358 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007359 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007360 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007361 }
7362 if (SuppressRHSDiags)
7363 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007364 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007365 job.Kind = Job::BinOpVisitedLHSKind;
7366 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007367 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007368 }
7369
7370 case Job::BinOpVisitedLHSKind: {
7371 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7372 EvalResult RHS;
7373 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007374 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007375 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007376 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007377 }
7378 }
7379
7380 llvm_unreachable("Invalid Job::Kind!");
7381}
7382
George Burgess IV8c892b52016-05-25 22:31:54 +00007383namespace {
7384/// Used when we determine that we should fail, but can keep evaluating prior to
7385/// noting that we had a failure.
7386class DelayedNoteFailureRAII {
7387 EvalInfo &Info;
7388 bool NoteFailure;
7389
7390public:
7391 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7392 : Info(Info), NoteFailure(NoteFailure) {}
7393 ~DelayedNoteFailureRAII() {
7394 if (NoteFailure) {
7395 bool ContinueAfterFailure = Info.noteFailure();
7396 (void)ContinueAfterFailure;
7397 assert(ContinueAfterFailure &&
7398 "Shouldn't have kept evaluating on failure.");
7399 }
7400 }
7401};
7402}
7403
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007404bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007405 // We don't call noteFailure immediately because the assignment happens after
7406 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007407 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007408 return Error(E);
7409
George Burgess IV8c892b52016-05-25 22:31:54 +00007410 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007411 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7412 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007413
Anders Carlssonacc79812008-11-16 07:17:21 +00007414 QualType LHSTy = E->getLHS()->getType();
7415 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007416
Chandler Carruthb29a7432014-10-11 11:03:30 +00007417 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007418 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007419 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007420 if (E->isAssignmentOp()) {
7421 LValue LV;
7422 EvaluateLValue(E->getLHS(), LV, Info);
7423 LHSOK = false;
7424 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007425 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7426 if (LHSOK) {
7427 LHS.makeComplexFloat();
7428 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7429 }
7430 } else {
7431 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7432 }
George Burgess IVa145e252016-05-25 22:38:36 +00007433 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007434 return false;
7435
Chandler Carruthb29a7432014-10-11 11:03:30 +00007436 if (E->getRHS()->getType()->isRealFloatingType()) {
7437 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7438 return false;
7439 RHS.makeComplexFloat();
7440 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7441 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007442 return false;
7443
7444 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007445 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007446 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007447 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007448 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7449
John McCalle3027922010-08-25 11:45:40 +00007450 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007451 return Success((CR_r == APFloat::cmpEqual &&
7452 CR_i == APFloat::cmpEqual), E);
7453 else {
John McCalle3027922010-08-25 11:45:40 +00007454 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007455 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007456 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007457 CR_r == APFloat::cmpLessThan ||
7458 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007459 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007460 CR_i == APFloat::cmpLessThan ||
7461 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007462 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007463 } else {
John McCalle3027922010-08-25 11:45:40 +00007464 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007465 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7466 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7467 else {
John McCalle3027922010-08-25 11:45:40 +00007468 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007469 "Invalid compex comparison.");
7470 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7471 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7472 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007473 }
7474 }
Mike Stump11289f42009-09-09 15:08:12 +00007475
Anders Carlssonacc79812008-11-16 07:17:21 +00007476 if (LHSTy->isRealFloatingType() &&
7477 RHSTy->isRealFloatingType()) {
7478 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007479
Richard Smith253c2a32012-01-27 01:14:48 +00007480 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007481 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007482 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007483
Richard Smith253c2a32012-01-27 01:14:48 +00007484 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007485 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007486
Anders Carlssonacc79812008-11-16 07:17:21 +00007487 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007488
Anders Carlssonacc79812008-11-16 07:17:21 +00007489 switch (E->getOpcode()) {
7490 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007491 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007492 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007493 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007494 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007495 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007496 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007497 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007498 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007499 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007500 E);
John McCalle3027922010-08-25 11:45:40 +00007501 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007502 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007503 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007504 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007505 || CR == APFloat::cmpLessThan
7506 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007507 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007508 }
Mike Stump11289f42009-09-09 15:08:12 +00007509
Eli Friedmana38da572009-04-28 19:17:36 +00007510 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007511 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007512 LValue LHSValue, RHSValue;
7513
7514 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007515 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007516 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007517
Richard Smith253c2a32012-01-27 01:14:48 +00007518 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007519 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007520
Richard Smith8b3497e2011-10-31 01:37:14 +00007521 // Reject differing bases from the normal codepath; we special-case
7522 // comparisons to null.
7523 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007524 if (E->getOpcode() == BO_Sub) {
7525 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007526 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007527 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007528 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007529 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007530 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007531 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007532 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7533 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7534 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007535 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007536 // Make sure both labels come from the same function.
7537 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7538 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007539 return Error(E);
7540 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007541 }
Richard Smith83c68212011-10-31 05:11:32 +00007542 // Inequalities and subtractions between unrelated pointers have
7543 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007544 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007545 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007546 // A constant address may compare equal to the address of a symbol.
7547 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007548 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007549 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7550 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007551 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007552 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007553 // distinct addresses. In clang, the result of such a comparison is
7554 // unspecified, so it is not a constant expression. However, we do know
7555 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007556 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7557 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007558 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007559 // We can't tell whether weak symbols will end up pointing to the same
7560 // object.
7561 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007562 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007563 // We can't compare the address of the start of one object with the
7564 // past-the-end address of another object, per C++ DR1652.
7565 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7566 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7567 (RHSValue.Base && RHSValue.Offset.isZero() &&
7568 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7569 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007570 // We can't tell whether an object is at the same address as another
7571 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007572 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7573 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007574 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007575 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007576 // (Note that clang defaults to -fmerge-all-constants, which can
7577 // lead to inconsistent results for comparisons involving the address
7578 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007579 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007580 }
Eli Friedman64004332009-03-23 04:38:34 +00007581
Richard Smith1b470412012-02-01 08:10:20 +00007582 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7583 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7584
Richard Smith84f6dcf2012-02-02 01:16:57 +00007585 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7586 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7587
John McCalle3027922010-08-25 11:45:40 +00007588 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007589 // C++11 [expr.add]p6:
7590 // Unless both pointers point to elements of the same array object, or
7591 // one past the last element of the array object, the behavior is
7592 // undefined.
7593 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7594 !AreElementsOfSameArray(getType(LHSValue.Base),
7595 LHSDesignator, RHSDesignator))
7596 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7597
Chris Lattner882bdf22010-04-20 17:13:14 +00007598 QualType Type = E->getLHS()->getType();
7599 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007600
Richard Smithd62306a2011-11-10 06:34:14 +00007601 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007602 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007603 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007604
Richard Smith84c6b3d2013-09-10 21:34:14 +00007605 // As an extension, a type may have zero size (empty struct or union in
7606 // C, array of zero length). Pointer subtraction in such cases has
7607 // undefined behavior, so is not constant.
7608 if (ElementSize.isZero()) {
7609 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7610 << ElementType;
7611 return false;
7612 }
7613
Richard Smith1b470412012-02-01 08:10:20 +00007614 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7615 // and produce incorrect results when it overflows. Such behavior
7616 // appears to be non-conforming, but is common, so perhaps we should
7617 // assume the standard intended for such cases to be undefined behavior
7618 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007619
Richard Smith1b470412012-02-01 08:10:20 +00007620 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7621 // overflow in the final conversion to ptrdiff_t.
7622 APSInt LHS(
7623 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7624 APSInt RHS(
7625 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7626 APSInt ElemSize(
7627 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7628 APSInt TrueResult = (LHS - RHS) / ElemSize;
7629 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7630
Richard Smith0c6124b2015-12-03 01:36:22 +00007631 if (Result.extend(65) != TrueResult &&
7632 !HandleOverflow(Info, E, TrueResult, E->getType()))
7633 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007634 return Success(Result, E);
7635 }
Richard Smithde21b242012-01-31 06:41:30 +00007636
7637 // C++11 [expr.rel]p3:
7638 // Pointers to void (after pointer conversions) can be compared, with a
7639 // result defined as follows: If both pointers represent the same
7640 // address or are both the null pointer value, the result is true if the
7641 // operator is <= or >= and false otherwise; otherwise the result is
7642 // unspecified.
7643 // We interpret this as applying to pointers to *cv* void.
7644 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007645 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007646 CCEDiag(E, diag::note_constexpr_void_comparison);
7647
Richard Smith84f6dcf2012-02-02 01:16:57 +00007648 // C++11 [expr.rel]p2:
7649 // - If two pointers point to non-static data members of the same object,
7650 // or to subobjects or array elements fo such members, recursively, the
7651 // pointer to the later declared member compares greater provided the
7652 // two members have the same access control and provided their class is
7653 // not a union.
7654 // [...]
7655 // - Otherwise pointer comparisons are unspecified.
7656 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7657 E->isRelationalOp()) {
7658 bool WasArrayIndex;
7659 unsigned Mismatch =
7660 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7661 RHSDesignator, WasArrayIndex);
7662 // At the point where the designators diverge, the comparison has a
7663 // specified value if:
7664 // - we are comparing array indices
7665 // - we are comparing fields of a union, or fields with the same access
7666 // Otherwise, the result is unspecified and thus the comparison is not a
7667 // constant expression.
7668 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7669 Mismatch < RHSDesignator.Entries.size()) {
7670 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7671 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7672 if (!LF && !RF)
7673 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7674 else if (!LF)
7675 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7676 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7677 << RF->getParent() << RF;
7678 else if (!RF)
7679 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7680 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7681 << LF->getParent() << LF;
7682 else if (!LF->getParent()->isUnion() &&
7683 LF->getAccess() != RF->getAccess())
7684 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7685 << LF << LF->getAccess() << RF << RF->getAccess()
7686 << LF->getParent();
7687 }
7688 }
7689
Eli Friedman6c31cb42012-04-16 04:30:08 +00007690 // The comparison here must be unsigned, and performed with the same
7691 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007692 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7693 uint64_t CompareLHS = LHSOffset.getQuantity();
7694 uint64_t CompareRHS = RHSOffset.getQuantity();
7695 assert(PtrSize <= 64 && "Unexpected pointer width");
7696 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7697 CompareLHS &= Mask;
7698 CompareRHS &= Mask;
7699
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007700 // If there is a base and this is a relational operator, we can only
7701 // compare pointers within the object in question; otherwise, the result
7702 // depends on where the object is located in memory.
7703 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7704 QualType BaseTy = getType(LHSValue.Base);
7705 if (BaseTy->isIncompleteType())
7706 return Error(E);
7707 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7708 uint64_t OffsetLimit = Size.getQuantity();
7709 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7710 return Error(E);
7711 }
7712
Richard Smith8b3497e2011-10-31 01:37:14 +00007713 switch (E->getOpcode()) {
7714 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007715 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7716 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7717 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7718 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7719 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7720 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007721 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007722 }
7723 }
Richard Smith7bb00672012-02-01 01:42:44 +00007724
7725 if (LHSTy->isMemberPointerType()) {
7726 assert(E->isEqualityOp() && "unexpected member pointer operation");
7727 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7728
7729 MemberPtr LHSValue, RHSValue;
7730
7731 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007732 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007733 return false;
7734
7735 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7736 return false;
7737
7738 // C++11 [expr.eq]p2:
7739 // If both operands are null, they compare equal. Otherwise if only one is
7740 // null, they compare unequal.
7741 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7742 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7743 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7744 }
7745
7746 // Otherwise if either is a pointer to a virtual member function, the
7747 // result is unspecified.
7748 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7749 if (MD->isVirtual())
7750 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7751 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7752 if (MD->isVirtual())
7753 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7754
7755 // Otherwise they compare equal if and only if they would refer to the
7756 // same member of the same most derived object or the same subobject if
7757 // they were dereferenced with a hypothetical object of the associated
7758 // class type.
7759 bool Equal = LHSValue == RHSValue;
7760 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7761 }
7762
Richard Smithab44d9b2012-02-14 22:35:28 +00007763 if (LHSTy->isNullPtrType()) {
7764 assert(E->isComparisonOp() && "unexpected nullptr operation");
7765 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7766 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7767 // are compared, the result is true of the operator is <=, >= or ==, and
7768 // false otherwise.
7769 BinaryOperator::Opcode Opcode = E->getOpcode();
7770 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7771 }
7772
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007773 assert((!LHSTy->isIntegralOrEnumerationType() ||
7774 !RHSTy->isIntegralOrEnumerationType()) &&
7775 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7776 // We can't continue from here for non-integral types.
7777 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007778}
7779
Peter Collingbournee190dee2011-03-11 19:24:49 +00007780/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7781/// a result as the expression's type.
7782bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7783 const UnaryExprOrTypeTraitExpr *E) {
7784 switch(E->getKind()) {
7785 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007786 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007787 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007788 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007789 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007790 }
Eli Friedman64004332009-03-23 04:38:34 +00007791
Peter Collingbournee190dee2011-03-11 19:24:49 +00007792 case UETT_VecStep: {
7793 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007794
Peter Collingbournee190dee2011-03-11 19:24:49 +00007795 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007796 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007797
Peter Collingbournee190dee2011-03-11 19:24:49 +00007798 // The vec_step built-in functions that take a 3-component
7799 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7800 if (n == 3)
7801 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007802
Peter Collingbournee190dee2011-03-11 19:24:49 +00007803 return Success(n, E);
7804 } else
7805 return Success(1, E);
7806 }
7807
7808 case UETT_SizeOf: {
7809 QualType SrcTy = E->getTypeOfArgument();
7810 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7811 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007812 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7813 SrcTy = Ref->getPointeeType();
7814
Richard Smithd62306a2011-11-10 06:34:14 +00007815 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007816 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007817 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007818 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007819 }
Alexey Bataev00396512015-07-02 03:40:19 +00007820 case UETT_OpenMPRequiredSimdAlign:
7821 assert(E->isArgumentType());
7822 return Success(
7823 Info.Ctx.toCharUnitsFromBits(
7824 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7825 .getQuantity(),
7826 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007827 }
7828
7829 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007830}
7831
Peter Collingbournee9200682011-05-13 03:29:01 +00007832bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007833 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007834 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007835 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007836 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007837 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007838 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007839 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007840 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007841 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007842 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007843 APSInt IdxResult;
7844 if (!EvaluateInteger(Idx, IdxResult, Info))
7845 return false;
7846 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7847 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007848 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007849 CurrentType = AT->getElementType();
7850 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7851 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007852 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007853 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007854
James Y Knight7281c352015-12-29 22:31:18 +00007855 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007856 FieldDecl *MemberDecl = ON.getField();
7857 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007858 if (!RT)
7859 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007860 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007861 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007862 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007863 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007864 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007865 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007866 CurrentType = MemberDecl->getType().getNonReferenceType();
7867 break;
7868 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007869
James Y Knight7281c352015-12-29 22:31:18 +00007870 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007871 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007872
James Y Knight7281c352015-12-29 22:31:18 +00007873 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007874 CXXBaseSpecifier *BaseSpec = ON.getBase();
7875 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007876 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007877
7878 // Find the layout of the class whose base we are looking into.
7879 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007880 if (!RT)
7881 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007882 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007883 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007884 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7885
7886 // Find the base class itself.
7887 CurrentType = BaseSpec->getType();
7888 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7889 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007890 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007891
7892 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007893 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007894 break;
7895 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007896 }
7897 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007898 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007899}
7900
Chris Lattnere13042c2008-07-11 19:10:17 +00007901bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007902 switch (E->getOpcode()) {
7903 default:
7904 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7905 // See C99 6.6p3.
7906 return Error(E);
7907 case UO_Extension:
7908 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7909 // If so, we could clear the diagnostic ID.
7910 return Visit(E->getSubExpr());
7911 case UO_Plus:
7912 // The result is just the value.
7913 return Visit(E->getSubExpr());
7914 case UO_Minus: {
7915 if (!Visit(E->getSubExpr()))
7916 return false;
7917 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007918 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007919 if (Value.isSigned() && Value.isMinSignedValue() &&
7920 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7921 E->getType()))
7922 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007923 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007924 }
7925 case UO_Not: {
7926 if (!Visit(E->getSubExpr()))
7927 return false;
7928 if (!Result.isInt()) return Error(E);
7929 return Success(~Result.getInt(), E);
7930 }
7931 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007932 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007933 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007934 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007935 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007936 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007937 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007938}
Mike Stump11289f42009-09-09 15:08:12 +00007939
Chris Lattner477c4be2008-07-12 01:15:53 +00007940/// HandleCast - This is used to evaluate implicit or explicit casts where the
7941/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007942bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7943 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007944 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007945 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007946
Eli Friedmanc757de22011-03-25 00:43:55 +00007947 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007948 case CK_BaseToDerived:
7949 case CK_DerivedToBase:
7950 case CK_UncheckedDerivedToBase:
7951 case CK_Dynamic:
7952 case CK_ToUnion:
7953 case CK_ArrayToPointerDecay:
7954 case CK_FunctionToPointerDecay:
7955 case CK_NullToPointer:
7956 case CK_NullToMemberPointer:
7957 case CK_BaseToDerivedMemberPointer:
7958 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007959 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007960 case CK_ConstructorConversion:
7961 case CK_IntegralToPointer:
7962 case CK_ToVoid:
7963 case CK_VectorSplat:
7964 case CK_IntegralToFloating:
7965 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007966 case CK_CPointerToObjCPointerCast:
7967 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007968 case CK_AnyPointerToBlockPointerCast:
7969 case CK_ObjCObjectLValueCast:
7970 case CK_FloatingRealToComplex:
7971 case CK_FloatingComplexToReal:
7972 case CK_FloatingComplexCast:
7973 case CK_FloatingComplexToIntegralComplex:
7974 case CK_IntegralRealToComplex:
7975 case CK_IntegralComplexCast:
7976 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007977 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007978 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007979 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007980 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007981 llvm_unreachable("invalid cast kind for integral value");
7982
Eli Friedman9faf2f92011-03-25 19:07:11 +00007983 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007984 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007985 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007986 case CK_ARCProduceObject:
7987 case CK_ARCConsumeObject:
7988 case CK_ARCReclaimReturnedObject:
7989 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007990 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007991 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007992
Richard Smith4ef685b2012-01-17 21:17:26 +00007993 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007994 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007995 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007996 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007997 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007998
7999 case CK_MemberPointerToBoolean:
8000 case CK_PointerToBoolean:
8001 case CK_IntegralToBoolean:
8002 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008003 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008004 case CK_FloatingComplexToBoolean:
8005 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008006 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008007 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008008 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008009 uint64_t IntResult = BoolResult;
8010 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8011 IntResult = (uint64_t)-1;
8012 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008013 }
8014
Eli Friedmanc757de22011-03-25 00:43:55 +00008015 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008016 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008017 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008018
Eli Friedman742421e2009-02-20 01:15:07 +00008019 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008020 // Allow casts of address-of-label differences if they are no-ops
8021 // or narrowing. (The narrowing case isn't actually guaranteed to
8022 // be constant-evaluatable except in some narrow cases which are hard
8023 // to detect here. We let it through on the assumption the user knows
8024 // what they are doing.)
8025 if (Result.isAddrLabelDiff())
8026 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008027 // Only allow casts of lvalues if they are lossless.
8028 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8029 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008030
Richard Smith911e1422012-01-30 22:27:01 +00008031 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8032 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008033 }
Mike Stump11289f42009-09-09 15:08:12 +00008034
Eli Friedmanc757de22011-03-25 00:43:55 +00008035 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008036 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8037
John McCall45d55e42010-05-07 21:00:08 +00008038 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008039 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008040 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008041
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008042 if (LV.getLValueBase()) {
8043 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008044 // FIXME: Allow a larger integer size than the pointer size, and allow
8045 // narrowing back down to pointer width in subsequent integral casts.
8046 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008047 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008048 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008049
Richard Smithcf74da72011-11-16 07:18:12 +00008050 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008051 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008052 return true;
8053 }
8054
Ken Dyck02990832010-01-15 12:37:54 +00008055 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8056 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008057 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008058 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008059
Eli Friedmanc757de22011-03-25 00:43:55 +00008060 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008061 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008062 if (!EvaluateComplex(SubExpr, C, Info))
8063 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008064 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008065 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008066
Eli Friedmanc757de22011-03-25 00:43:55 +00008067 case CK_FloatingToIntegral: {
8068 APFloat F(0.0);
8069 if (!EvaluateFloat(SubExpr, F, Info))
8070 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008071
Richard Smith357362d2011-12-13 06:39:58 +00008072 APSInt Value;
8073 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8074 return false;
8075 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008076 }
8077 }
Mike Stump11289f42009-09-09 15:08:12 +00008078
Eli Friedmanc757de22011-03-25 00:43:55 +00008079 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008080}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008081
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008082bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8083 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008084 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008085 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8086 return false;
8087 if (!LV.isComplexInt())
8088 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008089 return Success(LV.getComplexIntReal(), E);
8090 }
8091
8092 return Visit(E->getSubExpr());
8093}
8094
Eli Friedman4e7a2412009-02-27 04:45:43 +00008095bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008096 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008097 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008098 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8099 return false;
8100 if (!LV.isComplexInt())
8101 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008102 return Success(LV.getComplexIntImag(), E);
8103 }
8104
Richard Smith4a678122011-10-24 18:44:57 +00008105 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008106 return Success(0, E);
8107}
8108
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008109bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8110 return Success(E->getPackLength(), E);
8111}
8112
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008113bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8114 return Success(E->getValue(), E);
8115}
8116
Chris Lattner05706e882008-07-11 18:11:29 +00008117//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008118// Float Evaluation
8119//===----------------------------------------------------------------------===//
8120
8121namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008122class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008123 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008124 APFloat &Result;
8125public:
8126 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008127 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008128
Richard Smith2e312c82012-03-03 22:46:17 +00008129 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008130 Result = V.getFloat();
8131 return true;
8132 }
Eli Friedman24c01542008-08-22 00:06:13 +00008133
Richard Smithfddd3842011-12-30 21:15:51 +00008134 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008135 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8136 return true;
8137 }
8138
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008139 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008140
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008141 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008142 bool VisitBinaryOperator(const BinaryOperator *E);
8143 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008144 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008145
John McCallb1fb0d32010-05-07 22:08:54 +00008146 bool VisitUnaryReal(const UnaryOperator *E);
8147 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008148
Richard Smithfddd3842011-12-30 21:15:51 +00008149 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008150};
8151} // end anonymous namespace
8152
8153static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008154 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008155 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008156}
8157
Jay Foad39c79802011-01-12 09:06:06 +00008158static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008159 QualType ResultTy,
8160 const Expr *Arg,
8161 bool SNaN,
8162 llvm::APFloat &Result) {
8163 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8164 if (!S) return false;
8165
8166 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8167
8168 llvm::APInt fill;
8169
8170 // Treat empty strings as if they were zero.
8171 if (S->getString().empty())
8172 fill = llvm::APInt(32, 0);
8173 else if (S->getString().getAsInteger(0, fill))
8174 return false;
8175
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008176 if (Context.getTargetInfo().isNan2008()) {
8177 if (SNaN)
8178 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8179 else
8180 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8181 } else {
8182 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8183 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8184 // a different encoding to what became a standard in 2008, and for pre-
8185 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8186 // sNaN. This is now known as "legacy NaN" encoding.
8187 if (SNaN)
8188 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8189 else
8190 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8191 }
8192
John McCall16291492010-02-28 13:00:19 +00008193 return true;
8194}
8195
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008196bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008197 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008198 default:
8199 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8200
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008201 case Builtin::BI__builtin_huge_val:
8202 case Builtin::BI__builtin_huge_valf:
8203 case Builtin::BI__builtin_huge_vall:
8204 case Builtin::BI__builtin_inf:
8205 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008206 case Builtin::BI__builtin_infl: {
8207 const llvm::fltSemantics &Sem =
8208 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008209 Result = llvm::APFloat::getInf(Sem);
8210 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008211 }
Mike Stump11289f42009-09-09 15:08:12 +00008212
John McCall16291492010-02-28 13:00:19 +00008213 case Builtin::BI__builtin_nans:
8214 case Builtin::BI__builtin_nansf:
8215 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008216 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8217 true, Result))
8218 return Error(E);
8219 return true;
John McCall16291492010-02-28 13:00:19 +00008220
Chris Lattner0b7282e2008-10-06 06:31:58 +00008221 case Builtin::BI__builtin_nan:
8222 case Builtin::BI__builtin_nanf:
8223 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008224 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008225 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008226 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8227 false, Result))
8228 return Error(E);
8229 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008230
8231 case Builtin::BI__builtin_fabs:
8232 case Builtin::BI__builtin_fabsf:
8233 case Builtin::BI__builtin_fabsl:
8234 if (!EvaluateFloat(E->getArg(0), Result, Info))
8235 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008236
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008237 if (Result.isNegative())
8238 Result.changeSign();
8239 return true;
8240
Richard Smith8889a3d2013-06-13 06:26:32 +00008241 // FIXME: Builtin::BI__builtin_powi
8242 // FIXME: Builtin::BI__builtin_powif
8243 // FIXME: Builtin::BI__builtin_powil
8244
Mike Stump11289f42009-09-09 15:08:12 +00008245 case Builtin::BI__builtin_copysign:
8246 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008247 case Builtin::BI__builtin_copysignl: {
8248 APFloat RHS(0.);
8249 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8250 !EvaluateFloat(E->getArg(1), RHS, Info))
8251 return false;
8252 Result.copySign(RHS);
8253 return true;
8254 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008255 }
8256}
8257
John McCallb1fb0d32010-05-07 22:08:54 +00008258bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008259 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8260 ComplexValue CV;
8261 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8262 return false;
8263 Result = CV.FloatReal;
8264 return true;
8265 }
8266
8267 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008268}
8269
8270bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008271 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8272 ComplexValue CV;
8273 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8274 return false;
8275 Result = CV.FloatImag;
8276 return true;
8277 }
8278
Richard Smith4a678122011-10-24 18:44:57 +00008279 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008280 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8281 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008282 return true;
8283}
8284
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008285bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008286 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008287 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008288 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008289 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008290 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008291 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8292 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008293 Result.changeSign();
8294 return true;
8295 }
8296}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008297
Eli Friedman24c01542008-08-22 00:06:13 +00008298bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008299 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8300 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008301
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008302 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008303 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008304 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008305 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008306 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8307 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008308}
8309
8310bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8311 Result = E->getValue();
8312 return true;
8313}
8314
Peter Collingbournee9200682011-05-13 03:29:01 +00008315bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8316 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008317
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008318 switch (E->getCastKind()) {
8319 default:
Richard Smith11562c52011-10-28 17:51:58 +00008320 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008321
8322 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008323 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008324 return EvaluateInteger(SubExpr, IntResult, Info) &&
8325 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8326 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008327 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008328
8329 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008330 if (!Visit(SubExpr))
8331 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008332 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8333 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008334 }
John McCalld7646252010-11-14 08:17:51 +00008335
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008336 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008337 ComplexValue V;
8338 if (!EvaluateComplex(SubExpr, V, Info))
8339 return false;
8340 Result = V.getComplexFloatReal();
8341 return true;
8342 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008343 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008344}
8345
Eli Friedman24c01542008-08-22 00:06:13 +00008346//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008347// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008348//===----------------------------------------------------------------------===//
8349
8350namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008351class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008352 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008353 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008354
Anders Carlsson537969c2008-11-16 20:27:53 +00008355public:
John McCall93d91dc2010-05-07 17:22:02 +00008356 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008357 : ExprEvaluatorBaseTy(info), Result(Result) {}
8358
Richard Smith2e312c82012-03-03 22:46:17 +00008359 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008360 Result.setFrom(V);
8361 return true;
8362 }
Mike Stump11289f42009-09-09 15:08:12 +00008363
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008364 bool ZeroInitialization(const Expr *E);
8365
Anders Carlsson537969c2008-11-16 20:27:53 +00008366 //===--------------------------------------------------------------------===//
8367 // Visitor Methods
8368 //===--------------------------------------------------------------------===//
8369
Peter Collingbournee9200682011-05-13 03:29:01 +00008370 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008371 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008372 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008373 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008374 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008375};
8376} // end anonymous namespace
8377
John McCall93d91dc2010-05-07 17:22:02 +00008378static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8379 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008380 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008381 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008382}
8383
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008384bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008385 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008386 if (ElemTy->isRealFloatingType()) {
8387 Result.makeComplexFloat();
8388 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8389 Result.FloatReal = Zero;
8390 Result.FloatImag = Zero;
8391 } else {
8392 Result.makeComplexInt();
8393 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8394 Result.IntReal = Zero;
8395 Result.IntImag = Zero;
8396 }
8397 return true;
8398}
8399
Peter Collingbournee9200682011-05-13 03:29:01 +00008400bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8401 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008402
8403 if (SubExpr->getType()->isRealFloatingType()) {
8404 Result.makeComplexFloat();
8405 APFloat &Imag = Result.FloatImag;
8406 if (!EvaluateFloat(SubExpr, Imag, Info))
8407 return false;
8408
8409 Result.FloatReal = APFloat(Imag.getSemantics());
8410 return true;
8411 } else {
8412 assert(SubExpr->getType()->isIntegerType() &&
8413 "Unexpected imaginary literal.");
8414
8415 Result.makeComplexInt();
8416 APSInt &Imag = Result.IntImag;
8417 if (!EvaluateInteger(SubExpr, Imag, Info))
8418 return false;
8419
8420 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8421 return true;
8422 }
8423}
8424
Peter Collingbournee9200682011-05-13 03:29:01 +00008425bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008426
John McCallfcef3cf2010-12-14 17:51:41 +00008427 switch (E->getCastKind()) {
8428 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008429 case CK_BaseToDerived:
8430 case CK_DerivedToBase:
8431 case CK_UncheckedDerivedToBase:
8432 case CK_Dynamic:
8433 case CK_ToUnion:
8434 case CK_ArrayToPointerDecay:
8435 case CK_FunctionToPointerDecay:
8436 case CK_NullToPointer:
8437 case CK_NullToMemberPointer:
8438 case CK_BaseToDerivedMemberPointer:
8439 case CK_DerivedToBaseMemberPointer:
8440 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008441 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008442 case CK_ConstructorConversion:
8443 case CK_IntegralToPointer:
8444 case CK_PointerToIntegral:
8445 case CK_PointerToBoolean:
8446 case CK_ToVoid:
8447 case CK_VectorSplat:
8448 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008449 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008450 case CK_IntegralToBoolean:
8451 case CK_IntegralToFloating:
8452 case CK_FloatingToIntegral:
8453 case CK_FloatingToBoolean:
8454 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008455 case CK_CPointerToObjCPointerCast:
8456 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008457 case CK_AnyPointerToBlockPointerCast:
8458 case CK_ObjCObjectLValueCast:
8459 case CK_FloatingComplexToReal:
8460 case CK_FloatingComplexToBoolean:
8461 case CK_IntegralComplexToReal:
8462 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008463 case CK_ARCProduceObject:
8464 case CK_ARCConsumeObject:
8465 case CK_ARCReclaimReturnedObject:
8466 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008467 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008468 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008469 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008470 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008471 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008472 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008473
John McCallfcef3cf2010-12-14 17:51:41 +00008474 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008475 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008476 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008477 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008478
8479 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008480 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008481 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008482 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008483
8484 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008485 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008486 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008487 return false;
8488
John McCallfcef3cf2010-12-14 17:51:41 +00008489 Result.makeComplexFloat();
8490 Result.FloatImag = APFloat(Real.getSemantics());
8491 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008492 }
8493
John McCallfcef3cf2010-12-14 17:51:41 +00008494 case CK_FloatingComplexCast: {
8495 if (!Visit(E->getSubExpr()))
8496 return false;
8497
8498 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8499 QualType From
8500 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8501
Richard Smith357362d2011-12-13 06:39:58 +00008502 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8503 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008504 }
8505
8506 case CK_FloatingComplexToIntegralComplex: {
8507 if (!Visit(E->getSubExpr()))
8508 return false;
8509
8510 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8511 QualType From
8512 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8513 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008514 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8515 To, Result.IntReal) &&
8516 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8517 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008518 }
8519
8520 case CK_IntegralRealToComplex: {
8521 APSInt &Real = Result.IntReal;
8522 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8523 return false;
8524
8525 Result.makeComplexInt();
8526 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8527 return true;
8528 }
8529
8530 case CK_IntegralComplexCast: {
8531 if (!Visit(E->getSubExpr()))
8532 return false;
8533
8534 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8535 QualType From
8536 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8537
Richard Smith911e1422012-01-30 22:27:01 +00008538 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8539 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008540 return true;
8541 }
8542
8543 case CK_IntegralComplexToFloatingComplex: {
8544 if (!Visit(E->getSubExpr()))
8545 return false;
8546
Ted Kremenek28831752012-08-23 20:46:57 +00008547 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008548 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008549 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008550 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008551 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8552 To, Result.FloatReal) &&
8553 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8554 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008555 }
8556 }
8557
8558 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008559}
8560
John McCall93d91dc2010-05-07 17:22:02 +00008561bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008562 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008563 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8564
Chandler Carrutha216cad2014-10-11 00:57:18 +00008565 // Track whether the LHS or RHS is real at the type system level. When this is
8566 // the case we can simplify our evaluation strategy.
8567 bool LHSReal = false, RHSReal = false;
8568
8569 bool LHSOK;
8570 if (E->getLHS()->getType()->isRealFloatingType()) {
8571 LHSReal = true;
8572 APFloat &Real = Result.FloatReal;
8573 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8574 if (LHSOK) {
8575 Result.makeComplexFloat();
8576 Result.FloatImag = APFloat(Real.getSemantics());
8577 }
8578 } else {
8579 LHSOK = Visit(E->getLHS());
8580 }
George Burgess IVa145e252016-05-25 22:38:36 +00008581 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008582 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008583
John McCall93d91dc2010-05-07 17:22:02 +00008584 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008585 if (E->getRHS()->getType()->isRealFloatingType()) {
8586 RHSReal = true;
8587 APFloat &Real = RHS.FloatReal;
8588 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8589 return false;
8590 RHS.makeComplexFloat();
8591 RHS.FloatImag = APFloat(Real.getSemantics());
8592 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008593 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008594
Chandler Carrutha216cad2014-10-11 00:57:18 +00008595 assert(!(LHSReal && RHSReal) &&
8596 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008597 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008598 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008599 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008600 if (Result.isComplexFloat()) {
8601 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8602 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008603 if (LHSReal)
8604 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8605 else if (!RHSReal)
8606 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8607 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008608 } else {
8609 Result.getComplexIntReal() += RHS.getComplexIntReal();
8610 Result.getComplexIntImag() += RHS.getComplexIntImag();
8611 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008612 break;
John McCalle3027922010-08-25 11:45:40 +00008613 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008614 if (Result.isComplexFloat()) {
8615 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8616 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008617 if (LHSReal) {
8618 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8619 Result.getComplexFloatImag().changeSign();
8620 } else if (!RHSReal) {
8621 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8622 APFloat::rmNearestTiesToEven);
8623 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008624 } else {
8625 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8626 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8627 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008628 break;
John McCalle3027922010-08-25 11:45:40 +00008629 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008630 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008631 // This is an implementation of complex multiplication according to the
8632 // constraints laid out in C11 Annex G. The implemantion uses the
8633 // following naming scheme:
8634 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008635 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008636 APFloat &A = LHS.getComplexFloatReal();
8637 APFloat &B = LHS.getComplexFloatImag();
8638 APFloat &C = RHS.getComplexFloatReal();
8639 APFloat &D = RHS.getComplexFloatImag();
8640 APFloat &ResR = Result.getComplexFloatReal();
8641 APFloat &ResI = Result.getComplexFloatImag();
8642 if (LHSReal) {
8643 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8644 ResR = A * C;
8645 ResI = A * D;
8646 } else if (RHSReal) {
8647 ResR = C * A;
8648 ResI = C * B;
8649 } else {
8650 // In the fully general case, we need to handle NaNs and infinities
8651 // robustly.
8652 APFloat AC = A * C;
8653 APFloat BD = B * D;
8654 APFloat AD = A * D;
8655 APFloat BC = B * C;
8656 ResR = AC - BD;
8657 ResI = AD + BC;
8658 if (ResR.isNaN() && ResI.isNaN()) {
8659 bool Recalc = false;
8660 if (A.isInfinity() || B.isInfinity()) {
8661 A = APFloat::copySign(
8662 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8663 B = APFloat::copySign(
8664 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8665 if (C.isNaN())
8666 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8667 if (D.isNaN())
8668 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8669 Recalc = true;
8670 }
8671 if (C.isInfinity() || D.isInfinity()) {
8672 C = APFloat::copySign(
8673 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8674 D = APFloat::copySign(
8675 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8676 if (A.isNaN())
8677 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8678 if (B.isNaN())
8679 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8680 Recalc = true;
8681 }
8682 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8683 AD.isInfinity() || BC.isInfinity())) {
8684 if (A.isNaN())
8685 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8686 if (B.isNaN())
8687 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8688 if (C.isNaN())
8689 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8690 if (D.isNaN())
8691 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8692 Recalc = true;
8693 }
8694 if (Recalc) {
8695 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8696 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8697 }
8698 }
8699 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008700 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008701 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008702 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008703 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8704 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008705 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008706 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8707 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8708 }
8709 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008710 case BO_Div:
8711 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008712 // This is an implementation of complex division according to the
8713 // constraints laid out in C11 Annex G. The implemantion uses the
8714 // following naming scheme:
8715 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008716 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008717 APFloat &A = LHS.getComplexFloatReal();
8718 APFloat &B = LHS.getComplexFloatImag();
8719 APFloat &C = RHS.getComplexFloatReal();
8720 APFloat &D = RHS.getComplexFloatImag();
8721 APFloat &ResR = Result.getComplexFloatReal();
8722 APFloat &ResI = Result.getComplexFloatImag();
8723 if (RHSReal) {
8724 ResR = A / C;
8725 ResI = B / C;
8726 } else {
8727 if (LHSReal) {
8728 // No real optimizations we can do here, stub out with zero.
8729 B = APFloat::getZero(A.getSemantics());
8730 }
8731 int DenomLogB = 0;
8732 APFloat MaxCD = maxnum(abs(C), abs(D));
8733 if (MaxCD.isFinite()) {
8734 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008735 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8736 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008737 }
8738 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008739 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8740 APFloat::rmNearestTiesToEven);
8741 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8742 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008743 if (ResR.isNaN() && ResI.isNaN()) {
8744 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8745 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8746 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8747 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8748 D.isFinite()) {
8749 A = APFloat::copySign(
8750 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8751 B = APFloat::copySign(
8752 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8753 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8754 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8755 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8756 C = APFloat::copySign(
8757 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8758 D = APFloat::copySign(
8759 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8760 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8761 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8762 }
8763 }
8764 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008765 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8767 return Error(E, diag::note_expr_divide_by_zero);
8768
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008769 ComplexValue LHS = Result;
8770 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8771 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8772 Result.getComplexIntReal() =
8773 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8774 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8775 Result.getComplexIntImag() =
8776 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8777 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8778 }
8779 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008780 }
8781
John McCall93d91dc2010-05-07 17:22:02 +00008782 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008783}
8784
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008785bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8786 // Get the operand value into 'Result'.
8787 if (!Visit(E->getSubExpr()))
8788 return false;
8789
8790 switch (E->getOpcode()) {
8791 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008792 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008793 case UO_Extension:
8794 return true;
8795 case UO_Plus:
8796 // The result is always just the subexpr.
8797 return true;
8798 case UO_Minus:
8799 if (Result.isComplexFloat()) {
8800 Result.getComplexFloatReal().changeSign();
8801 Result.getComplexFloatImag().changeSign();
8802 }
8803 else {
8804 Result.getComplexIntReal() = -Result.getComplexIntReal();
8805 Result.getComplexIntImag() = -Result.getComplexIntImag();
8806 }
8807 return true;
8808 case UO_Not:
8809 if (Result.isComplexFloat())
8810 Result.getComplexFloatImag().changeSign();
8811 else
8812 Result.getComplexIntImag() = -Result.getComplexIntImag();
8813 return true;
8814 }
8815}
8816
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008817bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8818 if (E->getNumInits() == 2) {
8819 if (E->getType()->isComplexType()) {
8820 Result.makeComplexFloat();
8821 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8822 return false;
8823 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8824 return false;
8825 } else {
8826 Result.makeComplexInt();
8827 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8828 return false;
8829 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8830 return false;
8831 }
8832 return true;
8833 }
8834 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8835}
8836
Anders Carlsson537969c2008-11-16 20:27:53 +00008837//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008838// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8839// implicit conversion.
8840//===----------------------------------------------------------------------===//
8841
8842namespace {
8843class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008844 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008845 APValue &Result;
8846public:
8847 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8848 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8849
8850 bool Success(const APValue &V, const Expr *E) {
8851 Result = V;
8852 return true;
8853 }
8854
8855 bool ZeroInitialization(const Expr *E) {
8856 ImplicitValueInitExpr VIE(
8857 E->getType()->castAs<AtomicType>()->getValueType());
8858 return Evaluate(Result, Info, &VIE);
8859 }
8860
8861 bool VisitCastExpr(const CastExpr *E) {
8862 switch (E->getCastKind()) {
8863 default:
8864 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8865 case CK_NonAtomicToAtomic:
8866 return Evaluate(Result, Info, E->getSubExpr());
8867 }
8868 }
8869};
8870} // end anonymous namespace
8871
8872static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8873 assert(E->isRValue() && E->getType()->isAtomicType());
8874 return AtomicExprEvaluator(Info, Result).Visit(E);
8875}
8876
8877//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008878// Void expression evaluation, primarily for a cast to void on the LHS of a
8879// comma operator
8880//===----------------------------------------------------------------------===//
8881
8882namespace {
8883class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008884 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008885public:
8886 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8887
Richard Smith2e312c82012-03-03 22:46:17 +00008888 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008889
8890 bool VisitCastExpr(const CastExpr *E) {
8891 switch (E->getCastKind()) {
8892 default:
8893 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8894 case CK_ToVoid:
8895 VisitIgnoredValue(E->getSubExpr());
8896 return true;
8897 }
8898 }
Hal Finkela8443c32014-07-17 14:49:58 +00008899
8900 bool VisitCallExpr(const CallExpr *E) {
8901 switch (E->getBuiltinCallee()) {
8902 default:
8903 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8904 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008905 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008906 // The argument is not evaluated!
8907 return true;
8908 }
8909 }
Richard Smith42d3af92011-12-07 00:43:50 +00008910};
8911} // end anonymous namespace
8912
8913static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8914 assert(E->isRValue() && E->getType()->isVoidType());
8915 return VoidExprEvaluator(Info).Visit(E);
8916}
8917
8918//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008919// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008920//===----------------------------------------------------------------------===//
8921
Richard Smith2e312c82012-03-03 22:46:17 +00008922static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008923 // In C, function designators are not lvalues, but we evaluate them as if they
8924 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008925 QualType T = E->getType();
8926 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008927 LValue LV;
8928 if (!EvaluateLValue(E, LV, Info))
8929 return false;
8930 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008931 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008932 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008933 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008934 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008935 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008936 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008937 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008938 LValue LV;
8939 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008940 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008941 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008942 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008943 llvm::APFloat F(0.0);
8944 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008945 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008946 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008947 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008948 ComplexValue C;
8949 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008950 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008951 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008952 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008953 MemberPtr P;
8954 if (!EvaluateMemberPointer(E, P, Info))
8955 return false;
8956 P.moveInto(Result);
8957 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008958 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008959 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008960 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008961 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8962 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008963 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008964 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008965 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008966 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008967 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008968 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8969 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008970 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008971 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008972 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008973 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008974 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008975 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008976 if (!EvaluateVoid(E, Info))
8977 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008978 } else if (T->isAtomicType()) {
8979 if (!EvaluateAtomic(E, Result, Info))
8980 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008981 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008982 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008983 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008984 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008985 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008986 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008987 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008988
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008989 return true;
8990}
8991
Richard Smithb228a862012-02-15 02:18:13 +00008992/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8993/// cases, the in-place evaluation is essential, since later initializers for
8994/// an object can indirectly refer to subobjects which were initialized earlier.
8995static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008996 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008997 assert(!E->isValueDependent());
8998
Richard Smith7525ff62013-05-09 07:14:00 +00008999 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009000 return false;
9001
9002 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009003 // Evaluate arrays and record types in-place, so that later initializers can
9004 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009005 if (E->getType()->isArrayType())
9006 return EvaluateArray(E, This, Result, Info);
9007 else if (E->getType()->isRecordType())
9008 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009009 }
9010
9011 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009012 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009013}
9014
Richard Smithf57d8cb2011-12-09 22:58:01 +00009015/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9016/// lvalue-to-rvalue cast if it is an lvalue.
9017static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009018 if (E->getType().isNull())
9019 return false;
9020
Richard Smithfddd3842011-12-30 21:15:51 +00009021 if (!CheckLiteralType(Info, E))
9022 return false;
9023
Richard Smith2e312c82012-03-03 22:46:17 +00009024 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009025 return false;
9026
9027 if (E->isGLValue()) {
9028 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009029 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009030 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009031 return false;
9032 }
9033
Richard Smith2e312c82012-03-03 22:46:17 +00009034 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009035 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009036}
Richard Smith11562c52011-10-28 17:51:58 +00009037
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009038static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9039 const ASTContext &Ctx, bool &IsConst) {
9040 // Fast-path evaluations of integer literals, since we sometimes see files
9041 // containing vast quantities of these.
9042 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9043 Result.Val = APValue(APSInt(L->getValue(),
9044 L->getType()->isUnsignedIntegerType()));
9045 IsConst = true;
9046 return true;
9047 }
James Dennett0492ef02014-03-14 17:44:10 +00009048
9049 // This case should be rare, but we need to check it before we check on
9050 // the type below.
9051 if (Exp->getType().isNull()) {
9052 IsConst = false;
9053 return true;
9054 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009055
9056 // FIXME: Evaluating values of large array and record types can cause
9057 // performance problems. Only do so in C++11 for now.
9058 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9059 Exp->getType()->isRecordType()) &&
9060 !Ctx.getLangOpts().CPlusPlus11) {
9061 IsConst = false;
9062 return true;
9063 }
9064 return false;
9065}
9066
9067
Richard Smith7b553f12011-10-29 00:50:52 +00009068/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009069/// any crazy technique (that has nothing to do with language standards) that
9070/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009071/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9072/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009073bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009074 bool IsConst;
9075 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9076 return IsConst;
9077
Richard Smith6d4c6582013-11-05 22:18:15 +00009078 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009079 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009080}
9081
Jay Foad39c79802011-01-12 09:06:06 +00009082bool Expr::EvaluateAsBooleanCondition(bool &Result,
9083 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009084 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009085 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009086 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009087}
9088
Richard Smithce8eca52015-12-08 03:21:47 +00009089static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9090 Expr::SideEffectsKind SEK) {
9091 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9092 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9093}
9094
Richard Smith5fab0c92011-12-28 19:48:30 +00009095bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9096 SideEffectsKind AllowSideEffects) const {
9097 if (!getType()->isIntegralOrEnumerationType())
9098 return false;
9099
Richard Smith11562c52011-10-28 17:51:58 +00009100 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009101 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009102 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009103 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009104
Richard Smith11562c52011-10-28 17:51:58 +00009105 Result = ExprResult.Val.getInt();
9106 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009107}
9108
Richard Trieube234c32016-04-21 21:04:55 +00009109bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9110 SideEffectsKind AllowSideEffects) const {
9111 if (!getType()->isRealFloatingType())
9112 return false;
9113
9114 EvalResult ExprResult;
9115 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9116 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9117 return false;
9118
9119 Result = ExprResult.Val.getFloat();
9120 return true;
9121}
9122
Jay Foad39c79802011-01-12 09:06:06 +00009123bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009124 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009125
John McCall45d55e42010-05-07 21:00:08 +00009126 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009127 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9128 !CheckLValueConstantExpression(Info, getExprLoc(),
9129 Ctx.getLValueReferenceType(getType()), LV))
9130 return false;
9131
Richard Smith2e312c82012-03-03 22:46:17 +00009132 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009133 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009134}
9135
Richard Smithd0b4dd62011-12-19 06:19:21 +00009136bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9137 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009138 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009139 // FIXME: Evaluating initializers for large array and record types can cause
9140 // performance problems. Only do so in C++11 for now.
9141 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009142 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009143 return false;
9144
Richard Smithd0b4dd62011-12-19 06:19:21 +00009145 Expr::EvalStatus EStatus;
9146 EStatus.Diag = &Notes;
9147
Richard Smith0c6124b2015-12-03 01:36:22 +00009148 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9149 ? EvalInfo::EM_ConstantExpression
9150 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009151 InitInfo.setEvaluatingDecl(VD, Value);
9152
9153 LValue LVal;
9154 LVal.set(VD);
9155
Richard Smithfddd3842011-12-30 21:15:51 +00009156 // C++11 [basic.start.init]p2:
9157 // Variables with static storage duration or thread storage duration shall be
9158 // zero-initialized before any other initialization takes place.
9159 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009160 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009161 !VD->getType()->isReferenceType()) {
9162 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009163 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009164 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009165 return false;
9166 }
9167
Richard Smith7525ff62013-05-09 07:14:00 +00009168 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9169 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009170 EStatus.HasSideEffects)
9171 return false;
9172
9173 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9174 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009175}
9176
Richard Smith7b553f12011-10-29 00:50:52 +00009177/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9178/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009179bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009180 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009181 return EvaluateAsRValue(Result, Ctx) &&
9182 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009183}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009184
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009185APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009186 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009187 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009188 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009189 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009190 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009191 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009192 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009193
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009194 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009195}
John McCall864e3962010-05-07 05:32:02 +00009196
Richard Smithe9ff7702013-11-05 22:23:30 +00009197void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009198 bool IsConst;
9199 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009200 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009201 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009202 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9203 }
9204}
9205
Richard Smithe6c01442013-06-05 00:46:14 +00009206bool Expr::EvalResult::isGlobalLValue() const {
9207 assert(Val.isLValue());
9208 return IsGlobalLValue(Val.getLValueBase());
9209}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009210
9211
John McCall864e3962010-05-07 05:32:02 +00009212/// isIntegerConstantExpr - this recursive routine will test if an expression is
9213/// an integer constant expression.
9214
9215/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9216/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009217
9218// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009219// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9220// and a (possibly null) SourceLocation indicating the location of the problem.
9221//
John McCall864e3962010-05-07 05:32:02 +00009222// Note that to reduce code duplication, this helper does no evaluation
9223// itself; the caller checks whether the expression is evaluatable, and
9224// in the rare cases where CheckICE actually cares about the evaluated
9225// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009226
Dan Gohman28ade552010-07-26 21:25:24 +00009227namespace {
9228
Richard Smith9e575da2012-12-28 13:25:52 +00009229enum ICEKind {
9230 /// This expression is an ICE.
9231 IK_ICE,
9232 /// This expression is not an ICE, but if it isn't evaluated, it's
9233 /// a legal subexpression for an ICE. This return value is used to handle
9234 /// the comma operator in C99 mode, and non-constant subexpressions.
9235 IK_ICEIfUnevaluated,
9236 /// This expression is not an ICE, and is not a legal subexpression for one.
9237 IK_NotICE
9238};
9239
John McCall864e3962010-05-07 05:32:02 +00009240struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009241 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009242 SourceLocation Loc;
9243
Richard Smith9e575da2012-12-28 13:25:52 +00009244 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009245};
9246
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009247}
Dan Gohman28ade552010-07-26 21:25:24 +00009248
Richard Smith9e575da2012-12-28 13:25:52 +00009249static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9250
9251static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009252
Craig Toppera31a8822013-08-22 07:09:37 +00009253static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009254 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009255 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009256 !EVResult.Val.isInt())
9257 return ICEDiag(IK_NotICE, E->getLocStart());
9258
John McCall864e3962010-05-07 05:32:02 +00009259 return NoDiag();
9260}
9261
Craig Toppera31a8822013-08-22 07:09:37 +00009262static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009263 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009264 if (!E->getType()->isIntegralOrEnumerationType())
9265 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009266
9267 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009268#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009269#define STMT(Node, Base) case Expr::Node##Class:
9270#define EXPR(Node, Base)
9271#include "clang/AST/StmtNodes.inc"
9272 case Expr::PredefinedExprClass:
9273 case Expr::FloatingLiteralClass:
9274 case Expr::ImaginaryLiteralClass:
9275 case Expr::StringLiteralClass:
9276 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009277 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009278 case Expr::MemberExprClass:
9279 case Expr::CompoundAssignOperatorClass:
9280 case Expr::CompoundLiteralExprClass:
9281 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009282 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009283 case Expr::NoInitExprClass:
9284 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009285 case Expr::ImplicitValueInitExprClass:
9286 case Expr::ParenListExprClass:
9287 case Expr::VAArgExprClass:
9288 case Expr::AddrLabelExprClass:
9289 case Expr::StmtExprClass:
9290 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009291 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009292 case Expr::CXXDynamicCastExprClass:
9293 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009294 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009295 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009296 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009297 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009298 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009299 case Expr::CXXThisExprClass:
9300 case Expr::CXXThrowExprClass:
9301 case Expr::CXXNewExprClass:
9302 case Expr::CXXDeleteExprClass:
9303 case Expr::CXXPseudoDestructorExprClass:
9304 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009305 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009306 case Expr::DependentScopeDeclRefExprClass:
9307 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009308 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009309 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009310 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009311 case Expr::CXXTemporaryObjectExprClass:
9312 case Expr::CXXUnresolvedConstructExprClass:
9313 case Expr::CXXDependentScopeMemberExprClass:
9314 case Expr::UnresolvedMemberExprClass:
9315 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009316 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009317 case Expr::ObjCArrayLiteralClass:
9318 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009319 case Expr::ObjCEncodeExprClass:
9320 case Expr::ObjCMessageExprClass:
9321 case Expr::ObjCSelectorExprClass:
9322 case Expr::ObjCProtocolExprClass:
9323 case Expr::ObjCIvarRefExprClass:
9324 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009325 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009326 case Expr::ObjCIsaExprClass:
9327 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009328 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009329 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009330 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009331 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009332 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009333 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009334 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009335 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009336 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009337 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009338 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009339 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009340 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009341 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009342 case Expr::CoawaitExprClass:
9343 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009344 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009345
Richard Smithf137f932014-01-25 20:50:08 +00009346 case Expr::InitListExprClass: {
9347 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9348 // form "T x = { a };" is equivalent to "T x = a;".
9349 // Unless we're initializing a reference, T is a scalar as it is known to be
9350 // of integral or enumeration type.
9351 if (E->isRValue())
9352 if (cast<InitListExpr>(E)->getNumInits() == 1)
9353 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9354 return ICEDiag(IK_NotICE, E->getLocStart());
9355 }
9356
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009357 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009358 case Expr::GNUNullExprClass:
9359 // GCC considers the GNU __null value to be an integral constant expression.
9360 return NoDiag();
9361
John McCall7c454bb2011-07-15 05:09:51 +00009362 case Expr::SubstNonTypeTemplateParmExprClass:
9363 return
9364 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9365
John McCall864e3962010-05-07 05:32:02 +00009366 case Expr::ParenExprClass:
9367 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009368 case Expr::GenericSelectionExprClass:
9369 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009370 case Expr::IntegerLiteralClass:
9371 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009372 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009373 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009374 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009375 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009376 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009377 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009378 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009379 return NoDiag();
9380 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009381 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009382 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9383 // constant expressions, but they can never be ICEs because an ICE cannot
9384 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009385 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009386 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009387 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009388 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009389 }
Richard Smith6365c912012-02-24 22:12:32 +00009390 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009391 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9392 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009393 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009394 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009395 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009396 // Parameter variables are never constants. Without this check,
9397 // getAnyInitializer() can find a default argument, which leads
9398 // to chaos.
9399 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009400 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009401
9402 // C++ 7.1.5.1p2
9403 // A variable of non-volatile const-qualified integral or enumeration
9404 // type initialized by an ICE can be used in ICEs.
9405 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009406 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009407 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009408
Richard Smithd0b4dd62011-12-19 06:19:21 +00009409 const VarDecl *VD;
9410 // Look for a declaration of this variable that has an initializer, and
9411 // check whether it is an ICE.
9412 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9413 return NoDiag();
9414 else
Richard Smith9e575da2012-12-28 13:25:52 +00009415 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009416 }
9417 }
Richard Smith9e575da2012-12-28 13:25:52 +00009418 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009419 }
John McCall864e3962010-05-07 05:32:02 +00009420 case Expr::UnaryOperatorClass: {
9421 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9422 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009423 case UO_PostInc:
9424 case UO_PostDec:
9425 case UO_PreInc:
9426 case UO_PreDec:
9427 case UO_AddrOf:
9428 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009429 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009430 // C99 6.6/3 allows increment and decrement within unevaluated
9431 // subexpressions of constant expressions, but they can never be ICEs
9432 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009433 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009434 case UO_Extension:
9435 case UO_LNot:
9436 case UO_Plus:
9437 case UO_Minus:
9438 case UO_Not:
9439 case UO_Real:
9440 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009441 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009442 }
Richard Smith9e575da2012-12-28 13:25:52 +00009443
John McCall864e3962010-05-07 05:32:02 +00009444 // OffsetOf falls through here.
9445 }
9446 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009447 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9448 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9449 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9450 // compliance: we should warn earlier for offsetof expressions with
9451 // array subscripts that aren't ICEs, and if the array subscripts
9452 // are ICEs, the value of the offsetof must be an integer constant.
9453 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009454 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009455 case Expr::UnaryExprOrTypeTraitExprClass: {
9456 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9457 if ((Exp->getKind() == UETT_SizeOf) &&
9458 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009459 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009460 return NoDiag();
9461 }
9462 case Expr::BinaryOperatorClass: {
9463 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9464 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009465 case BO_PtrMemD:
9466 case BO_PtrMemI:
9467 case BO_Assign:
9468 case BO_MulAssign:
9469 case BO_DivAssign:
9470 case BO_RemAssign:
9471 case BO_AddAssign:
9472 case BO_SubAssign:
9473 case BO_ShlAssign:
9474 case BO_ShrAssign:
9475 case BO_AndAssign:
9476 case BO_XorAssign:
9477 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009478 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9479 // constant expressions, but they can never be ICEs because an ICE cannot
9480 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009481 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009482
John McCalle3027922010-08-25 11:45:40 +00009483 case BO_Mul:
9484 case BO_Div:
9485 case BO_Rem:
9486 case BO_Add:
9487 case BO_Sub:
9488 case BO_Shl:
9489 case BO_Shr:
9490 case BO_LT:
9491 case BO_GT:
9492 case BO_LE:
9493 case BO_GE:
9494 case BO_EQ:
9495 case BO_NE:
9496 case BO_And:
9497 case BO_Xor:
9498 case BO_Or:
9499 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009500 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9501 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009502 if (Exp->getOpcode() == BO_Div ||
9503 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009504 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009505 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009506 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009507 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009508 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009509 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009510 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009511 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009512 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009513 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009514 }
9515 }
9516 }
John McCalle3027922010-08-25 11:45:40 +00009517 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009518 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009519 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9520 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009521 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9522 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009523 } else {
9524 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009525 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009526 }
9527 }
Richard Smith9e575da2012-12-28 13:25:52 +00009528 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009529 }
John McCalle3027922010-08-25 11:45:40 +00009530 case BO_LAnd:
9531 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009532 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9533 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009534 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009535 // Rare case where the RHS has a comma "side-effect"; we need
9536 // to actually check the condition to see whether the side
9537 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009538 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009539 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009540 return RHSResult;
9541 return NoDiag();
9542 }
9543
Richard Smith9e575da2012-12-28 13:25:52 +00009544 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009545 }
9546 }
9547 }
9548 case Expr::ImplicitCastExprClass:
9549 case Expr::CStyleCastExprClass:
9550 case Expr::CXXFunctionalCastExprClass:
9551 case Expr::CXXStaticCastExprClass:
9552 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009553 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009554 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009555 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009556 if (isa<ExplicitCastExpr>(E)) {
9557 if (const FloatingLiteral *FL
9558 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9559 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9560 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9561 APSInt IgnoredVal(DestWidth, !DestSigned);
9562 bool Ignored;
9563 // If the value does not fit in the destination type, the behavior is
9564 // undefined, so we are not required to treat it as a constant
9565 // expression.
9566 if (FL->getValue().convertToInteger(IgnoredVal,
9567 llvm::APFloat::rmTowardZero,
9568 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009569 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009570 return NoDiag();
9571 }
9572 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009573 switch (cast<CastExpr>(E)->getCastKind()) {
9574 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009575 case CK_AtomicToNonAtomic:
9576 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009577 case CK_NoOp:
9578 case CK_IntegralToBoolean:
9579 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009580 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009581 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009582 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009583 }
John McCall864e3962010-05-07 05:32:02 +00009584 }
John McCallc07a0c72011-02-17 10:25:35 +00009585 case Expr::BinaryConditionalOperatorClass: {
9586 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9587 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009588 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009589 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009590 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9591 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9592 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009593 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009594 return FalseResult;
9595 }
John McCall864e3962010-05-07 05:32:02 +00009596 case Expr::ConditionalOperatorClass: {
9597 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9598 // If the condition (ignoring parens) is a __builtin_constant_p call,
9599 // then only the true side is actually considered in an integer constant
9600 // expression, and it is fully evaluated. This is an important GNU
9601 // extension. See GCC PR38377 for discussion.
9602 if (const CallExpr *CallCE
9603 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009604 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009605 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009606 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009607 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009608 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009609
Richard Smithf57d8cb2011-12-09 22:58:01 +00009610 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9611 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009612
Richard Smith9e575da2012-12-28 13:25:52 +00009613 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009614 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009615 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009616 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009617 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009618 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009619 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009620 return NoDiag();
9621 // Rare case where the diagnostics depend on which side is evaluated
9622 // Note that if we get here, CondResult is 0, and at least one of
9623 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009624 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009625 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009626 return TrueResult;
9627 }
9628 case Expr::CXXDefaultArgExprClass:
9629 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009630 case Expr::CXXDefaultInitExprClass:
9631 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009632 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009633 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009634 }
9635 }
9636
David Blaikiee4d798f2012-01-20 21:50:17 +00009637 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009638}
9639
Richard Smithf57d8cb2011-12-09 22:58:01 +00009640/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009641static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009642 const Expr *E,
9643 llvm::APSInt *Value,
9644 SourceLocation *Loc) {
9645 if (!E->getType()->isIntegralOrEnumerationType()) {
9646 if (Loc) *Loc = E->getExprLoc();
9647 return false;
9648 }
9649
Richard Smith66e05fe2012-01-18 05:21:49 +00009650 APValue Result;
9651 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009652 return false;
9653
Richard Smith98710fc2014-11-13 23:03:19 +00009654 if (!Result.isInt()) {
9655 if (Loc) *Loc = E->getExprLoc();
9656 return false;
9657 }
9658
Richard Smith66e05fe2012-01-18 05:21:49 +00009659 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009660 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009661}
9662
Craig Toppera31a8822013-08-22 07:09:37 +00009663bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9664 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009665 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009666 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009667
Richard Smith9e575da2012-12-28 13:25:52 +00009668 ICEDiag D = CheckICE(this, Ctx);
9669 if (D.Kind != IK_ICE) {
9670 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009671 return false;
9672 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009673 return true;
9674}
9675
Craig Toppera31a8822013-08-22 07:09:37 +00009676bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009677 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009678 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009679 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9680
9681 if (!isIntegerConstantExpr(Ctx, Loc))
9682 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009683 // The only possible side-effects here are due to UB discovered in the
9684 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9685 // required to treat the expression as an ICE, so we produce the folded
9686 // value.
9687 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009688 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009689 return true;
9690}
Richard Smith66e05fe2012-01-18 05:21:49 +00009691
Craig Toppera31a8822013-08-22 07:09:37 +00009692bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009693 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009694}
9695
Craig Toppera31a8822013-08-22 07:09:37 +00009696bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009697 SourceLocation *Loc) const {
9698 // We support this checking in C++98 mode in order to diagnose compatibility
9699 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009700 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009701
Richard Smith98a0a492012-02-14 21:38:30 +00009702 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009703 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009704 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009705 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009706 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009707
9708 APValue Scratch;
9709 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9710
9711 if (!Diags.empty()) {
9712 IsConstExpr = false;
9713 if (Loc) *Loc = Diags[0].first;
9714 } else if (!IsConstExpr) {
9715 // FIXME: This shouldn't happen.
9716 if (Loc) *Loc = getExprLoc();
9717 }
9718
9719 return IsConstExpr;
9720}
Richard Smith253c2a32012-01-27 01:14:48 +00009721
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009722bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9723 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009724 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009725 Expr::EvalStatus Status;
9726 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9727
9728 ArgVector ArgValues(Args.size());
9729 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9730 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009731 if ((*I)->isValueDependent() ||
9732 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009733 // If evaluation fails, throw away the argument entirely.
9734 ArgValues[I - Args.begin()] = APValue();
9735 if (Info.EvalStatus.HasSideEffects)
9736 return false;
9737 }
9738
9739 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009740 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009741 ArgValues.data());
9742 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9743}
9744
Richard Smith253c2a32012-01-27 01:14:48 +00009745bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009746 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009747 PartialDiagnosticAt> &Diags) {
9748 // FIXME: It would be useful to check constexpr function templates, but at the
9749 // moment the constant expression evaluator cannot cope with the non-rigorous
9750 // ASTs which we build for dependent expressions.
9751 if (FD->isDependentContext())
9752 return true;
9753
9754 Expr::EvalStatus Status;
9755 Status.Diag = &Diags;
9756
Richard Smith6d4c6582013-11-05 22:18:15 +00009757 EvalInfo Info(FD->getASTContext(), Status,
9758 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009759
9760 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009761 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009762
Richard Smith7525ff62013-05-09 07:14:00 +00009763 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009764 // is a temporary being used as the 'this' pointer.
9765 LValue This;
9766 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009767 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009768
Richard Smith253c2a32012-01-27 01:14:48 +00009769 ArrayRef<const Expr*> Args;
9770
9771 SourceLocation Loc = FD->getLocation();
9772
Richard Smith2e312c82012-03-03 22:46:17 +00009773 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009774 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9775 // Evaluate the call as a constant initializer, to allow the construction
9776 // of objects of non-literal types.
9777 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009778 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009779 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009780 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009781 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009782
9783 return Diags.empty();
9784}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009785
9786bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9787 const FunctionDecl *FD,
9788 SmallVectorImpl<
9789 PartialDiagnosticAt> &Diags) {
9790 Expr::EvalStatus Status;
9791 Status.Diag = &Diags;
9792
9793 EvalInfo Info(FD->getASTContext(), Status,
9794 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9795
9796 // Fabricate a call stack frame to give the arguments a plausible cover story.
9797 ArrayRef<const Expr*> Args;
9798 ArgVector ArgValues(0);
9799 bool Success = EvaluateArgs(Args, ArgValues, Info);
9800 (void)Success;
9801 assert(Success &&
9802 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009803 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009804
9805 APValue ResultScratch;
9806 Evaluate(ResultScratch, Info, E);
9807 return Diags.empty();
9808}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009809
9810bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9811 unsigned Type) const {
9812 if (!getType()->isPointerType())
9813 return false;
9814
9815 Expr::EvalStatus Status;
9816 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9817 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9818}