blob: 262c97a74b3e5c8feb05a8c3e09f0b50803ab8dd [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"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
160 bool Invalid : 1;
161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
163 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
166 bool MostDerivedIsArrayElement : 1;
167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smithb228a862012-02-15 02:18:13 +0000319 /// Index - The call index of this call.
320 unsigned Index;
321
Richard Smithd62306a2011-11-10 06:34:14 +0000322 /// This - The binding for the this pointer in this call, if any.
323 const LValue *This;
324
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000325 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000326 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000327 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000328
Eli Friedman4830ec82012-06-25 21:21:08 +0000329 // Note that we intentionally use std::map here so that references to
330 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000331 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith357362d2011-12-13 06:39:58 +0000472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
475
Richard Smith0c6124b2015-12-03 01:36:22 +0000476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
477 /// fold (not just why it's not strictly a constant expression)?
478 bool HasFoldFailureDiagnostic;
479
Richard Smith6d4c6582013-11-05 22:18:15 +0000480 enum EvaluationMode {
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression.
483 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000484
Richard Smith6d4c6582013-11-05 22:18:15 +0000485 /// Evaluate as a potential constant expression. Keep going if we hit a
486 /// construct that we can't evaluate yet (because we don't yet know the
487 /// value of something) but stop if we hit something that could never be
488 /// a constant expression.
489 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000490
Richard Smith6d4c6582013-11-05 22:18:15 +0000491 /// Fold the expression to a constant. Stop if we hit a side-effect that
492 /// we can't model.
493 EM_ConstantFold,
494
495 /// Evaluate the expression looking for integer overflow and similar
496 /// issues. Don't worry about side-effects, and try to visit all
497 /// subexpressions.
498 EM_EvaluateForOverflow,
499
500 /// Evaluate in any way we know how. Don't worry about side-effects that
501 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000502 EM_IgnoreSideEffects,
503
504 /// Evaluate as a constant expression. Stop if we find that the expression
505 /// is not a constant expression. Some expressions can be retried in the
506 /// optimizer if we don't constant fold them here, but in an unevaluated
507 /// context we try to fold them immediately since the optimizer never
508 /// gets a chance to look at it.
509 EM_ConstantExpressionUnevaluated,
510
511 /// Evaluate as a potential constant expression. Keep going if we hit a
512 /// construct that we can't evaluate yet (because we don't yet know the
513 /// value of something) but stop if we hit something that could never be
514 /// a constant expression. Some expressions can be retried in the
515 /// optimizer if we don't constant fold them here, but in an unevaluated
516 /// context we try to fold them immediately since the optimizer never
517 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000518 EM_PotentialConstantExpressionUnevaluated,
519
520 /// Evaluate as a constant expression. Continue evaluating if we find a
521 /// MemberExpr with a base that can't be evaluated.
522 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000523 } EvalMode;
524
525 /// Are we checking whether the expression is a potential constant
526 /// expression?
527 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000528 return EvalMode == EM_PotentialConstantExpression ||
529 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000530 }
531
532 /// Are we checking an expression for overflow?
533 // FIXME: We should check for any kind of undefined or suspicious behavior
534 // in such constructs, not just overflow.
535 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
536
537 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000538 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000539 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000540 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000541 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
542 EvaluatingDecl((const ValueDecl *)nullptr),
543 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith0c6124b2015-12-03 01:36:22 +0000544 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000545
Richard Smith7525ff62013-05-09 07:14:00 +0000546 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
547 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000548 EvaluatingDeclValue = &Value;
549 }
550
David Blaikiebbafb8a2012-03-11 07:00:24 +0000551 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000552
Richard Smith357362d2011-12-13 06:39:58 +0000553 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000554 // Don't perform any constexpr calls (other than the call we're checking)
555 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000556 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000557 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000558 if (NextCallIndex == 0) {
559 // NextCallIndex has wrapped around.
560 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
561 return false;
562 }
Richard Smith357362d2011-12-13 06:39:58 +0000563 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
564 return true;
565 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
566 << getLangOpts().ConstexprCallDepth;
567 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000568 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000569
Richard Smithb228a862012-02-15 02:18:13 +0000570 CallStackFrame *getCallFrame(unsigned CallIndex) {
571 assert(CallIndex && "no call index in getCallFrame");
572 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
573 // be null in this loop.
574 CallStackFrame *Frame = CurrentCall;
575 while (Frame->Index > CallIndex)
576 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000577 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000578 }
579
Richard Smitha3d3bd22013-05-08 02:12:03 +0000580 bool nextStep(const Stmt *S) {
581 if (!StepsLeft) {
582 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
583 return false;
584 }
585 --StepsLeft;
586 return true;
587 }
588
Richard Smith357362d2011-12-13 06:39:58 +0000589 private:
590 /// Add a diagnostic to the diagnostics list.
591 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
592 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
593 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
594 return EvalStatus.Diag->back().second;
595 }
596
Richard Smithf6f003a2011-12-16 19:06:07 +0000597 /// Add notes containing a call stack to the current point of evaluation.
598 void addCallStack(unsigned Limit);
599
Richard Smith357362d2011-12-13 06:39:58 +0000600 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000601 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000602 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
603 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000604 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000605 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000606 // If we have a prior diagnostic, it will be noting that the expression
607 // isn't a constant expression. This diagnostic is more important,
608 // unless we require this evaluation to produce a constant expression.
609 //
610 // FIXME: We might want to show both diagnostics to the user in
611 // EM_ConstantFold mode.
612 if (!EvalStatus.Diag->empty()) {
613 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000614 case EM_ConstantFold:
615 case EM_IgnoreSideEffects:
616 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000617 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000618 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000619 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000620 case EM_ConstantExpression:
621 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000622 case EM_ConstantExpressionUnevaluated:
623 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000624 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000625 HasActiveDiagnostic = false;
626 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 }
628 }
629
Richard Smithf6f003a2011-12-16 19:06:07 +0000630 unsigned CallStackNotes = CallStackDepth - 1;
631 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
632 if (Limit)
633 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000634 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000635 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000636
Richard Smith357362d2011-12-13 06:39:58 +0000637 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000638 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000639 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000640 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
641 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000643 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000644 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000647 return OptionalDiagnostic();
648 }
649
Richard Smithce1ec5e2012-03-15 04:53:45 +0000650 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
651 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000652 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000653 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000654 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000655 HasActiveDiagnostic = false;
656 return OptionalDiagnostic();
657 }
658
Richard Smith92b1ce02011-12-12 09:28:41 +0000659 /// Diagnose that the evaluation does not produce a C++11 core constant
660 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000661 ///
662 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
663 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000664 template<typename LocArg>
665 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000666 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000667 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000668 // Don't override a previous diagnostic. Don't bother collecting
669 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000670 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000671 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000672 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000673 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000674 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000675 }
676
677 /// Add a note to a prior diagnostic.
678 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
679 if (!HasActiveDiagnostic)
680 return OptionalDiagnostic();
681 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000682 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000683
684 /// Add a stack of notes to a prior diagnostic.
685 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
686 if (HasActiveDiagnostic) {
687 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
688 Diags.begin(), Diags.end());
689 }
690 }
Richard Smith253c2a32012-01-27 01:14:48 +0000691
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 /// Should we continue evaluation after encountering a side-effect that we
693 /// couldn't model?
694 bool keepEvaluatingAfterSideEffect() {
695 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000696 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_EvaluateForOverflow:
699 case EM_IgnoreSideEffects:
700 return true;
701
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000703 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000705 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000706 return false;
707 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000708 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 }
710
711 /// Note that we have had a side-effect, and determine whether we should
712 /// keep evaluating.
713 bool noteSideEffect() {
714 EvalStatus.HasSideEffects = true;
715 return keepEvaluatingAfterSideEffect();
716 }
717
Richard Smithce8eca52015-12-08 03:21:47 +0000718 /// Should we continue evaluation after encountering undefined behavior?
719 bool keepEvaluatingAfterUndefinedBehavior() {
720 switch (EvalMode) {
721 case EM_EvaluateForOverflow:
722 case EM_IgnoreSideEffects:
723 case EM_ConstantFold:
724 case EM_DesignatorFold:
725 return true;
726
727 case EM_PotentialConstantExpression:
728 case EM_PotentialConstantExpressionUnevaluated:
729 case EM_ConstantExpression:
730 case EM_ConstantExpressionUnevaluated:
731 return false;
732 }
733 llvm_unreachable("Missed EvalMode case");
734 }
735
736 /// Note that we hit something that was technically undefined behavior, but
737 /// that we can evaluate past it (such as signed overflow or floating-point
738 /// division by zero.)
739 bool noteUndefinedBehavior() {
740 EvalStatus.HasUndefinedBehavior = true;
741 return keepEvaluatingAfterUndefinedBehavior();
742 }
743
Richard Smith253c2a32012-01-27 01:14:48 +0000744 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000745 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000746 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 if (!StepsLeft)
748 return false;
749
750 switch (EvalMode) {
751 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000752 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000753 case EM_EvaluateForOverflow:
754 return true;
755
756 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000757 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000758 case EM_ConstantFold:
759 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000760 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 return false;
762 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000763 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000764 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000765
766 bool allowInvalidBaseExpr() const {
767 return EvalMode == EM_DesignatorFold;
768 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000769 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000770
771 /// Object used to treat all foldable expressions as constant expressions.
772 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000773 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000774 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000775 bool HadNoPriorDiags;
776 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000777
Richard Smith6d4c6582013-11-05 22:18:15 +0000778 explicit FoldConstant(EvalInfo &Info, bool Enabled)
779 : Info(Info),
780 Enabled(Enabled),
781 HadNoPriorDiags(Info.EvalStatus.Diag &&
782 Info.EvalStatus.Diag->empty() &&
783 !Info.EvalStatus.HasSideEffects),
784 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000785 if (Enabled &&
786 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
787 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000789 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000790 void keepDiagnostics() { Enabled = false; }
791 ~FoldConstant() {
792 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000793 !Info.EvalStatus.HasSideEffects)
794 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000796 }
797 };
Richard Smith17100ba2012-02-16 02:46:34 +0000798
George Burgess IV3a03fab2015-09-04 21:28:13 +0000799 /// RAII object used to treat the current evaluation as the correct pointer
800 /// offset fold for the current EvalMode
801 struct FoldOffsetRAII {
802 EvalInfo &Info;
803 EvalInfo::EvaluationMode OldMode;
804 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
805 : Info(Info), OldMode(Info.EvalMode) {
806 if (!Info.checkingPotentialConstantExpression())
807 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
808 : EvalInfo::EM_ConstantFold;
809 }
810
811 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
812 };
813
Richard Smith17100ba2012-02-16 02:46:34 +0000814 /// RAII object used to suppress diagnostics and side-effects from a
815 /// speculative evaluation.
816 class SpeculativeEvaluationRAII {
817 EvalInfo &Info;
818 Expr::EvalStatus Old;
819
820 public:
821 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000822 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000823 : Info(Info), Old(Info.EvalStatus) {
824 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 // If we're speculatively evaluating, we may have skipped over some
826 // evaluations and missed out a side effect.
827 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000828 }
829 ~SpeculativeEvaluationRAII() {
830 Info.EvalStatus = Old;
831 }
832 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000833
834 /// RAII object wrapping a full-expression or block scope, and handling
835 /// the ending of the lifetime of temporaries created within it.
836 template<bool IsFullExpression>
837 class ScopeRAII {
838 EvalInfo &Info;
839 unsigned OldStackSize;
840 public:
841 ScopeRAII(EvalInfo &Info)
842 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
843 ~ScopeRAII() {
844 // Body moved to a static method to encourage the compiler to inline away
845 // instances of this class.
846 cleanup(Info, OldStackSize);
847 }
848 private:
849 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
850 unsigned NewEnd = OldStackSize;
851 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
852 I != N; ++I) {
853 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
854 // Full-expression cleanup of a lifetime-extended temporary: nothing
855 // to do, just move this cleanup to the right place in the stack.
856 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
857 ++NewEnd;
858 } else {
859 // End the lifetime of the object.
860 Info.CleanupStack[I].endLifetime();
861 }
862 }
863 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
864 Info.CleanupStack.end());
865 }
866 };
867 typedef ScopeRAII<false> BlockScopeRAII;
868 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000869}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000870
Richard Smitha8105bc2012-01-06 16:39:00 +0000871bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
872 CheckSubobjectKind CSK) {
873 if (Invalid)
874 return false;
875 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000876 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000877 << CSK;
878 setInvalid();
879 return false;
880 }
881 return true;
882}
883
884void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
885 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000886 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000887 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000888 << static_cast<int>(N) << /*array*/ 0
889 << static_cast<unsigned>(MostDerivedArraySize);
890 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000891 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000892 << static_cast<int>(N) << /*non-array*/ 1;
893 setInvalid();
894}
895
Richard Smithf6f003a2011-12-16 19:06:07 +0000896CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
897 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000898 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000899 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000900 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000901 Info.CurrentCall = this;
902 ++Info.CallStackDepth;
903}
904
905CallStackFrame::~CallStackFrame() {
906 assert(Info.CurrentCall == this && "calls retired out of order");
907 --Info.CallStackDepth;
908 Info.CurrentCall = Caller;
909}
910
Richard Smith08d6a2c2013-07-24 07:11:57 +0000911APValue &CallStackFrame::createTemporary(const void *Key,
912 bool IsLifetimeExtended) {
913 APValue &Result = Temporaries[Key];
914 assert(Result.isUninit() && "temporary created multiple times");
915 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
916 return Result;
917}
918
Richard Smith84401042013-06-03 05:03:02 +0000919static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000920
921void EvalInfo::addCallStack(unsigned Limit) {
922 // Determine which calls to skip, if any.
923 unsigned ActiveCalls = CallStackDepth - 1;
924 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
925 if (Limit && Limit < ActiveCalls) {
926 SkipStart = Limit / 2 + Limit % 2;
927 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000928 }
929
Richard Smithf6f003a2011-12-16 19:06:07 +0000930 // Walk the call stack and add the diagnostics.
931 unsigned CallIdx = 0;
932 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
933 Frame = Frame->Caller, ++CallIdx) {
934 // Skip this call?
935 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
936 if (CallIdx == SkipStart) {
937 // Note that we're skipping calls.
938 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
939 << unsigned(ActiveCalls - Limit);
940 }
941 continue;
942 }
943
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000944 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000945 llvm::raw_svector_ostream Out(Buffer);
946 describeCall(Frame, Out);
947 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
948 }
949}
950
951namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000952 struct ComplexValue {
953 private:
954 bool IsInt;
955
956 public:
957 APSInt IntReal, IntImag;
958 APFloat FloatReal, FloatImag;
959
960 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
961
962 void makeComplexFloat() { IsInt = false; }
963 bool isComplexFloat() const { return !IsInt; }
964 APFloat &getComplexFloatReal() { return FloatReal; }
965 APFloat &getComplexFloatImag() { return FloatImag; }
966
967 void makeComplexInt() { IsInt = true; }
968 bool isComplexInt() const { return IsInt; }
969 APSInt &getComplexIntReal() { return IntReal; }
970 APSInt &getComplexIntImag() { return IntImag; }
971
Richard Smith2e312c82012-03-03 22:46:17 +0000972 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000973 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000974 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000975 else
Richard Smith2e312c82012-03-03 22:46:17 +0000976 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000977 }
Richard Smith2e312c82012-03-03 22:46:17 +0000978 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000979 assert(v.isComplexFloat() || v.isComplexInt());
980 if (v.isComplexFloat()) {
981 makeComplexFloat();
982 FloatReal = v.getComplexFloatReal();
983 FloatImag = v.getComplexFloatImag();
984 } else {
985 makeComplexInt();
986 IntReal = v.getComplexIntReal();
987 IntImag = v.getComplexIntImag();
988 }
989 }
John McCall93d91dc2010-05-07 17:22:02 +0000990 };
John McCall45d55e42010-05-07 21:00:08 +0000991
992 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000993 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000994 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000995 bool InvalidBase : 1;
996 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000997 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000998
Richard Smithce40ad62011-11-12 22:28:03 +0000999 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001000 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001001 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001002 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001003 SubobjectDesignator &getLValueDesignator() { return Designator; }
1004 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001005
Richard Smith2e312c82012-03-03 22:46:17 +00001006 void moveInto(APValue &V) const {
1007 if (Designator.Invalid)
1008 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1009 else
1010 V = APValue(Base, Offset, Designator.Entries,
1011 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001012 }
Richard Smith2e312c82012-03-03 22:46:17 +00001013 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001014 assert(V.isLValue());
1015 Base = V.getLValueBase();
1016 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001017 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001018 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001019 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001020 }
1021
George Burgess IV3a03fab2015-09-04 21:28:13 +00001022 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001023 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001024 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001025 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001026 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001027 Designator = SubobjectDesignator(getType(B));
1028 }
1029
George Burgess IV3a03fab2015-09-04 21:28:13 +00001030 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1031 set(B, I, true);
1032 }
1033
Richard Smitha8105bc2012-01-06 16:39:00 +00001034 // Check that this LValue is not based on a null pointer. If it is, produce
1035 // a diagnostic and mark the designator as invalid.
1036 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1037 CheckSubobjectKind CSK) {
1038 if (Designator.Invalid)
1039 return false;
1040 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001041 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001042 << CSK;
1043 Designator.setInvalid();
1044 return false;
1045 }
1046 return true;
1047 }
1048
1049 // Check this LValue refers to an object. If not, set the designator to be
1050 // invalid and emit a diagnostic.
1051 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001052 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001053 Designator.checkSubobject(Info, E, CSK);
1054 }
1055
1056 void addDecl(EvalInfo &Info, const Expr *E,
1057 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001058 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1059 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001060 }
1061 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001062 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1063 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001064 }
Richard Smith66c96992012-02-18 22:04:06 +00001065 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1067 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001068 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001069 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001070 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001071 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001072 }
John McCall45d55e42010-05-07 21:00:08 +00001073 };
Richard Smith027bf112011-11-17 22:56:20 +00001074
1075 struct MemberPtr {
1076 MemberPtr() {}
1077 explicit MemberPtr(const ValueDecl *Decl) :
1078 DeclAndIsDerivedMember(Decl, false), Path() {}
1079
1080 /// The member or (direct or indirect) field referred to by this member
1081 /// pointer, or 0 if this is a null member pointer.
1082 const ValueDecl *getDecl() const {
1083 return DeclAndIsDerivedMember.getPointer();
1084 }
1085 /// Is this actually a member of some type derived from the relevant class?
1086 bool isDerivedMember() const {
1087 return DeclAndIsDerivedMember.getInt();
1088 }
1089 /// Get the class which the declaration actually lives in.
1090 const CXXRecordDecl *getContainingRecord() const {
1091 return cast<CXXRecordDecl>(
1092 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1093 }
1094
Richard Smith2e312c82012-03-03 22:46:17 +00001095 void moveInto(APValue &V) const {
1096 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001097 }
Richard Smith2e312c82012-03-03 22:46:17 +00001098 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001099 assert(V.isMemberPointer());
1100 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1101 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1102 Path.clear();
1103 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1104 Path.insert(Path.end(), P.begin(), P.end());
1105 }
1106
1107 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1108 /// whether the member is a member of some class derived from the class type
1109 /// of the member pointer.
1110 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1111 /// Path - The path of base/derived classes from the member declaration's
1112 /// class (exclusive) to the class type of the member pointer (inclusive).
1113 SmallVector<const CXXRecordDecl*, 4> Path;
1114
1115 /// Perform a cast towards the class of the Decl (either up or down the
1116 /// hierarchy).
1117 bool castBack(const CXXRecordDecl *Class) {
1118 assert(!Path.empty());
1119 const CXXRecordDecl *Expected;
1120 if (Path.size() >= 2)
1121 Expected = Path[Path.size() - 2];
1122 else
1123 Expected = getContainingRecord();
1124 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1125 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1126 // if B does not contain the original member and is not a base or
1127 // derived class of the class containing the original member, the result
1128 // of the cast is undefined.
1129 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1130 // (D::*). We consider that to be a language defect.
1131 return false;
1132 }
1133 Path.pop_back();
1134 return true;
1135 }
1136 /// Perform a base-to-derived member pointer cast.
1137 bool castToDerived(const CXXRecordDecl *Derived) {
1138 if (!getDecl())
1139 return true;
1140 if (!isDerivedMember()) {
1141 Path.push_back(Derived);
1142 return true;
1143 }
1144 if (!castBack(Derived))
1145 return false;
1146 if (Path.empty())
1147 DeclAndIsDerivedMember.setInt(false);
1148 return true;
1149 }
1150 /// Perform a derived-to-base member pointer cast.
1151 bool castToBase(const CXXRecordDecl *Base) {
1152 if (!getDecl())
1153 return true;
1154 if (Path.empty())
1155 DeclAndIsDerivedMember.setInt(true);
1156 if (isDerivedMember()) {
1157 Path.push_back(Base);
1158 return true;
1159 }
1160 return castBack(Base);
1161 }
1162 };
Richard Smith357362d2011-12-13 06:39:58 +00001163
Richard Smith7bb00672012-02-01 01:42:44 +00001164 /// Compare two member pointers, which are assumed to be of the same type.
1165 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1166 if (!LHS.getDecl() || !RHS.getDecl())
1167 return !LHS.getDecl() && !RHS.getDecl();
1168 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1169 return false;
1170 return LHS.Path == RHS.Path;
1171 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001172}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001173
Richard Smith2e312c82012-03-03 22:46:17 +00001174static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001175static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1176 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001177 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001178static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1179static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001180static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1181 EvalInfo &Info);
1182static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001183static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001184static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001185 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001186static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001187static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001188static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001189static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001190
1191//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001192// Misc utilities
1193//===----------------------------------------------------------------------===//
1194
Richard Smith84401042013-06-03 05:03:02 +00001195/// Produce a string describing the given constexpr call.
1196static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1197 unsigned ArgIndex = 0;
1198 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1199 !isa<CXXConstructorDecl>(Frame->Callee) &&
1200 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1201
1202 if (!IsMemberCall)
1203 Out << *Frame->Callee << '(';
1204
1205 if (Frame->This && IsMemberCall) {
1206 APValue Val;
1207 Frame->This->moveInto(Val);
1208 Val.printPretty(Out, Frame->Info.Ctx,
1209 Frame->This->Designator.MostDerivedType);
1210 // FIXME: Add parens around Val if needed.
1211 Out << "->" << *Frame->Callee << '(';
1212 IsMemberCall = false;
1213 }
1214
1215 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1216 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1217 if (ArgIndex > (unsigned)IsMemberCall)
1218 Out << ", ";
1219
1220 const ParmVarDecl *Param = *I;
1221 const APValue &Arg = Frame->Arguments[ArgIndex];
1222 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1223
1224 if (ArgIndex == 0 && IsMemberCall)
1225 Out << "->" << *Frame->Callee << '(';
1226 }
1227
1228 Out << ')';
1229}
1230
Richard Smithd9f663b2013-04-22 15:31:51 +00001231/// Evaluate an expression to see if it had side-effects, and discard its
1232/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001233/// \return \c true if the caller should keep evaluating.
1234static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001235 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001236 if (!Evaluate(Scratch, Info, E))
1237 // We don't need the value, but we might have skipped a side effect here.
1238 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001239 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001240}
1241
Richard Smith861b5b52013-05-07 23:34:45 +00001242/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1243/// return its existing value.
1244static int64_t getExtValue(const APSInt &Value) {
1245 return Value.isSigned() ? Value.getSExtValue()
1246 : static_cast<int64_t>(Value.getZExtValue());
1247}
1248
Richard Smithd62306a2011-11-10 06:34:14 +00001249/// Should this call expression be treated as a string literal?
1250static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001251 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001252 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1253 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1254}
1255
Richard Smithce40ad62011-11-12 22:28:03 +00001256static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001257 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1258 // constant expression of pointer type that evaluates to...
1259
1260 // ... a null pointer value, or a prvalue core constant expression of type
1261 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001262 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001263
Richard Smithce40ad62011-11-12 22:28:03 +00001264 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1265 // ... the address of an object with static storage duration,
1266 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1267 return VD->hasGlobalStorage();
1268 // ... the address of a function,
1269 return isa<FunctionDecl>(D);
1270 }
1271
1272 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001273 switch (E->getStmtClass()) {
1274 default:
1275 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001276 case Expr::CompoundLiteralExprClass: {
1277 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1278 return CLE->isFileScope() && CLE->isLValue();
1279 }
Richard Smithe6c01442013-06-05 00:46:14 +00001280 case Expr::MaterializeTemporaryExprClass:
1281 // A materialized temporary might have been lifetime-extended to static
1282 // storage duration.
1283 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001284 // A string literal has static storage duration.
1285 case Expr::StringLiteralClass:
1286 case Expr::PredefinedExprClass:
1287 case Expr::ObjCStringLiteralClass:
1288 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001289 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001290 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001291 return true;
1292 case Expr::CallExprClass:
1293 return IsStringLiteralCall(cast<CallExpr>(E));
1294 // For GCC compatibility, &&label has static storage duration.
1295 case Expr::AddrLabelExprClass:
1296 return true;
1297 // A Block literal expression may be used as the initialization value for
1298 // Block variables at global or local static scope.
1299 case Expr::BlockExprClass:
1300 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001301 case Expr::ImplicitValueInitExprClass:
1302 // FIXME:
1303 // We can never form an lvalue with an implicit value initialization as its
1304 // base through expression evaluation, so these only appear in one case: the
1305 // implicit variable declaration we invent when checking whether a constexpr
1306 // constructor can produce a constant expression. We must assume that such
1307 // an expression might be a global lvalue.
1308 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001309 }
John McCall95007602010-05-10 23:27:23 +00001310}
1311
Richard Smithb228a862012-02-15 02:18:13 +00001312static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1313 assert(Base && "no location for a null lvalue");
1314 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1315 if (VD)
1316 Info.Note(VD->getLocation(), diag::note_declared_at);
1317 else
Ted Kremenek28831752012-08-23 20:46:57 +00001318 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001319 diag::note_constexpr_temporary_here);
1320}
1321
Richard Smith80815602011-11-07 05:07:52 +00001322/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001323/// value for an address or reference constant expression. Return true if we
1324/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001325static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1326 QualType Type, const LValue &LVal) {
1327 bool IsReferenceType = Type->isReferenceType();
1328
Richard Smith357362d2011-12-13 06:39:58 +00001329 APValue::LValueBase Base = LVal.getLValueBase();
1330 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1331
Richard Smith0dea49e2012-02-18 04:58:18 +00001332 // Check that the object is a global. Note that the fake 'this' object we
1333 // manufacture when checking potential constant expressions is conservatively
1334 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001335 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001336 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001337 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001338 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1339 << IsReferenceType << !Designator.Entries.empty()
1340 << !!VD << VD;
1341 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001342 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001343 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001344 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001345 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001346 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001347 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001348 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001349 LVal.getLValueCallIndex() == 0) &&
1350 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001351
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001352 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1353 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001354 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001355 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001356 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001357
Hans Wennborg82dd8772014-06-25 22:19:48 +00001358 // A dllimport variable never acts like a constant.
1359 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001360 return false;
1361 }
1362 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1363 // __declspec(dllimport) must be handled very carefully:
1364 // We must never initialize an expression with the thunk in C++.
1365 // Doing otherwise would allow the same id-expression to yield
1366 // different addresses for the same function in different translation
1367 // units. However, this means that we must dynamically initialize the
1368 // expression with the contents of the import address table at runtime.
1369 //
1370 // The C language has no notion of ODR; furthermore, it has no notion of
1371 // dynamic initialization. This means that we are permitted to
1372 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001373 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001374 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001375 }
1376 }
1377
Richard Smitha8105bc2012-01-06 16:39:00 +00001378 // Allow address constant expressions to be past-the-end pointers. This is
1379 // an extension: the standard requires them to point to an object.
1380 if (!IsReferenceType)
1381 return true;
1382
1383 // A reference constant expression must refer to an object.
1384 if (!Base) {
1385 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001386 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001387 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001388 }
1389
Richard Smith357362d2011-12-13 06:39:58 +00001390 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001391 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001392 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001393 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001394 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001395 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001396 }
1397
Richard Smith80815602011-11-07 05:07:52 +00001398 return true;
1399}
1400
Richard Smithfddd3842011-12-30 21:15:51 +00001401/// Check that this core constant expression is of literal type, and if not,
1402/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001403static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001404 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001405 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001406 return true;
1407
Richard Smith7525ff62013-05-09 07:14:00 +00001408 // C++1y: A constant initializer for an object o [...] may also invoke
1409 // constexpr constructors for o and its subobjects even if those objects
1410 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001411 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001412 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001413 return true;
1414
Richard Smithfddd3842011-12-30 21:15:51 +00001415 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001416 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001417 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001418 << E->getType();
1419 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001420 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001421 return false;
1422}
1423
Richard Smith0b0a0b62011-10-29 20:57:55 +00001424/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001425/// constant expression. If not, report an appropriate diagnostic. Does not
1426/// check that the expression is of literal type.
1427static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1428 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001429 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001430 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1431 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001432 return false;
1433 }
1434
Richard Smith77be48a2014-07-31 06:31:19 +00001435 // We allow _Atomic(T) to be initialized from anything that T can be
1436 // initialized from.
1437 if (const AtomicType *AT = Type->getAs<AtomicType>())
1438 Type = AT->getValueType();
1439
Richard Smithb228a862012-02-15 02:18:13 +00001440 // Core issue 1454: For a literal constant expression of array or class type,
1441 // each subobject of its value shall have been initialized by a constant
1442 // expression.
1443 if (Value.isArray()) {
1444 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1445 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1446 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1447 Value.getArrayInitializedElt(I)))
1448 return false;
1449 }
1450 if (!Value.hasArrayFiller())
1451 return true;
1452 return CheckConstantExpression(Info, DiagLoc, EltTy,
1453 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001454 }
Richard Smithb228a862012-02-15 02:18:13 +00001455 if (Value.isUnion() && Value.getUnionField()) {
1456 return CheckConstantExpression(Info, DiagLoc,
1457 Value.getUnionField()->getType(),
1458 Value.getUnionValue());
1459 }
1460 if (Value.isStruct()) {
1461 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1462 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1463 unsigned BaseIndex = 0;
1464 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1465 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1466 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1467 Value.getStructBase(BaseIndex)))
1468 return false;
1469 }
1470 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001471 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001472 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1473 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001474 return false;
1475 }
1476 }
1477
1478 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001479 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001480 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001481 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1482 }
1483
1484 // Everything else is fine.
1485 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001486}
1487
Benjamin Kramer8407df72015-03-09 16:47:52 +00001488static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001489 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001490}
1491
1492static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001493 if (Value.CallIndex)
1494 return false;
1495 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1496 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001497}
1498
Richard Smithcecf1842011-11-01 21:06:14 +00001499static bool IsWeakLValue(const LValue &Value) {
1500 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001501 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001502}
1503
David Majnemerb5116032014-12-09 23:32:34 +00001504static bool isZeroSized(const LValue &Value) {
1505 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001506 if (Decl && isa<VarDecl>(Decl)) {
1507 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001508 if (Ty->isArrayType())
1509 return Ty->isIncompleteType() ||
1510 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001511 }
1512 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001513}
1514
Richard Smith2e312c82012-03-03 22:46:17 +00001515static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001516 // A null base expression indicates a null pointer. These are always
1517 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001518 if (!Value.getLValueBase()) {
1519 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001520 return true;
1521 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001522
Richard Smith027bf112011-11-17 22:56:20 +00001523 // We have a non-null base. These are generally known to be true, but if it's
1524 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001525 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001526 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001527 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001528}
1529
Richard Smith2e312c82012-03-03 22:46:17 +00001530static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001531 switch (Val.getKind()) {
1532 case APValue::Uninitialized:
1533 return false;
1534 case APValue::Int:
1535 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001536 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001537 case APValue::Float:
1538 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001539 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001540 case APValue::ComplexInt:
1541 Result = Val.getComplexIntReal().getBoolValue() ||
1542 Val.getComplexIntImag().getBoolValue();
1543 return true;
1544 case APValue::ComplexFloat:
1545 Result = !Val.getComplexFloatReal().isZero() ||
1546 !Val.getComplexFloatImag().isZero();
1547 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001548 case APValue::LValue:
1549 return EvalPointerValueAsBool(Val, Result);
1550 case APValue::MemberPointer:
1551 Result = Val.getMemberPointerDecl();
1552 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001553 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001554 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001555 case APValue::Struct:
1556 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001557 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001558 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001559 }
1560
Richard Smith11562c52011-10-28 17:51:58 +00001561 llvm_unreachable("unknown APValue kind");
1562}
1563
1564static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1565 EvalInfo &Info) {
1566 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001567 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001568 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001569 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001570 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001571}
1572
Richard Smith357362d2011-12-13 06:39:58 +00001573template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001574static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001575 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001576 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001577 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001578 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001579}
1580
1581static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1582 QualType SrcType, const APFloat &Value,
1583 QualType DestType, APSInt &Result) {
1584 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001585 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001586 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001587
Richard Smith357362d2011-12-13 06:39:58 +00001588 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001589 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001590 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1591 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001592 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001593 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001594}
1595
Richard Smith357362d2011-12-13 06:39:58 +00001596static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1597 QualType SrcType, QualType DestType,
1598 APFloat &Result) {
1599 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001600 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001601 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1602 APFloat::rmNearestTiesToEven, &ignored)
1603 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001604 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001605 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001606}
1607
Richard Smith911e1422012-01-30 22:27:01 +00001608static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1609 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001610 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001611 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001612 APSInt Result = Value;
1613 // Figure out if this is a truncate, extend or noop cast.
1614 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001615 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001616 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001617 return Result;
1618}
1619
Richard Smith357362d2011-12-13 06:39:58 +00001620static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1621 QualType SrcType, const APSInt &Value,
1622 QualType DestType, APFloat &Result) {
1623 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1624 if (Result.convertFromAPInt(Value, Value.isSigned(),
1625 APFloat::rmNearestTiesToEven)
1626 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001627 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001628 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001629}
1630
Richard Smith49ca8aa2013-08-06 07:09:20 +00001631static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1632 APValue &Value, const FieldDecl *FD) {
1633 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1634
1635 if (!Value.isInt()) {
1636 // Trying to store a pointer-cast-to-integer into a bitfield.
1637 // FIXME: In this case, we should provide the diagnostic for casting
1638 // a pointer to an integer.
1639 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1640 Info.Diag(E);
1641 return false;
1642 }
1643
1644 APSInt &Int = Value.getInt();
1645 unsigned OldBitWidth = Int.getBitWidth();
1646 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1647 if (NewBitWidth < OldBitWidth)
1648 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1649 return true;
1650}
1651
Eli Friedman803acb32011-12-22 03:51:45 +00001652static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1653 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001654 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001655 if (!Evaluate(SVal, Info, E))
1656 return false;
1657 if (SVal.isInt()) {
1658 Res = SVal.getInt();
1659 return true;
1660 }
1661 if (SVal.isFloat()) {
1662 Res = SVal.getFloat().bitcastToAPInt();
1663 return true;
1664 }
1665 if (SVal.isVector()) {
1666 QualType VecTy = E->getType();
1667 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1668 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1669 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1670 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1671 Res = llvm::APInt::getNullValue(VecSize);
1672 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1673 APValue &Elt = SVal.getVectorElt(i);
1674 llvm::APInt EltAsInt;
1675 if (Elt.isInt()) {
1676 EltAsInt = Elt.getInt();
1677 } else if (Elt.isFloat()) {
1678 EltAsInt = Elt.getFloat().bitcastToAPInt();
1679 } else {
1680 // Don't try to handle vectors of anything other than int or float
1681 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001682 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001683 return false;
1684 }
1685 unsigned BaseEltSize = EltAsInt.getBitWidth();
1686 if (BigEndian)
1687 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1688 else
1689 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1690 }
1691 return true;
1692 }
1693 // Give up if the input isn't an int, float, or vector. For example, we
1694 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001695 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001696 return false;
1697}
1698
Richard Smith43e77732013-05-07 04:50:00 +00001699/// Perform the given integer operation, which is known to need at most BitWidth
1700/// bits, and check for overflow in the original type (if that type was not an
1701/// unsigned type).
1702template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001703static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1704 const APSInt &LHS, const APSInt &RHS,
1705 unsigned BitWidth, Operation Op,
1706 APSInt &Result) {
1707 if (LHS.isUnsigned()) {
1708 Result = Op(LHS, RHS);
1709 return true;
1710 }
Richard Smith43e77732013-05-07 04:50:00 +00001711
1712 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001713 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001714 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001715 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001716 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001717 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001718 << Result.toString(10) << E->getType();
1719 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001720 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001721 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001722 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001723}
1724
1725/// Perform the given binary integer operation.
1726static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1727 BinaryOperatorKind Opcode, APSInt RHS,
1728 APSInt &Result) {
1729 switch (Opcode) {
1730 default:
1731 Info.Diag(E);
1732 return false;
1733 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001734 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1735 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001736 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001737 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1738 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001739 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001740 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1741 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001742 case BO_And: Result = LHS & RHS; return true;
1743 case BO_Xor: Result = LHS ^ RHS; return true;
1744 case BO_Or: Result = LHS | RHS; return true;
1745 case BO_Div:
1746 case BO_Rem:
1747 if (RHS == 0) {
1748 Info.Diag(E, diag::note_expr_divide_by_zero);
1749 return false;
1750 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001751 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1752 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1753 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001754 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1755 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001756 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1757 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001758 return true;
1759 case BO_Shl: {
1760 if (Info.getLangOpts().OpenCL)
1761 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1762 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1763 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1764 RHS.isUnsigned());
1765 else if (RHS.isSigned() && RHS.isNegative()) {
1766 // During constant-folding, a negative shift is an opposite shift. Such
1767 // a shift is not a constant expression.
1768 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1769 RHS = -RHS;
1770 goto shift_right;
1771 }
1772 shift_left:
1773 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1774 // the shifted type.
1775 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1776 if (SA != RHS) {
1777 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1778 << RHS << E->getType() << LHS.getBitWidth();
1779 } else if (LHS.isSigned()) {
1780 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1781 // operand, and must not overflow the corresponding unsigned type.
1782 if (LHS.isNegative())
1783 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1784 else if (LHS.countLeadingZeros() < SA)
1785 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1786 }
1787 Result = LHS << SA;
1788 return true;
1789 }
1790 case BO_Shr: {
1791 if (Info.getLangOpts().OpenCL)
1792 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1793 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1794 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1795 RHS.isUnsigned());
1796 else if (RHS.isSigned() && RHS.isNegative()) {
1797 // During constant-folding, a negative shift is an opposite shift. Such a
1798 // shift is not a constant expression.
1799 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1800 RHS = -RHS;
1801 goto shift_left;
1802 }
1803 shift_right:
1804 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1805 // shifted type.
1806 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1807 if (SA != RHS)
1808 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1809 << RHS << E->getType() << LHS.getBitWidth();
1810 Result = LHS >> SA;
1811 return true;
1812 }
1813
1814 case BO_LT: Result = LHS < RHS; return true;
1815 case BO_GT: Result = LHS > RHS; return true;
1816 case BO_LE: Result = LHS <= RHS; return true;
1817 case BO_GE: Result = LHS >= RHS; return true;
1818 case BO_EQ: Result = LHS == RHS; return true;
1819 case BO_NE: Result = LHS != RHS; return true;
1820 }
1821}
1822
Richard Smith861b5b52013-05-07 23:34:45 +00001823/// Perform the given binary floating-point operation, in-place, on LHS.
1824static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1825 APFloat &LHS, BinaryOperatorKind Opcode,
1826 const APFloat &RHS) {
1827 switch (Opcode) {
1828 default:
1829 Info.Diag(E);
1830 return false;
1831 case BO_Mul:
1832 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1833 break;
1834 case BO_Add:
1835 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1836 break;
1837 case BO_Sub:
1838 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1839 break;
1840 case BO_Div:
1841 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1842 break;
1843 }
1844
Richard Smith0c6124b2015-12-03 01:36:22 +00001845 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001846 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001847 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001848 }
Richard Smith861b5b52013-05-07 23:34:45 +00001849 return true;
1850}
1851
Richard Smitha8105bc2012-01-06 16:39:00 +00001852/// Cast an lvalue referring to a base subobject to a derived class, by
1853/// truncating the lvalue's path to the given length.
1854static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1855 const RecordDecl *TruncatedType,
1856 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001857 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001858
1859 // Check we actually point to a derived class object.
1860 if (TruncatedElements == D.Entries.size())
1861 return true;
1862 assert(TruncatedElements >= D.MostDerivedPathLength &&
1863 "not casting to a derived class");
1864 if (!Result.checkSubobject(Info, E, CSK_Derived))
1865 return false;
1866
1867 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001868 const RecordDecl *RD = TruncatedType;
1869 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001870 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001871 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1872 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001873 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001874 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001875 else
Richard Smithd62306a2011-11-10 06:34:14 +00001876 Result.Offset -= Layout.getBaseClassOffset(Base);
1877 RD = Base;
1878 }
Richard Smith027bf112011-11-17 22:56:20 +00001879 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001880 return true;
1881}
1882
John McCalld7bca762012-05-01 00:38:49 +00001883static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001884 const CXXRecordDecl *Derived,
1885 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001886 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001887 if (!RL) {
1888 if (Derived->isInvalidDecl()) return false;
1889 RL = &Info.Ctx.getASTRecordLayout(Derived);
1890 }
1891
Richard Smithd62306a2011-11-10 06:34:14 +00001892 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001893 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001894 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001895}
1896
Richard Smitha8105bc2012-01-06 16:39:00 +00001897static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001898 const CXXRecordDecl *DerivedDecl,
1899 const CXXBaseSpecifier *Base) {
1900 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1901
John McCalld7bca762012-05-01 00:38:49 +00001902 if (!Base->isVirtual())
1903 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001904
Richard Smitha8105bc2012-01-06 16:39:00 +00001905 SubobjectDesignator &D = Obj.Designator;
1906 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001907 return false;
1908
Richard Smitha8105bc2012-01-06 16:39:00 +00001909 // Extract most-derived object and corresponding type.
1910 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1911 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1912 return false;
1913
1914 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001915 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001916 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1917 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001918 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001919 return true;
1920}
1921
Richard Smith84401042013-06-03 05:03:02 +00001922static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1923 QualType Type, LValue &Result) {
1924 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1925 PathE = E->path_end();
1926 PathI != PathE; ++PathI) {
1927 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1928 *PathI))
1929 return false;
1930 Type = (*PathI)->getType();
1931 }
1932 return true;
1933}
1934
Richard Smithd62306a2011-11-10 06:34:14 +00001935/// Update LVal to refer to the given field, which must be a member of the type
1936/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001937static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001938 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001939 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001940 if (!RL) {
1941 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001942 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001943 }
Richard Smithd62306a2011-11-10 06:34:14 +00001944
1945 unsigned I = FD->getFieldIndex();
1946 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001947 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001948 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001949}
1950
Richard Smith1b78b3d2012-01-25 22:15:11 +00001951/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001952static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001953 LValue &LVal,
1954 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001955 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001956 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001957 return false;
1958 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001959}
1960
Richard Smithd62306a2011-11-10 06:34:14 +00001961/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001962static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1963 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001964 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1965 // extension.
1966 if (Type->isVoidType() || Type->isFunctionType()) {
1967 Size = CharUnits::One();
1968 return true;
1969 }
1970
1971 if (!Type->isConstantSizeType()) {
1972 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001973 // FIXME: Better diagnostic.
1974 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001975 return false;
1976 }
1977
1978 Size = Info.Ctx.getTypeSizeInChars(Type);
1979 return true;
1980}
1981
1982/// Update a pointer value to model pointer arithmetic.
1983/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001984/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001985/// \param LVal - The pointer value to be updated.
1986/// \param EltTy - The pointee type represented by LVal.
1987/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001988static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1989 LValue &LVal, QualType EltTy,
1990 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001991 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001992 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001993 return false;
1994
1995 // Compute the new offset in the appropriate width.
1996 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001997 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001998 return true;
1999}
2000
Richard Smith66c96992012-02-18 22:04:06 +00002001/// Update an lvalue to refer to a component of a complex number.
2002/// \param Info - Information about the ongoing evaluation.
2003/// \param LVal - The lvalue to be updated.
2004/// \param EltTy - The complex number's component type.
2005/// \param Imag - False for the real component, true for the imaginary.
2006static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2007 LValue &LVal, QualType EltTy,
2008 bool Imag) {
2009 if (Imag) {
2010 CharUnits SizeOfComponent;
2011 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2012 return false;
2013 LVal.Offset += SizeOfComponent;
2014 }
2015 LVal.addComplex(Info, E, EltTy, Imag);
2016 return true;
2017}
2018
Richard Smith27908702011-10-24 17:54:18 +00002019/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002020///
2021/// \param Info Information about the ongoing evaluation.
2022/// \param E An expression to be used when printing diagnostics.
2023/// \param VD The variable whose initializer should be obtained.
2024/// \param Frame The frame in which the variable was created. Must be null
2025/// if this variable is not local to the evaluation.
2026/// \param Result Filled in with a pointer to the value of the variable.
2027static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2028 const VarDecl *VD, CallStackFrame *Frame,
2029 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002030 // If this is a parameter to an active constexpr function call, perform
2031 // argument substitution.
2032 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002033 // Assume arguments of a potential constant expression are unknown
2034 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002035 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002036 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002037 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002038 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002039 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002040 }
Richard Smith3229b742013-05-05 21:17:10 +00002041 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002042 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002043 }
Richard Smith27908702011-10-24 17:54:18 +00002044
Richard Smithd9f663b2013-04-22 15:31:51 +00002045 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002046 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002047 Result = Frame->getTemporary(VD);
2048 assert(Result && "missing value for local variable");
2049 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002050 }
2051
Richard Smithd0b4dd62011-12-19 06:19:21 +00002052 // Dig out the initializer, and use the declaration which it's attached to.
2053 const Expr *Init = VD->getAnyInitializer(VD);
2054 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002055 // If we're checking a potential constant expression, the variable could be
2056 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002057 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002058 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002059 return false;
2060 }
2061
Richard Smithd62306a2011-11-10 06:34:14 +00002062 // If we're currently evaluating the initializer of this declaration, use that
2063 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002064 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002065 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002066 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002067 }
2068
Richard Smithcecf1842011-11-01 21:06:14 +00002069 // Never evaluate the initializer of a weak variable. We can't be sure that
2070 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002071 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002072 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002073 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002074 }
Richard Smithcecf1842011-11-01 21:06:14 +00002075
Richard Smithd0b4dd62011-12-19 06:19:21 +00002076 // Check that we can fold the initializer. In C++, we will have already done
2077 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002078 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002079 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002080 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002081 Notes.size() + 1) << VD;
2082 Info.Note(VD->getLocation(), diag::note_declared_at);
2083 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002084 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002085 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002086 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002087 Notes.size() + 1) << VD;
2088 Info.Note(VD->getLocation(), diag::note_declared_at);
2089 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 }
Richard Smith27908702011-10-24 17:54:18 +00002091
Richard Smith3229b742013-05-05 21:17:10 +00002092 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002093 return true;
Richard Smith27908702011-10-24 17:54:18 +00002094}
2095
Richard Smith11562c52011-10-28 17:51:58 +00002096static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002097 Qualifiers Quals = T.getQualifiers();
2098 return Quals.hasConst() && !Quals.hasVolatile();
2099}
2100
Richard Smithe97cbd72011-11-11 04:05:33 +00002101/// Get the base index of the given base class within an APValue representing
2102/// the given derived class.
2103static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2104 const CXXRecordDecl *Base) {
2105 Base = Base->getCanonicalDecl();
2106 unsigned Index = 0;
2107 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2108 E = Derived->bases_end(); I != E; ++I, ++Index) {
2109 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2110 return Index;
2111 }
2112
2113 llvm_unreachable("base class missing from derived class's bases list");
2114}
2115
Richard Smith3da88fa2013-04-26 14:36:30 +00002116/// Extract the value of a character from a string literal.
2117static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2118 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002119 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2120 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2121 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002122 const StringLiteral *S = cast<StringLiteral>(Lit);
2123 const ConstantArrayType *CAT =
2124 Info.Ctx.getAsConstantArrayType(S->getType());
2125 assert(CAT && "string literal isn't an array");
2126 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002127 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002128
2129 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002130 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002131 if (Index < S->getLength())
2132 Value = S->getCodeUnit(Index);
2133 return Value;
2134}
2135
Richard Smith3da88fa2013-04-26 14:36:30 +00002136// Expand a string literal into an array of characters.
2137static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2138 APValue &Result) {
2139 const StringLiteral *S = cast<StringLiteral>(Lit);
2140 const ConstantArrayType *CAT =
2141 Info.Ctx.getAsConstantArrayType(S->getType());
2142 assert(CAT && "string literal isn't an array");
2143 QualType CharType = CAT->getElementType();
2144 assert(CharType->isIntegerType() && "unexpected character type");
2145
2146 unsigned Elts = CAT->getSize().getZExtValue();
2147 Result = APValue(APValue::UninitArray(),
2148 std::min(S->getLength(), Elts), Elts);
2149 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2150 CharType->isUnsignedIntegerType());
2151 if (Result.hasArrayFiller())
2152 Result.getArrayFiller() = APValue(Value);
2153 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2154 Value = S->getCodeUnit(I);
2155 Result.getArrayInitializedElt(I) = APValue(Value);
2156 }
2157}
2158
2159// Expand an array so that it has more than Index filled elements.
2160static void expandArray(APValue &Array, unsigned Index) {
2161 unsigned Size = Array.getArraySize();
2162 assert(Index < Size);
2163
2164 // Always at least double the number of elements for which we store a value.
2165 unsigned OldElts = Array.getArrayInitializedElts();
2166 unsigned NewElts = std::max(Index+1, OldElts * 2);
2167 NewElts = std::min(Size, std::max(NewElts, 8u));
2168
2169 // Copy the data across.
2170 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2171 for (unsigned I = 0; I != OldElts; ++I)
2172 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2173 for (unsigned I = OldElts; I != NewElts; ++I)
2174 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2175 if (NewValue.hasArrayFiller())
2176 NewValue.getArrayFiller() = Array.getArrayFiller();
2177 Array.swap(NewValue);
2178}
2179
Richard Smithb01fe402014-09-16 01:24:02 +00002180/// Determine whether a type would actually be read by an lvalue-to-rvalue
2181/// conversion. If it's of class type, we may assume that the copy operation
2182/// is trivial. Note that this is never true for a union type with fields
2183/// (because the copy always "reads" the active member) and always true for
2184/// a non-class type.
2185static bool isReadByLvalueToRvalueConversion(QualType T) {
2186 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2187 if (!RD || (RD->isUnion() && !RD->field_empty()))
2188 return true;
2189 if (RD->isEmpty())
2190 return false;
2191
2192 for (auto *Field : RD->fields())
2193 if (isReadByLvalueToRvalueConversion(Field->getType()))
2194 return true;
2195
2196 for (auto &BaseSpec : RD->bases())
2197 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2198 return true;
2199
2200 return false;
2201}
2202
2203/// Diagnose an attempt to read from any unreadable field within the specified
2204/// type, which might be a class type.
2205static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2206 QualType T) {
2207 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2208 if (!RD)
2209 return false;
2210
2211 if (!RD->hasMutableFields())
2212 return false;
2213
2214 for (auto *Field : RD->fields()) {
2215 // If we're actually going to read this field in some way, then it can't
2216 // be mutable. If we're in a union, then assigning to a mutable field
2217 // (even an empty one) can change the active member, so that's not OK.
2218 // FIXME: Add core issue number for the union case.
2219 if (Field->isMutable() &&
2220 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2221 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2222 Info.Note(Field->getLocation(), diag::note_declared_at);
2223 return true;
2224 }
2225
2226 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2227 return true;
2228 }
2229
2230 for (auto &BaseSpec : RD->bases())
2231 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2232 return true;
2233
2234 // All mutable fields were empty, and thus not actually read.
2235 return false;
2236}
2237
Richard Smith861b5b52013-05-07 23:34:45 +00002238/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002239enum AccessKinds {
2240 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002241 AK_Assign,
2242 AK_Increment,
2243 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002244};
2245
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002246namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002247/// A handle to a complete object (an object that is not a subobject of
2248/// another object).
2249struct CompleteObject {
2250 /// The value of the complete object.
2251 APValue *Value;
2252 /// The type of the complete object.
2253 QualType Type;
2254
Craig Topper36250ad2014-05-12 05:36:57 +00002255 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002256 CompleteObject(APValue *Value, QualType Type)
2257 : Value(Value), Type(Type) {
2258 assert(Value && "missing value for complete object");
2259 }
2260
Aaron Ballman67347662015-02-15 22:00:28 +00002261 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002262};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002263} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002264
Richard Smith3da88fa2013-04-26 14:36:30 +00002265/// Find the designated sub-object of an rvalue.
2266template<typename SubobjectHandler>
2267typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002268findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002269 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002270 if (Sub.Invalid)
2271 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002272 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002273 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002274 if (Info.getLangOpts().CPlusPlus11)
2275 Info.Diag(E, diag::note_constexpr_access_past_end)
2276 << handler.AccessKind;
2277 else
2278 Info.Diag(E);
2279 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002280 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002281
Richard Smith3229b742013-05-05 21:17:10 +00002282 APValue *O = Obj.Value;
2283 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002284 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002285
Richard Smithd62306a2011-11-10 06:34:14 +00002286 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002287 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2288 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002289 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002290 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2291 return handler.failed();
2292 }
2293
Richard Smith49ca8aa2013-08-06 07:09:20 +00002294 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002295 // If we are reading an object of class type, there may still be more
2296 // things we need to check: if there are any mutable subobjects, we
2297 // cannot perform this read. (This only happens when performing a trivial
2298 // copy or assignment.)
2299 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2300 diagnoseUnreadableFields(Info, E, ObjType))
2301 return handler.failed();
2302
Richard Smith49ca8aa2013-08-06 07:09:20 +00002303 if (!handler.found(*O, ObjType))
2304 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002305
Richard Smith49ca8aa2013-08-06 07:09:20 +00002306 // If we modified a bit-field, truncate it to the right width.
2307 if (handler.AccessKind != AK_Read &&
2308 LastField && LastField->isBitField() &&
2309 !truncateBitfieldValue(Info, E, *O, LastField))
2310 return false;
2311
2312 return true;
2313 }
2314
Craig Topper36250ad2014-05-12 05:36:57 +00002315 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002316 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002317 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002318 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002319 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002320 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002321 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002322 // Note, it should not be possible to form a pointer with a valid
2323 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002324 if (Info.getLangOpts().CPlusPlus11)
2325 Info.Diag(E, diag::note_constexpr_access_past_end)
2326 << handler.AccessKind;
2327 else
2328 Info.Diag(E);
2329 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002330 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002331
2332 ObjType = CAT->getElementType();
2333
Richard Smith14a94132012-02-17 03:35:37 +00002334 // An array object is represented as either an Array APValue or as an
2335 // LValue which refers to a string literal.
2336 if (O->isLValue()) {
2337 assert(I == N - 1 && "extracting subobject of character?");
2338 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002339 if (handler.AccessKind != AK_Read)
2340 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2341 *O);
2342 else
2343 return handler.foundString(*O, ObjType, Index);
2344 }
2345
2346 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002347 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002348 else if (handler.AccessKind != AK_Read) {
2349 expandArray(*O, Index);
2350 O = &O->getArrayInitializedElt(Index);
2351 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002352 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002353 } else if (ObjType->isAnyComplexType()) {
2354 // Next subobject is a complex number.
2355 uint64_t Index = Sub.Entries[I].ArrayIndex;
2356 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002357 if (Info.getLangOpts().CPlusPlus11)
2358 Info.Diag(E, diag::note_constexpr_access_past_end)
2359 << handler.AccessKind;
2360 else
2361 Info.Diag(E);
2362 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002363 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002364
2365 bool WasConstQualified = ObjType.isConstQualified();
2366 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2367 if (WasConstQualified)
2368 ObjType.addConst();
2369
Richard Smith66c96992012-02-18 22:04:06 +00002370 assert(I == N - 1 && "extracting subobject of scalar?");
2371 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002372 return handler.found(Index ? O->getComplexIntImag()
2373 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002374 } else {
2375 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002376 return handler.found(Index ? O->getComplexFloatImag()
2377 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002378 }
Richard Smithd62306a2011-11-10 06:34:14 +00002379 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002380 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002381 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002382 << Field;
2383 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002384 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002385 }
2386
Richard Smithd62306a2011-11-10 06:34:14 +00002387 // Next subobject is a class, struct or union field.
2388 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2389 if (RD->isUnion()) {
2390 const FieldDecl *UnionField = O->getUnionField();
2391 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002392 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002393 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2394 << handler.AccessKind << Field << !UnionField << UnionField;
2395 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002396 }
Richard Smithd62306a2011-11-10 06:34:14 +00002397 O = &O->getUnionValue();
2398 } else
2399 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002400
2401 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002402 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002403 if (WasConstQualified && !Field->isMutable())
2404 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002405
2406 if (ObjType.isVolatileQualified()) {
2407 if (Info.getLangOpts().CPlusPlus) {
2408 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002409 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2410 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002411 Info.Note(Field->getLocation(), diag::note_declared_at);
2412 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002413 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002414 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002415 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002416 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002417
2418 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002419 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002420 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002421 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2422 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2423 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002424
2425 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002426 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002427 if (WasConstQualified)
2428 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002429 }
2430 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002431}
2432
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002433namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002434struct ExtractSubobjectHandler {
2435 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002436 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002437
2438 static const AccessKinds AccessKind = AK_Read;
2439
2440 typedef bool result_type;
2441 bool failed() { return false; }
2442 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002443 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002444 return true;
2445 }
2446 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002447 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002448 return true;
2449 }
2450 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002451 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 return true;
2453 }
2454 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002455 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002456 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2457 return true;
2458 }
2459};
Richard Smith3229b742013-05-05 21:17:10 +00002460} // end anonymous namespace
2461
Richard Smith3da88fa2013-04-26 14:36:30 +00002462const AccessKinds ExtractSubobjectHandler::AccessKind;
2463
2464/// Extract the designated sub-object of an rvalue.
2465static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002466 const CompleteObject &Obj,
2467 const SubobjectDesignator &Sub,
2468 APValue &Result) {
2469 ExtractSubobjectHandler Handler = { Info, Result };
2470 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002471}
2472
Richard Smith3229b742013-05-05 21:17:10 +00002473namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002474struct ModifySubobjectHandler {
2475 EvalInfo &Info;
2476 APValue &NewVal;
2477 const Expr *E;
2478
2479 typedef bool result_type;
2480 static const AccessKinds AccessKind = AK_Assign;
2481
2482 bool checkConst(QualType QT) {
2483 // Assigning to a const object has undefined behavior.
2484 if (QT.isConstQualified()) {
2485 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2486 return false;
2487 }
2488 return true;
2489 }
2490
2491 bool failed() { return false; }
2492 bool found(APValue &Subobj, QualType SubobjType) {
2493 if (!checkConst(SubobjType))
2494 return false;
2495 // We've been given ownership of NewVal, so just swap it in.
2496 Subobj.swap(NewVal);
2497 return true;
2498 }
2499 bool found(APSInt &Value, QualType SubobjType) {
2500 if (!checkConst(SubobjType))
2501 return false;
2502 if (!NewVal.isInt()) {
2503 // Maybe trying to write a cast pointer value into a complex?
2504 Info.Diag(E);
2505 return false;
2506 }
2507 Value = NewVal.getInt();
2508 return true;
2509 }
2510 bool found(APFloat &Value, QualType SubobjType) {
2511 if (!checkConst(SubobjType))
2512 return false;
2513 Value = NewVal.getFloat();
2514 return true;
2515 }
2516 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2517 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2518 }
2519};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002520} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002521
Richard Smith3229b742013-05-05 21:17:10 +00002522const AccessKinds ModifySubobjectHandler::AccessKind;
2523
Richard Smith3da88fa2013-04-26 14:36:30 +00002524/// Update the designated sub-object of an rvalue to the given value.
2525static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002526 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002527 const SubobjectDesignator &Sub,
2528 APValue &NewVal) {
2529 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002530 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002531}
2532
Richard Smith84f6dcf2012-02-02 01:16:57 +00002533/// Find the position where two subobject designators diverge, or equivalently
2534/// the length of the common initial subsequence.
2535static unsigned FindDesignatorMismatch(QualType ObjType,
2536 const SubobjectDesignator &A,
2537 const SubobjectDesignator &B,
2538 bool &WasArrayIndex) {
2539 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2540 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002541 if (!ObjType.isNull() &&
2542 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002543 // Next subobject is an array element.
2544 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2545 WasArrayIndex = true;
2546 return I;
2547 }
Richard Smith66c96992012-02-18 22:04:06 +00002548 if (ObjType->isAnyComplexType())
2549 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2550 else
2551 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002552 } else {
2553 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2554 WasArrayIndex = false;
2555 return I;
2556 }
2557 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2558 // Next subobject is a field.
2559 ObjType = FD->getType();
2560 else
2561 // Next subobject is a base class.
2562 ObjType = QualType();
2563 }
2564 }
2565 WasArrayIndex = false;
2566 return I;
2567}
2568
2569/// Determine whether the given subobject designators refer to elements of the
2570/// same array object.
2571static bool AreElementsOfSameArray(QualType ObjType,
2572 const SubobjectDesignator &A,
2573 const SubobjectDesignator &B) {
2574 if (A.Entries.size() != B.Entries.size())
2575 return false;
2576
George Burgess IVa51c4072015-10-16 01:49:01 +00002577 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002578 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2579 // A is a subobject of the array element.
2580 return false;
2581
2582 // If A (and B) designates an array element, the last entry will be the array
2583 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2584 // of length 1' case, and the entire path must match.
2585 bool WasArrayIndex;
2586 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2587 return CommonLength >= A.Entries.size() - IsArray;
2588}
2589
Richard Smith3229b742013-05-05 21:17:10 +00002590/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002591static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2592 AccessKinds AK, const LValue &LVal,
2593 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002594 if (!LVal.Base) {
2595 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2596 return CompleteObject();
2597 }
2598
Craig Topper36250ad2014-05-12 05:36:57 +00002599 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002600 if (LVal.CallIndex) {
2601 Frame = Info.getCallFrame(LVal.CallIndex);
2602 if (!Frame) {
2603 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2604 << AK << LVal.Base.is<const ValueDecl*>();
2605 NoteLValueLocation(Info, LVal.Base);
2606 return CompleteObject();
2607 }
Richard Smith3229b742013-05-05 21:17:10 +00002608 }
2609
2610 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2611 // is not a constant expression (even if the object is non-volatile). We also
2612 // apply this rule to C++98, in order to conform to the expected 'volatile'
2613 // semantics.
2614 if (LValType.isVolatileQualified()) {
2615 if (Info.getLangOpts().CPlusPlus)
2616 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2617 << AK << LValType;
2618 else
2619 Info.Diag(E);
2620 return CompleteObject();
2621 }
2622
2623 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002624 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002625 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002626
2627 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2628 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2629 // In C++11, constexpr, non-volatile variables initialized with constant
2630 // expressions are constant expressions too. Inside constexpr functions,
2631 // parameters are constant expressions even if they're non-const.
2632 // In C++1y, objects local to a constant expression (those with a Frame) are
2633 // both readable and writable inside constant expressions.
2634 // In C, such things can also be folded, although they are not ICEs.
2635 const VarDecl *VD = dyn_cast<VarDecl>(D);
2636 if (VD) {
2637 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2638 VD = VDef;
2639 }
2640 if (!VD || VD->isInvalidDecl()) {
2641 Info.Diag(E);
2642 return CompleteObject();
2643 }
2644
2645 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002646 if (BaseType.isVolatileQualified()) {
2647 if (Info.getLangOpts().CPlusPlus) {
2648 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2649 << AK << 1 << VD;
2650 Info.Note(VD->getLocation(), diag::note_declared_at);
2651 } else {
2652 Info.Diag(E);
2653 }
2654 return CompleteObject();
2655 }
2656
2657 // Unless we're looking at a local variable or argument in a constexpr call,
2658 // the variable we're reading must be const.
2659 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002660 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002661 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2662 // OK, we can read and modify an object if we're in the process of
2663 // evaluating its initializer, because its lifetime began in this
2664 // evaluation.
2665 } else if (AK != AK_Read) {
2666 // All the remaining cases only permit reading.
2667 Info.Diag(E, diag::note_constexpr_modify_global);
2668 return CompleteObject();
2669 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002670 // OK, we can read this variable.
2671 } else if (BaseType->isIntegralOrEnumerationType()) {
2672 if (!BaseType.isConstQualified()) {
2673 if (Info.getLangOpts().CPlusPlus) {
2674 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2675 Info.Note(VD->getLocation(), diag::note_declared_at);
2676 } else {
2677 Info.Diag(E);
2678 }
2679 return CompleteObject();
2680 }
2681 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2682 // We support folding of const floating-point types, in order to make
2683 // static const data members of such types (supported as an extension)
2684 // more useful.
2685 if (Info.getLangOpts().CPlusPlus11) {
2686 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2687 Info.Note(VD->getLocation(), diag::note_declared_at);
2688 } else {
2689 Info.CCEDiag(E);
2690 }
2691 } else {
2692 // FIXME: Allow folding of values of any literal type in all languages.
2693 if (Info.getLangOpts().CPlusPlus11) {
2694 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2695 Info.Note(VD->getLocation(), diag::note_declared_at);
2696 } else {
2697 Info.Diag(E);
2698 }
2699 return CompleteObject();
2700 }
2701 }
2702
2703 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2704 return CompleteObject();
2705 } else {
2706 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2707
2708 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002709 if (const MaterializeTemporaryExpr *MTE =
2710 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2711 assert(MTE->getStorageDuration() == SD_Static &&
2712 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002713
Richard Smithe6c01442013-06-05 00:46:14 +00002714 // Per C++1y [expr.const]p2:
2715 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2716 // - a [...] glvalue of integral or enumeration type that refers to
2717 // a non-volatile const object [...]
2718 // [...]
2719 // - a [...] glvalue of literal type that refers to a non-volatile
2720 // object whose lifetime began within the evaluation of e.
2721 //
2722 // C++11 misses the 'began within the evaluation of e' check and
2723 // instead allows all temporaries, including things like:
2724 // int &&r = 1;
2725 // int x = ++r;
2726 // constexpr int k = r;
2727 // Therefore we use the C++1y rules in C++11 too.
2728 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2729 const ValueDecl *ED = MTE->getExtendingDecl();
2730 if (!(BaseType.isConstQualified() &&
2731 BaseType->isIntegralOrEnumerationType()) &&
2732 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2733 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2734 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2735 return CompleteObject();
2736 }
2737
2738 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2739 assert(BaseVal && "got reference to unevaluated temporary");
2740 } else {
2741 Info.Diag(E);
2742 return CompleteObject();
2743 }
2744 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002745 BaseVal = Frame->getTemporary(Base);
2746 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002747 }
Richard Smith3229b742013-05-05 21:17:10 +00002748
2749 // Volatile temporary objects cannot be accessed in constant expressions.
2750 if (BaseType.isVolatileQualified()) {
2751 if (Info.getLangOpts().CPlusPlus) {
2752 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2753 << AK << 0;
2754 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2755 } else {
2756 Info.Diag(E);
2757 }
2758 return CompleteObject();
2759 }
2760 }
2761
Richard Smith7525ff62013-05-09 07:14:00 +00002762 // During the construction of an object, it is not yet 'const'.
2763 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2764 // and this doesn't do quite the right thing for const subobjects of the
2765 // object under construction.
2766 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2767 BaseType = Info.Ctx.getCanonicalType(BaseType);
2768 BaseType.removeLocalConst();
2769 }
2770
Richard Smith6d4c6582013-11-05 22:18:15 +00002771 // In C++1y, we can't safely access any mutable state when we might be
2772 // evaluating after an unmodeled side effect or an evaluation failure.
2773 //
2774 // FIXME: Not all local state is mutable. Allow local constant subobjects
2775 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002776 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002777 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002778 return CompleteObject();
2779
2780 return CompleteObject(BaseVal, BaseType);
2781}
2782
Richard Smith243ef902013-05-05 23:31:59 +00002783/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2784/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2785/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002786///
2787/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002788/// \param Conv - The expression for which we are performing the conversion.
2789/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002790/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2791/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002792/// \param LVal - The glvalue on which we are attempting to perform this action.
2793/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002794static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002795 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002796 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002797 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002798 return false;
2799
Richard Smith3229b742013-05-05 21:17:10 +00002800 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002801 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002802 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002803 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2804 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2805 // initializer until now for such expressions. Such an expression can't be
2806 // an ICE in C, so this only matters for fold.
2807 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2808 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002809 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002810 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002811 }
Richard Smith3229b742013-05-05 21:17:10 +00002812 APValue Lit;
2813 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2814 return false;
2815 CompleteObject LitObj(&Lit, Base->getType());
2816 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002817 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002818 // We represent a string literal array as an lvalue pointing at the
2819 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002820 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002821 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2822 CompleteObject StrObj(&Str, Base->getType());
2823 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002824 }
Richard Smith11562c52011-10-28 17:51:58 +00002825 }
2826
Richard Smith3229b742013-05-05 21:17:10 +00002827 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2828 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002829}
2830
2831/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002832static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002835 return false;
2836
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002837 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002838 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 return false;
2840 }
2841
Richard Smith3229b742013-05-05 21:17:10 +00002842 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2843 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002844}
2845
Richard Smith243ef902013-05-05 23:31:59 +00002846static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2847 return T->isSignedIntegerType() &&
2848 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2849}
2850
2851namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002852struct CompoundAssignSubobjectHandler {
2853 EvalInfo &Info;
2854 const Expr *E;
2855 QualType PromotedLHSType;
2856 BinaryOperatorKind Opcode;
2857 const APValue &RHS;
2858
2859 static const AccessKinds AccessKind = AK_Assign;
2860
2861 typedef bool result_type;
2862
2863 bool checkConst(QualType QT) {
2864 // Assigning to a const object has undefined behavior.
2865 if (QT.isConstQualified()) {
2866 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2867 return false;
2868 }
2869 return true;
2870 }
2871
2872 bool failed() { return false; }
2873 bool found(APValue &Subobj, QualType SubobjType) {
2874 switch (Subobj.getKind()) {
2875 case APValue::Int:
2876 return found(Subobj.getInt(), SubobjType);
2877 case APValue::Float:
2878 return found(Subobj.getFloat(), SubobjType);
2879 case APValue::ComplexInt:
2880 case APValue::ComplexFloat:
2881 // FIXME: Implement complex compound assignment.
2882 Info.Diag(E);
2883 return false;
2884 case APValue::LValue:
2885 return foundPointer(Subobj, SubobjType);
2886 default:
2887 // FIXME: can this happen?
2888 Info.Diag(E);
2889 return false;
2890 }
2891 }
2892 bool found(APSInt &Value, QualType SubobjType) {
2893 if (!checkConst(SubobjType))
2894 return false;
2895
2896 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2897 // We don't support compound assignment on integer-cast-to-pointer
2898 // values.
2899 Info.Diag(E);
2900 return false;
2901 }
2902
2903 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2904 SubobjType, Value);
2905 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2906 return false;
2907 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2908 return true;
2909 }
2910 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002911 return checkConst(SubobjType) &&
2912 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2913 Value) &&
2914 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2915 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002916 }
2917 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2918 if (!checkConst(SubobjType))
2919 return false;
2920
2921 QualType PointeeType;
2922 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2923 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002924
2925 if (PointeeType.isNull() || !RHS.isInt() ||
2926 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002927 Info.Diag(E);
2928 return false;
2929 }
2930
Richard Smith861b5b52013-05-07 23:34:45 +00002931 int64_t Offset = getExtValue(RHS.getInt());
2932 if (Opcode == BO_Sub)
2933 Offset = -Offset;
2934
2935 LValue LVal;
2936 LVal.setFrom(Info.Ctx, Subobj);
2937 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2938 return false;
2939 LVal.moveInto(Subobj);
2940 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002941 }
2942 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2943 llvm_unreachable("shouldn't encounter string elements here");
2944 }
2945};
2946} // end anonymous namespace
2947
2948const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2949
2950/// Perform a compound assignment of LVal <op>= RVal.
2951static bool handleCompoundAssignment(
2952 EvalInfo &Info, const Expr *E,
2953 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2954 BinaryOperatorKind Opcode, const APValue &RVal) {
2955 if (LVal.Designator.Invalid)
2956 return false;
2957
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002958 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002959 Info.Diag(E);
2960 return false;
2961 }
2962
2963 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2964 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2965 RVal };
2966 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2967}
2968
2969namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002970struct IncDecSubobjectHandler {
2971 EvalInfo &Info;
2972 const Expr *E;
2973 AccessKinds AccessKind;
2974 APValue *Old;
2975
2976 typedef bool result_type;
2977
2978 bool checkConst(QualType QT) {
2979 // Assigning to a const object has undefined behavior.
2980 if (QT.isConstQualified()) {
2981 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2982 return false;
2983 }
2984 return true;
2985 }
2986
2987 bool failed() { return false; }
2988 bool found(APValue &Subobj, QualType SubobjType) {
2989 // Stash the old value. Also clear Old, so we don't clobber it later
2990 // if we're post-incrementing a complex.
2991 if (Old) {
2992 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002993 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002994 }
2995
2996 switch (Subobj.getKind()) {
2997 case APValue::Int:
2998 return found(Subobj.getInt(), SubobjType);
2999 case APValue::Float:
3000 return found(Subobj.getFloat(), SubobjType);
3001 case APValue::ComplexInt:
3002 return found(Subobj.getComplexIntReal(),
3003 SubobjType->castAs<ComplexType>()->getElementType()
3004 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3005 case APValue::ComplexFloat:
3006 return found(Subobj.getComplexFloatReal(),
3007 SubobjType->castAs<ComplexType>()->getElementType()
3008 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3009 case APValue::LValue:
3010 return foundPointer(Subobj, SubobjType);
3011 default:
3012 // FIXME: can this happen?
3013 Info.Diag(E);
3014 return false;
3015 }
3016 }
3017 bool found(APSInt &Value, QualType SubobjType) {
3018 if (!checkConst(SubobjType))
3019 return false;
3020
3021 if (!SubobjType->isIntegerType()) {
3022 // We don't support increment / decrement on integer-cast-to-pointer
3023 // values.
3024 Info.Diag(E);
3025 return false;
3026 }
3027
3028 if (Old) *Old = APValue(Value);
3029
3030 // bool arithmetic promotes to int, and the conversion back to bool
3031 // doesn't reduce mod 2^n, so special-case it.
3032 if (SubobjType->isBooleanType()) {
3033 if (AccessKind == AK_Increment)
3034 Value = 1;
3035 else
3036 Value = !Value;
3037 return true;
3038 }
3039
3040 bool WasNegative = Value.isNegative();
3041 if (AccessKind == AK_Increment) {
3042 ++Value;
3043
3044 if (!WasNegative && Value.isNegative() &&
3045 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3046 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003047 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003048 }
3049 } else {
3050 --Value;
3051
3052 if (WasNegative && !Value.isNegative() &&
3053 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3054 unsigned BitWidth = Value.getBitWidth();
3055 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3056 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003057 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003058 }
3059 }
3060 return true;
3061 }
3062 bool found(APFloat &Value, QualType SubobjType) {
3063 if (!checkConst(SubobjType))
3064 return false;
3065
3066 if (Old) *Old = APValue(Value);
3067
3068 APFloat One(Value.getSemantics(), 1);
3069 if (AccessKind == AK_Increment)
3070 Value.add(One, APFloat::rmNearestTiesToEven);
3071 else
3072 Value.subtract(One, APFloat::rmNearestTiesToEven);
3073 return true;
3074 }
3075 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3076 if (!checkConst(SubobjType))
3077 return false;
3078
3079 QualType PointeeType;
3080 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3081 PointeeType = PT->getPointeeType();
3082 else {
3083 Info.Diag(E);
3084 return false;
3085 }
3086
3087 LValue LVal;
3088 LVal.setFrom(Info.Ctx, Subobj);
3089 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3090 AccessKind == AK_Increment ? 1 : -1))
3091 return false;
3092 LVal.moveInto(Subobj);
3093 return true;
3094 }
3095 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3096 llvm_unreachable("shouldn't encounter string elements here");
3097 }
3098};
3099} // end anonymous namespace
3100
3101/// Perform an increment or decrement on LVal.
3102static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3103 QualType LValType, bool IsIncrement, APValue *Old) {
3104 if (LVal.Designator.Invalid)
3105 return false;
3106
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003107 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003108 Info.Diag(E);
3109 return false;
3110 }
3111
3112 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3113 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3114 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3115 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3116}
3117
Richard Smithe97cbd72011-11-11 04:05:33 +00003118/// Build an lvalue for the object argument of a member function call.
3119static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3120 LValue &This) {
3121 if (Object->getType()->isPointerType())
3122 return EvaluatePointer(Object, This, Info);
3123
3124 if (Object->isGLValue())
3125 return EvaluateLValue(Object, This, Info);
3126
Richard Smithd9f663b2013-04-22 15:31:51 +00003127 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003128 return EvaluateTemporary(Object, This, Info);
3129
Richard Smith3e79a572014-06-11 19:53:12 +00003130 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003131 return false;
3132}
3133
3134/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3135/// lvalue referring to the result.
3136///
3137/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003138/// \param LV - An lvalue referring to the base of the member pointer.
3139/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003140/// \param IncludeMember - Specifies whether the member itself is included in
3141/// the resulting LValue subobject designator. This is not possible when
3142/// creating a bound member function.
3143/// \return The field or method declaration to which the member pointer refers,
3144/// or 0 if evaluation fails.
3145static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003146 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003147 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003148 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003149 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003150 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003151 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003152 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003153
3154 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3155 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003156 if (!MemPtr.getDecl()) {
3157 // FIXME: Specific diagnostic.
3158 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003159 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003160 }
Richard Smith253c2a32012-01-27 01:14:48 +00003161
Richard Smith027bf112011-11-17 22:56:20 +00003162 if (MemPtr.isDerivedMember()) {
3163 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003164 // The end of the derived-to-base path for the base object must match the
3165 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003166 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003167 LV.Designator.Entries.size()) {
3168 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003169 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003170 }
Richard Smith027bf112011-11-17 22:56:20 +00003171 unsigned PathLengthToMember =
3172 LV.Designator.Entries.size() - MemPtr.Path.size();
3173 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3174 const CXXRecordDecl *LVDecl = getAsBaseClass(
3175 LV.Designator.Entries[PathLengthToMember + I]);
3176 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003177 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3178 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003179 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003180 }
Richard Smith027bf112011-11-17 22:56:20 +00003181 }
3182
3183 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003184 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003185 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003186 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003187 } else if (!MemPtr.Path.empty()) {
3188 // Extend the LValue path with the member pointer's path.
3189 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3190 MemPtr.Path.size() + IncludeMember);
3191
3192 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003193 if (const PointerType *PT = LVType->getAs<PointerType>())
3194 LVType = PT->getPointeeType();
3195 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3196 assert(RD && "member pointer access on non-class-type expression");
3197 // The first class in the path is that of the lvalue.
3198 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3199 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003200 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003201 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003202 RD = Base;
3203 }
3204 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003205 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3206 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003207 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003208 }
3209
3210 // Add the member. Note that we cannot build bound member functions here.
3211 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003212 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003213 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003214 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003215 } else if (const IndirectFieldDecl *IFD =
3216 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003217 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003218 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003219 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003220 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003221 }
Richard Smith027bf112011-11-17 22:56:20 +00003222 }
3223
3224 return MemPtr.getDecl();
3225}
3226
Richard Smith84401042013-06-03 05:03:02 +00003227static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3228 const BinaryOperator *BO,
3229 LValue &LV,
3230 bool IncludeMember = true) {
3231 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3232
3233 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3234 if (Info.keepEvaluatingAfterFailure()) {
3235 MemberPtr MemPtr;
3236 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3237 }
Craig Topper36250ad2014-05-12 05:36:57 +00003238 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003239 }
3240
3241 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3242 BO->getRHS(), IncludeMember);
3243}
3244
Richard Smith027bf112011-11-17 22:56:20 +00003245/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3246/// the provided lvalue, which currently refers to the base object.
3247static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3248 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003249 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003250 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003251 return false;
3252
Richard Smitha8105bc2012-01-06 16:39:00 +00003253 QualType TargetQT = E->getType();
3254 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3255 TargetQT = PT->getPointeeType();
3256
3257 // Check this cast lands within the final derived-to-base subobject path.
3258 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003259 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003260 << D.MostDerivedType << TargetQT;
3261 return false;
3262 }
3263
Richard Smith027bf112011-11-17 22:56:20 +00003264 // Check the type of the final cast. We don't need to check the path,
3265 // since a cast can only be formed if the path is unique.
3266 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003267 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3268 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003269 if (NewEntriesSize == D.MostDerivedPathLength)
3270 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3271 else
Richard Smith027bf112011-11-17 22:56:20 +00003272 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003273 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003274 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003275 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003276 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003277 }
Richard Smith027bf112011-11-17 22:56:20 +00003278
3279 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003280 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003281}
3282
Mike Stump876387b2009-10-27 22:09:17 +00003283namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003284enum EvalStmtResult {
3285 /// Evaluation failed.
3286 ESR_Failed,
3287 /// Hit a 'return' statement.
3288 ESR_Returned,
3289 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003290 ESR_Succeeded,
3291 /// Hit a 'continue' statement.
3292 ESR_Continue,
3293 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003294 ESR_Break,
3295 /// Still scanning for 'case' or 'default' statement.
3296 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003297};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003298}
Richard Smith254a73d2011-10-28 22:34:42 +00003299
Richard Smithd9f663b2013-04-22 15:31:51 +00003300static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3301 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3302 // We don't need to evaluate the initializer for a static local.
3303 if (!VD->hasLocalStorage())
3304 return true;
3305
3306 LValue Result;
3307 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003309
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003310 const Expr *InitE = VD->getInit();
3311 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003312 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3313 << false << VD->getType();
3314 Val = APValue();
3315 return false;
3316 }
3317
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003318 if (InitE->isValueDependent())
3319 return false;
3320
3321 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003322 // Wipe out any partially-computed value, to allow tracking that this
3323 // evaluation failed.
3324 Val = APValue();
3325 return false;
3326 }
3327 }
3328
3329 return true;
3330}
3331
Richard Smith4e18ca52013-05-06 05:56:11 +00003332/// Evaluate a condition (either a variable declaration or an expression).
3333static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3334 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003335 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003336 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3337 return false;
3338 return EvaluateAsBooleanCondition(Cond, Result, Info);
3339}
3340
Richard Smith52a980a2015-08-28 02:43:42 +00003341/// \brief A location where the result (returned value) of evaluating a
3342/// statement should be stored.
3343struct StmtResult {
3344 /// The APValue that should be filled in with the returned value.
3345 APValue &Value;
3346 /// The location containing the result, if any (used to support RVO).
3347 const LValue *Slot;
3348};
3349
3350static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003351 const Stmt *S,
3352 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003353
3354/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003355static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003356 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003357 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003358 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003359 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003360 case ESR_Break:
3361 return ESR_Succeeded;
3362 case ESR_Succeeded:
3363 case ESR_Continue:
3364 return ESR_Continue;
3365 case ESR_Failed:
3366 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003367 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003368 return ESR;
3369 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003370 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003371}
3372
Richard Smith496ddcf2013-05-12 17:32:42 +00003373/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003374static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003375 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003376 BlockScopeRAII Scope(Info);
3377
Richard Smith496ddcf2013-05-12 17:32:42 +00003378 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003379 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003380 {
3381 FullExpressionRAII Scope(Info);
3382 if (SS->getConditionVariable() &&
3383 !EvaluateDecl(Info, SS->getConditionVariable()))
3384 return ESR_Failed;
3385 if (!EvaluateInteger(SS->getCond(), Value, Info))
3386 return ESR_Failed;
3387 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003388
3389 // Find the switch case corresponding to the value of the condition.
3390 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003391 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003392 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3393 SC = SC->getNextSwitchCase()) {
3394 if (isa<DefaultStmt>(SC)) {
3395 Found = SC;
3396 continue;
3397 }
3398
3399 const CaseStmt *CS = cast<CaseStmt>(SC);
3400 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3401 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3402 : LHS;
3403 if (LHS <= Value && Value <= RHS) {
3404 Found = SC;
3405 break;
3406 }
3407 }
3408
3409 if (!Found)
3410 return ESR_Succeeded;
3411
3412 // Search the switch body for the switch case and evaluate it from there.
3413 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3414 case ESR_Break:
3415 return ESR_Succeeded;
3416 case ESR_Succeeded:
3417 case ESR_Continue:
3418 case ESR_Failed:
3419 case ESR_Returned:
3420 return ESR;
3421 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003422 // This can only happen if the switch case is nested within a statement
3423 // expression. We have no intention of supporting that.
3424 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3425 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003426 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003427 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003428}
3429
Richard Smith254a73d2011-10-28 22:34:42 +00003430// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003431static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003432 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003433 if (!Info.nextStep(S))
3434 return ESR_Failed;
3435
Richard Smith496ddcf2013-05-12 17:32:42 +00003436 // If we're hunting down a 'case' or 'default' label, recurse through
3437 // substatements until we hit the label.
3438 if (Case) {
3439 // FIXME: We don't start the lifetime of objects whose initialization we
3440 // jump over. However, such objects must be of class type with a trivial
3441 // default constructor that initialize all subobjects, so must be empty,
3442 // so this almost never matters.
3443 switch (S->getStmtClass()) {
3444 case Stmt::CompoundStmtClass:
3445 // FIXME: Precompute which substatement of a compound statement we
3446 // would jump to, and go straight there rather than performing a
3447 // linear scan each time.
3448 case Stmt::LabelStmtClass:
3449 case Stmt::AttributedStmtClass:
3450 case Stmt::DoStmtClass:
3451 break;
3452
3453 case Stmt::CaseStmtClass:
3454 case Stmt::DefaultStmtClass:
3455 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003456 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003457 break;
3458
3459 case Stmt::IfStmtClass: {
3460 // FIXME: Precompute which side of an 'if' we would jump to, and go
3461 // straight there rather than scanning both sides.
3462 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003463
3464 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3465 // preceded by our switch label.
3466 BlockScopeRAII Scope(Info);
3467
Richard Smith496ddcf2013-05-12 17:32:42 +00003468 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3469 if (ESR != ESR_CaseNotFound || !IS->getElse())
3470 return ESR;
3471 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3472 }
3473
3474 case Stmt::WhileStmtClass: {
3475 EvalStmtResult ESR =
3476 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3477 if (ESR != ESR_Continue)
3478 return ESR;
3479 break;
3480 }
3481
3482 case Stmt::ForStmtClass: {
3483 const ForStmt *FS = cast<ForStmt>(S);
3484 EvalStmtResult ESR =
3485 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3486 if (ESR != ESR_Continue)
3487 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003488 if (FS->getInc()) {
3489 FullExpressionRAII IncScope(Info);
3490 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3491 return ESR_Failed;
3492 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003493 break;
3494 }
3495
3496 case Stmt::DeclStmtClass:
3497 // FIXME: If the variable has initialization that can't be jumped over,
3498 // bail out of any immediately-surrounding compound-statement too.
3499 default:
3500 return ESR_CaseNotFound;
3501 }
3502 }
3503
Richard Smith254a73d2011-10-28 22:34:42 +00003504 switch (S->getStmtClass()) {
3505 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003506 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003507 // Don't bother evaluating beyond an expression-statement which couldn't
3508 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003509 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003510 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003511 return ESR_Failed;
3512 return ESR_Succeeded;
3513 }
3514
3515 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003516 return ESR_Failed;
3517
3518 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003519 return ESR_Succeeded;
3520
Richard Smithd9f663b2013-04-22 15:31:51 +00003521 case Stmt::DeclStmtClass: {
3522 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003523 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003524 // Each declaration initialization is its own full-expression.
3525 // FIXME: This isn't quite right; if we're performing aggregate
3526 // initialization, each braced subexpression is its own full-expression.
3527 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003528 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003529 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003530 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003531 return ESR_Succeeded;
3532 }
3533
Richard Smith357362d2011-12-13 06:39:58 +00003534 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003535 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003536 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003537 if (RetExpr &&
3538 !(Result.Slot
3539 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3540 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003541 return ESR_Failed;
3542 return ESR_Returned;
3543 }
Richard Smith254a73d2011-10-28 22:34:42 +00003544
3545 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003546 BlockScopeRAII Scope(Info);
3547
Richard Smith254a73d2011-10-28 22:34:42 +00003548 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003549 for (const auto *BI : CS->body()) {
3550 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003551 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003552 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003553 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003554 return ESR;
3555 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003556 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003557 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003558
3559 case Stmt::IfStmtClass: {
3560 const IfStmt *IS = cast<IfStmt>(S);
3561
3562 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003563 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003564 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003565 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003566 return ESR_Failed;
3567
3568 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3569 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3570 if (ESR != ESR_Succeeded)
3571 return ESR;
3572 }
3573 return ESR_Succeeded;
3574 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003575
3576 case Stmt::WhileStmtClass: {
3577 const WhileStmt *WS = cast<WhileStmt>(S);
3578 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003579 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003580 bool Continue;
3581 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3582 Continue))
3583 return ESR_Failed;
3584 if (!Continue)
3585 break;
3586
3587 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3588 if (ESR != ESR_Continue)
3589 return ESR;
3590 }
3591 return ESR_Succeeded;
3592 }
3593
3594 case Stmt::DoStmtClass: {
3595 const DoStmt *DS = cast<DoStmt>(S);
3596 bool Continue;
3597 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003598 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003599 if (ESR != ESR_Continue)
3600 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003601 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003602
Richard Smith08d6a2c2013-07-24 07:11:57 +00003603 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003604 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3605 return ESR_Failed;
3606 } while (Continue);
3607 return ESR_Succeeded;
3608 }
3609
3610 case Stmt::ForStmtClass: {
3611 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003612 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003613 if (FS->getInit()) {
3614 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3615 if (ESR != ESR_Succeeded)
3616 return ESR;
3617 }
3618 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003619 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003620 bool Continue = true;
3621 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3622 FS->getCond(), Continue))
3623 return ESR_Failed;
3624 if (!Continue)
3625 break;
3626
3627 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3628 if (ESR != ESR_Continue)
3629 return ESR;
3630
Richard Smith08d6a2c2013-07-24 07:11:57 +00003631 if (FS->getInc()) {
3632 FullExpressionRAII IncScope(Info);
3633 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3634 return ESR_Failed;
3635 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003636 }
3637 return ESR_Succeeded;
3638 }
3639
Richard Smith896e0d72013-05-06 06:51:17 +00003640 case Stmt::CXXForRangeStmtClass: {
3641 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003642 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003643
3644 // Initialize the __range variable.
3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3646 if (ESR != ESR_Succeeded)
3647 return ESR;
3648
3649 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003650 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3651 if (ESR != ESR_Succeeded)
3652 return ESR;
3653 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003654 if (ESR != ESR_Succeeded)
3655 return ESR;
3656
3657 while (true) {
3658 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003659 {
3660 bool Continue = true;
3661 FullExpressionRAII CondExpr(Info);
3662 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3663 return ESR_Failed;
3664 if (!Continue)
3665 break;
3666 }
Richard Smith896e0d72013-05-06 06:51:17 +00003667
3668 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003669 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003670 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3671 if (ESR != ESR_Succeeded)
3672 return ESR;
3673
3674 // Loop body.
3675 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3676 if (ESR != ESR_Continue)
3677 return ESR;
3678
3679 // Increment: ++__begin
3680 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3681 return ESR_Failed;
3682 }
3683
3684 return ESR_Succeeded;
3685 }
3686
Richard Smith496ddcf2013-05-12 17:32:42 +00003687 case Stmt::SwitchStmtClass:
3688 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3689
Richard Smith4e18ca52013-05-06 05:56:11 +00003690 case Stmt::ContinueStmtClass:
3691 return ESR_Continue;
3692
3693 case Stmt::BreakStmtClass:
3694 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003695
3696 case Stmt::LabelStmtClass:
3697 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3698
3699 case Stmt::AttributedStmtClass:
3700 // As a general principle, C++11 attributes can be ignored without
3701 // any semantic impact.
3702 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3703 Case);
3704
3705 case Stmt::CaseStmtClass:
3706 case Stmt::DefaultStmtClass:
3707 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003708 }
3709}
3710
Richard Smithcc36f692011-12-22 02:22:31 +00003711/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3712/// default constructor. If so, we'll fold it whether or not it's marked as
3713/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3714/// so we need special handling.
3715static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003716 const CXXConstructorDecl *CD,
3717 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003718 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3719 return false;
3720
Richard Smith66e05fe2012-01-18 05:21:49 +00003721 // Value-initialization does not call a trivial default constructor, so such a
3722 // call is a core constant expression whether or not the constructor is
3723 // constexpr.
3724 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003725 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003726 // FIXME: If DiagDecl is an implicitly-declared special member function,
3727 // we should be much more explicit about why it's not constexpr.
3728 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3729 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3730 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003731 } else {
3732 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3733 }
3734 }
3735 return true;
3736}
3737
Richard Smith357362d2011-12-13 06:39:58 +00003738/// CheckConstexprFunction - Check that a function can be called in a constant
3739/// expression.
3740static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3741 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003742 const FunctionDecl *Definition,
3743 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003744 // Potential constant expressions can contain calls to declared, but not yet
3745 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003746 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003747 Declaration->isConstexpr())
3748 return false;
3749
Richard Smith0838f3a2013-05-14 05:18:44 +00003750 // Bail out with no diagnostic if the function declaration itself is invalid.
3751 // We will have produced a relevant diagnostic while parsing it.
3752 if (Declaration->isInvalidDecl())
3753 return false;
3754
Richard Smith357362d2011-12-13 06:39:58 +00003755 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003756 if (Definition && Definition->isConstexpr() &&
3757 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003758 return true;
3759
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003760 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003761 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003762 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3763 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003764 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3765 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3766 << DiagDecl;
3767 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3768 } else {
3769 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3770 }
3771 return false;
3772}
3773
Richard Smithbe6dd812014-11-19 21:27:17 +00003774/// Determine if a class has any fields that might need to be copied by a
3775/// trivial copy or move operation.
3776static bool hasFields(const CXXRecordDecl *RD) {
3777 if (!RD || RD->isEmpty())
3778 return false;
3779 for (auto *FD : RD->fields()) {
3780 if (FD->isUnnamedBitfield())
3781 continue;
3782 return true;
3783 }
3784 for (auto &Base : RD->bases())
3785 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3786 return true;
3787 return false;
3788}
3789
Richard Smithd62306a2011-11-10 06:34:14 +00003790namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003791typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003792}
3793
3794/// EvaluateArgs - Evaluate the arguments to a function call.
3795static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3796 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003797 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003798 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003799 I != E; ++I) {
3800 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3801 // If we're checking for a potential constant expression, evaluate all
3802 // initializers even if some of them fail.
3803 if (!Info.keepEvaluatingAfterFailure())
3804 return false;
3805 Success = false;
3806 }
3807 }
3808 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003809}
3810
Richard Smith254a73d2011-10-28 22:34:42 +00003811/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003812static bool HandleFunctionCall(SourceLocation CallLoc,
3813 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003814 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003815 EvalInfo &Info, APValue &Result,
3816 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003817 ArgVector ArgValues(Args.size());
3818 if (!EvaluateArgs(Args, ArgValues, Info))
3819 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003820
Richard Smith253c2a32012-01-27 01:14:48 +00003821 if (!Info.CheckCallLimit(CallLoc))
3822 return false;
3823
3824 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003825
3826 // For a trivial copy or move assignment, perform an APValue copy. This is
3827 // essential for unions, where the operations performed by the assignment
3828 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003829 //
3830 // Skip this for non-union classes with no fields; in that case, the defaulted
3831 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003832 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003833 if (MD && MD->isDefaulted() &&
3834 (MD->getParent()->isUnion() ||
3835 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003836 assert(This &&
3837 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3838 LValue RHS;
3839 RHS.setFrom(Info.Ctx, ArgValues[0]);
3840 APValue RHSValue;
3841 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3842 RHS, RHSValue))
3843 return false;
3844 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3845 RHSValue))
3846 return false;
3847 This->moveInto(Result);
3848 return true;
3849 }
3850
Richard Smith52a980a2015-08-28 02:43:42 +00003851 StmtResult Ret = {Result, ResultSlot};
3852 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003853 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003854 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003855 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003856 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003857 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003858 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003859}
3860
Richard Smithd62306a2011-11-10 06:34:14 +00003861/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003862static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003863 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003864 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003865 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003866 ArgVector ArgValues(Args.size());
3867 if (!EvaluateArgs(Args, ArgValues, Info))
3868 return false;
3869
Richard Smith253c2a32012-01-27 01:14:48 +00003870 if (!Info.CheckCallLimit(CallLoc))
3871 return false;
3872
Richard Smith3607ffe2012-02-13 03:54:03 +00003873 const CXXRecordDecl *RD = Definition->getParent();
3874 if (RD->getNumVBases()) {
3875 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3876 return false;
3877 }
3878
Richard Smith253c2a32012-01-27 01:14:48 +00003879 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003880
Richard Smith52a980a2015-08-28 02:43:42 +00003881 // FIXME: Creating an APValue just to hold a nonexistent return value is
3882 // wasteful.
3883 APValue RetVal;
3884 StmtResult Ret = {RetVal, nullptr};
3885
Richard Smithd62306a2011-11-10 06:34:14 +00003886 // If it's a delegating constructor, just delegate.
3887 if (Definition->isDelegatingConstructor()) {
3888 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003889 {
3890 FullExpressionRAII InitScope(Info);
3891 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3892 return false;
3893 }
Richard Smith52a980a2015-08-28 02:43:42 +00003894 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003895 }
3896
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003897 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003898 // essential for unions (or classes with anonymous union members), where the
3899 // operations performed by the constructor cannot be represented by
3900 // ctor-initializers.
3901 //
3902 // Skip this for empty non-union classes; we should not perform an
3903 // lvalue-to-rvalue conversion on them because their copy constructor does not
3904 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003905 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003906 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003907 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003908 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003909 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003910 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003911 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003912 }
3913
3914 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003915 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003916 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003917 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003918
John McCalld7bca762012-05-01 00:38:49 +00003919 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003920 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3921
Richard Smith08d6a2c2013-07-24 07:11:57 +00003922 // A scope for temporaries lifetime-extended by reference members.
3923 BlockScopeRAII LifetimeExtendedScope(Info);
3924
Richard Smith253c2a32012-01-27 01:14:48 +00003925 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003926 unsigned BasesSeen = 0;
3927#ifndef NDEBUG
3928 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3929#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003930 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003931 LValue Subobject = This;
3932 APValue *Value = &Result;
3933
3934 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003935 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003936 if (I->isBaseInitializer()) {
3937 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003938#ifndef NDEBUG
3939 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003940 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003941 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3942 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3943 "base class initializers not in expected order");
3944 ++BaseIt;
3945#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003946 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003947 BaseType->getAsCXXRecordDecl(), &Layout))
3948 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003949 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003950 } else if ((FD = I->getMember())) {
3951 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003952 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003953 if (RD->isUnion()) {
3954 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003955 Value = &Result.getUnionValue();
3956 } else {
3957 Value = &Result.getStructField(FD->getFieldIndex());
3958 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003959 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003960 // Walk the indirect field decl's chain to find the object to initialize,
3961 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003962 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003963 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003964 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3965 // Switch the union field if it differs. This happens if we had
3966 // preceding zero-initialization, and we're now initializing a union
3967 // subobject other than the first.
3968 // FIXME: In this case, the values of the other subobjects are
3969 // specified, since zero-initialization sets all padding bits to zero.
3970 if (Value->isUninit() ||
3971 (Value->isUnion() && Value->getUnionField() != FD)) {
3972 if (CD->isUnion())
3973 *Value = APValue(FD);
3974 else
3975 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003976 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003977 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003978 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003979 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003980 if (CD->isUnion())
3981 Value = &Value->getUnionValue();
3982 else
3983 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003984 }
Richard Smithd62306a2011-11-10 06:34:14 +00003985 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003986 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003987 }
Richard Smith253c2a32012-01-27 01:14:48 +00003988
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003990 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3991 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003992 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003993 // If we're checking for a potential constant expression, evaluate all
3994 // initializers even if some of them fail.
3995 if (!Info.keepEvaluatingAfterFailure())
3996 return false;
3997 Success = false;
3998 }
Richard Smithd62306a2011-11-10 06:34:14 +00003999 }
4000
Richard Smithd9f663b2013-04-22 15:31:51 +00004001 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004002 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004003}
4004
Eli Friedman9a156e52008-11-12 09:44:48 +00004005//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004006// Generic Evaluation
4007//===----------------------------------------------------------------------===//
4008namespace {
4009
Aaron Ballman68af21c2014-01-03 19:26:43 +00004010template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004011class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004012 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004013private:
Richard Smith52a980a2015-08-28 02:43:42 +00004014 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004015 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004016 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004017 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004018 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004019 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004020 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004021
Richard Smith17100ba2012-02-16 02:46:34 +00004022 // Check whether a conditional operator with a non-constant condition is a
4023 // potential constant expression. If neither arm is a potential constant
4024 // expression, then the conditional operator is not either.
4025 template<typename ConditionalOperator>
4026 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004027 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004028
4029 // Speculatively evaluate both arms.
4030 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004031 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004032 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4033
4034 StmtVisitorTy::Visit(E->getFalseExpr());
4035 if (Diag.empty())
4036 return;
4037
4038 Diag.clear();
4039 StmtVisitorTy::Visit(E->getTrueExpr());
4040 if (Diag.empty())
4041 return;
4042 }
4043
4044 Error(E, diag::note_constexpr_conditional_never_const);
4045 }
4046
4047
4048 template<typename ConditionalOperator>
4049 bool HandleConditionalOperator(const ConditionalOperator *E) {
4050 bool BoolResult;
4051 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004052 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00004053 CheckPotentialConstantConditional(E);
4054 return false;
4055 }
4056
4057 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4058 return StmtVisitorTy::Visit(EvalExpr);
4059 }
4060
Peter Collingbournee9200682011-05-13 03:29:01 +00004061protected:
4062 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004063 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004064 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4065
Richard Smith92b1ce02011-12-12 09:28:41 +00004066 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004067 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004068 }
4069
Aaron Ballman68af21c2014-01-03 19:26:43 +00004070 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004071
4072public:
4073 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4074
4075 EvalInfo &getEvalInfo() { return Info; }
4076
Richard Smithf57d8cb2011-12-09 22:58:01 +00004077 /// Report an evaluation error. This should only be called when an error is
4078 /// first discovered. When propagating an error, just return false.
4079 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004080 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004081 return false;
4082 }
4083 bool Error(const Expr *E) {
4084 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4085 }
4086
Aaron Ballman68af21c2014-01-03 19:26:43 +00004087 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004088 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004089 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004090 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004091 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004092 }
4093
Aaron Ballman68af21c2014-01-03 19:26:43 +00004094 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004095 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004096 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004097 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004099 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004100 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004101 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004102 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004103 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004104 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004105 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004106 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004107 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004108 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004109 // The initializer may not have been parsed yet, or might be erroneous.
4110 if (!E->getExpr())
4111 return Error(E);
4112 return StmtVisitorTy::Visit(E->getExpr());
4113 }
Richard Smith5894a912011-12-19 22:12:41 +00004114 // We cannot create any objects for which cleanups are required, so there is
4115 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004116 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004117 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004118
Aaron Ballman68af21c2014-01-03 19:26:43 +00004119 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004120 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4121 return static_cast<Derived*>(this)->VisitCastExpr(E);
4122 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004123 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004124 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4125 return static_cast<Derived*>(this)->VisitCastExpr(E);
4126 }
4127
Aaron Ballman68af21c2014-01-03 19:26:43 +00004128 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004129 switch (E->getOpcode()) {
4130 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004131 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004132
4133 case BO_Comma:
4134 VisitIgnoredValue(E->getLHS());
4135 return StmtVisitorTy::Visit(E->getRHS());
4136
4137 case BO_PtrMemD:
4138 case BO_PtrMemI: {
4139 LValue Obj;
4140 if (!HandleMemberPointerAccess(Info, E, Obj))
4141 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004142 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004143 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004144 return false;
4145 return DerivedSuccess(Result, E);
4146 }
4147 }
4148 }
4149
Aaron Ballman68af21c2014-01-03 19:26:43 +00004150 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004151 // Evaluate and cache the common expression. We treat it as a temporary,
4152 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004153 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004154 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004155 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004156
Richard Smith17100ba2012-02-16 02:46:34 +00004157 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004158 }
4159
Aaron Ballman68af21c2014-01-03 19:26:43 +00004160 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004161 bool IsBcpCall = false;
4162 // If the condition (ignoring parens) is a __builtin_constant_p call,
4163 // the result is a constant expression if it can be folded without
4164 // side-effects. This is an important GNU extension. See GCC PR38377
4165 // for discussion.
4166 if (const CallExpr *CallCE =
4167 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004168 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004169 IsBcpCall = true;
4170
4171 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4172 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004173 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004174 return false;
4175
Richard Smith6d4c6582013-11-05 22:18:15 +00004176 FoldConstant Fold(Info, IsBcpCall);
4177 if (!HandleConditionalOperator(E)) {
4178 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004179 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004180 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004181
4182 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004183 }
4184
Aaron Ballman68af21c2014-01-03 19:26:43 +00004185 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004186 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4187 return DerivedSuccess(*Value, E);
4188
4189 const Expr *Source = E->getSourceExpr();
4190 if (!Source)
4191 return Error(E);
4192 if (Source == E) { // sanity checking.
4193 assert(0 && "OpaqueValueExpr recursively refers to itself");
4194 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004195 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004196 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004197 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004198
Aaron Ballman68af21c2014-01-03 19:26:43 +00004199 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004200 APValue Result;
4201 if (!handleCallExpr(E, Result, nullptr))
4202 return false;
4203 return DerivedSuccess(Result, E);
4204 }
4205
4206 bool handleCallExpr(const CallExpr *E, APValue &Result,
4207 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004208 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004209 QualType CalleeType = Callee->getType();
4210
Craig Topper36250ad2014-05-12 05:36:57 +00004211 const FunctionDecl *FD = nullptr;
4212 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004213 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004214 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004215
Richard Smithe97cbd72011-11-11 04:05:33 +00004216 // Extract function decl and 'this' pointer from the callee.
4217 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004218 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004219 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4220 // Explicit bound member calls, such as x.f() or p->g();
4221 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004222 return false;
4223 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004224 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004225 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004226 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4227 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004228 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4229 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004230 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004231 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004232 return Error(Callee);
4233
4234 FD = dyn_cast<FunctionDecl>(Member);
4235 if (!FD)
4236 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004237 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004238 LValue Call;
4239 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004240 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004241
Richard Smitha8105bc2012-01-06 16:39:00 +00004242 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004243 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004244 FD = dyn_cast_or_null<FunctionDecl>(
4245 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004246 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004247 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004248
4249 // Overloaded operator calls to member functions are represented as normal
4250 // calls with '*this' as the first argument.
4251 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4252 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004253 // FIXME: When selecting an implicit conversion for an overloaded
4254 // operator delete, we sometimes try to evaluate calls to conversion
4255 // operators without a 'this' parameter!
4256 if (Args.empty())
4257 return Error(E);
4258
Richard Smithe97cbd72011-11-11 04:05:33 +00004259 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4260 return false;
4261 This = &ThisVal;
4262 Args = Args.slice(1);
4263 }
4264
4265 // Don't call function pointers which have been cast to some other type.
4266 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004267 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004268 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004270
Richard Smith47b34932012-02-01 02:39:43 +00004271 if (This && !This->checkSubobject(Info, E, CSK_This))
4272 return false;
4273
Richard Smith3607ffe2012-02-13 03:54:03 +00004274 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4275 // calls to such functions in constant expressions.
4276 if (This && !HasQualifier &&
4277 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4278 return Error(E, diag::note_constexpr_virtual_call);
4279
Craig Topper36250ad2014-05-12 05:36:57 +00004280 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004281 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004282
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004283 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004284 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4285 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004286 return false;
4287
Richard Smith52a980a2015-08-28 02:43:42 +00004288 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004289 }
4290
Aaron Ballman68af21c2014-01-03 19:26:43 +00004291 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004292 return StmtVisitorTy::Visit(E->getInitializer());
4293 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004294 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004295 if (E->getNumInits() == 0)
4296 return DerivedZeroInitialization(E);
4297 if (E->getNumInits() == 1)
4298 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004299 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004300 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004301 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004302 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004303 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004304 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004305 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004306 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004307 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004308 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004309 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004310
Richard Smithd62306a2011-11-10 06:34:14 +00004311 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004312 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004313 assert(!E->isArrow() && "missing call to bound member function?");
4314
Richard Smith2e312c82012-03-03 22:46:17 +00004315 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004316 if (!Evaluate(Val, Info, E->getBase()))
4317 return false;
4318
4319 QualType BaseTy = E->getBase()->getType();
4320
4321 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004322 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004323 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004324 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004325 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4326
Richard Smith3229b742013-05-05 21:17:10 +00004327 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004328 SubobjectDesignator Designator(BaseTy);
4329 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004330
Richard Smith3229b742013-05-05 21:17:10 +00004331 APValue Result;
4332 return extractSubobject(Info, E, Obj, Designator, Result) &&
4333 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004334 }
4335
Aaron Ballman68af21c2014-01-03 19:26:43 +00004336 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004337 switch (E->getCastKind()) {
4338 default:
4339 break;
4340
Richard Smitha23ab512013-05-23 00:30:41 +00004341 case CK_AtomicToNonAtomic: {
4342 APValue AtomicVal;
4343 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4344 return false;
4345 return DerivedSuccess(AtomicVal, E);
4346 }
4347
Richard Smith11562c52011-10-28 17:51:58 +00004348 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004349 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004350 return StmtVisitorTy::Visit(E->getSubExpr());
4351
4352 case CK_LValueToRValue: {
4353 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004354 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4355 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004356 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004357 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004358 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004359 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004360 return false;
4361 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004362 }
4363 }
4364
Richard Smithf57d8cb2011-12-09 22:58:01 +00004365 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004366 }
4367
Aaron Ballman68af21c2014-01-03 19:26:43 +00004368 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004369 return VisitUnaryPostIncDec(UO);
4370 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004371 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004372 return VisitUnaryPostIncDec(UO);
4373 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004374 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004375 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004376 return Error(UO);
4377
4378 LValue LVal;
4379 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4380 return false;
4381 APValue RVal;
4382 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4383 UO->isIncrementOp(), &RVal))
4384 return false;
4385 return DerivedSuccess(RVal, UO);
4386 }
4387
Aaron Ballman68af21c2014-01-03 19:26:43 +00004388 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004389 // We will have checked the full-expressions inside the statement expression
4390 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004391 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004392 return Error(E);
4393
Richard Smith08d6a2c2013-07-24 07:11:57 +00004394 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004395 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004396 if (CS->body_empty())
4397 return true;
4398
Richard Smith51f03172013-06-20 03:00:05 +00004399 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4400 BE = CS->body_end();
4401 /**/; ++BI) {
4402 if (BI + 1 == BE) {
4403 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4404 if (!FinalExpr) {
4405 Info.Diag((*BI)->getLocStart(),
4406 diag::note_constexpr_stmt_expr_unsupported);
4407 return false;
4408 }
4409 return this->Visit(FinalExpr);
4410 }
4411
4412 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004413 StmtResult Result = { ReturnValue, nullptr };
4414 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004415 if (ESR != ESR_Succeeded) {
4416 // FIXME: If the statement-expression terminated due to 'return',
4417 // 'break', or 'continue', it would be nice to propagate that to
4418 // the outer statement evaluation rather than bailing out.
4419 if (ESR != ESR_Failed)
4420 Info.Diag((*BI)->getLocStart(),
4421 diag::note_constexpr_stmt_expr_unsupported);
4422 return false;
4423 }
4424 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004425
4426 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004427 }
4428
Richard Smith4a678122011-10-24 18:44:57 +00004429 /// Visit a value which is evaluated, but whose value is ignored.
4430 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004431 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004432 }
David Majnemere9807b22016-02-26 04:23:19 +00004433
4434 /// Potentially visit a MemberExpr's base expression.
4435 void VisitIgnoredBaseExpression(const Expr *E) {
4436 // While MSVC doesn't evaluate the base expression, it does diagnose the
4437 // presence of side-effecting behavior.
4438 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4439 return;
4440 VisitIgnoredValue(E);
4441 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004442};
4443
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004444}
Peter Collingbournee9200682011-05-13 03:29:01 +00004445
4446//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004447// Common base class for lvalue and temporary evaluation.
4448//===----------------------------------------------------------------------===//
4449namespace {
4450template<class Derived>
4451class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004452 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004453protected:
4454 LValue &Result;
4455 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004456 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004457
4458 bool Success(APValue::LValueBase B) {
4459 Result.set(B);
4460 return true;
4461 }
4462
4463public:
4464 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4465 ExprEvaluatorBaseTy(Info), Result(Result) {}
4466
Richard Smith2e312c82012-03-03 22:46:17 +00004467 bool Success(const APValue &V, const Expr *E) {
4468 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004469 return true;
4470 }
Richard Smith027bf112011-11-17 22:56:20 +00004471
Richard Smith027bf112011-11-17 22:56:20 +00004472 bool VisitMemberExpr(const MemberExpr *E) {
4473 // Handle non-static data members.
4474 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004475 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004476 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004477 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004478 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004479 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004480 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004481 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004482 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004483 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004484 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004485 BaseTy = E->getBase()->getType();
4486 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004487 if (!EvalOK) {
4488 if (!this->Info.allowInvalidBaseExpr())
4489 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004490 Result.setInvalid(E);
4491 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004492 }
Richard Smith027bf112011-11-17 22:56:20 +00004493
Richard Smith1b78b3d2012-01-25 22:15:11 +00004494 const ValueDecl *MD = E->getMemberDecl();
4495 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4496 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4497 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4498 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004499 if (!HandleLValueMember(this->Info, E, Result, FD))
4500 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004501 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004502 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4503 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004504 } else
4505 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004506
Richard Smith1b78b3d2012-01-25 22:15:11 +00004507 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004508 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004509 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004510 RefValue))
4511 return false;
4512 return Success(RefValue, E);
4513 }
4514 return true;
4515 }
4516
4517 bool VisitBinaryOperator(const BinaryOperator *E) {
4518 switch (E->getOpcode()) {
4519 default:
4520 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4521
4522 case BO_PtrMemD:
4523 case BO_PtrMemI:
4524 return HandleMemberPointerAccess(this->Info, E, Result);
4525 }
4526 }
4527
4528 bool VisitCastExpr(const CastExpr *E) {
4529 switch (E->getCastKind()) {
4530 default:
4531 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4532
4533 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004534 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004535 if (!this->Visit(E->getSubExpr()))
4536 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004537
4538 // Now figure out the necessary offset to add to the base LV to get from
4539 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004540 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4541 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004542 }
4543 }
4544};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004545}
Richard Smith027bf112011-11-17 22:56:20 +00004546
4547//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004548// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004549//
4550// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4551// function designators (in C), decl references to void objects (in C), and
4552// temporaries (if building with -Wno-address-of-temporary).
4553//
4554// LValue evaluation produces values comprising a base expression of one of the
4555// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004556// - Declarations
4557// * VarDecl
4558// * FunctionDecl
4559// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004560// * CompoundLiteralExpr in C
4561// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004562// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004563// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004564// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004565// * ObjCEncodeExpr
4566// * AddrLabelExpr
4567// * BlockExpr
4568// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004569// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004570// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004571// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004572// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4573// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004574// * A MaterializeTemporaryExpr that has static storage duration, with no
4575// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004576// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004577//===----------------------------------------------------------------------===//
4578namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004579class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004580 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004581public:
Richard Smith027bf112011-11-17 22:56:20 +00004582 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4583 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004584
Richard Smith11562c52011-10-28 17:51:58 +00004585 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004586 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004587
Peter Collingbournee9200682011-05-13 03:29:01 +00004588 bool VisitDeclRefExpr(const DeclRefExpr *E);
4589 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004590 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004591 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4592 bool VisitMemberExpr(const MemberExpr *E);
4593 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4594 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004595 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004596 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004597 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4598 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004599 bool VisitUnaryReal(const UnaryOperator *E);
4600 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004601 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4602 return VisitUnaryPreIncDec(UO);
4603 }
4604 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4605 return VisitUnaryPreIncDec(UO);
4606 }
Richard Smith3229b742013-05-05 21:17:10 +00004607 bool VisitBinAssign(const BinaryOperator *BO);
4608 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004609
Peter Collingbournee9200682011-05-13 03:29:01 +00004610 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004611 switch (E->getCastKind()) {
4612 default:
Richard Smith027bf112011-11-17 22:56:20 +00004613 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004614
Eli Friedmance3e02a2011-10-11 00:13:24 +00004615 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004616 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004617 if (!Visit(E->getSubExpr()))
4618 return false;
4619 Result.Designator.setInvalid();
4620 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004621
Richard Smith027bf112011-11-17 22:56:20 +00004622 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004623 if (!Visit(E->getSubExpr()))
4624 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004625 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004626 }
4627 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004628};
4629} // end anonymous namespace
4630
Richard Smith11562c52011-10-28 17:51:58 +00004631/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004632/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004633/// * function designators in C, and
4634/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004635/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004636static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4637 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004638 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004639 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004640}
4641
Peter Collingbournee9200682011-05-13 03:29:01 +00004642bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004643 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004644 return Success(FD);
4645 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004646 return VisitVarDecl(E, VD);
4647 return Error(E);
4648}
Richard Smith733237d2011-10-24 23:14:33 +00004649
Richard Smith11562c52011-10-28 17:51:58 +00004650bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004651 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004652 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4653 Frame = Info.CurrentCall;
4654
Richard Smithfec09922011-11-01 16:57:24 +00004655 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004656 if (Frame) {
4657 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004658 return true;
4659 }
Richard Smithce40ad62011-11-12 22:28:03 +00004660 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004661 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004662
Richard Smith3229b742013-05-05 21:17:10 +00004663 APValue *V;
4664 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004665 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004666 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004667 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004668 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4669 return false;
4670 }
Richard Smith3229b742013-05-05 21:17:10 +00004671 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004672}
4673
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004674bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4675 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004676 // Walk through the expression to find the materialized temporary itself.
4677 SmallVector<const Expr *, 2> CommaLHSs;
4678 SmallVector<SubobjectAdjustment, 2> Adjustments;
4679 const Expr *Inner = E->GetTemporaryExpr()->
4680 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004681
Richard Smith84401042013-06-03 05:03:02 +00004682 // If we passed any comma operators, evaluate their LHSs.
4683 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4684 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4685 return false;
4686
Richard Smithe6c01442013-06-05 00:46:14 +00004687 // A materialized temporary with static storage duration can appear within the
4688 // result of a constant expression evaluation, so we need to preserve its
4689 // value for use outside this evaluation.
4690 APValue *Value;
4691 if (E->getStorageDuration() == SD_Static) {
4692 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004693 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004694 Result.set(E);
4695 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004696 Value = &Info.CurrentCall->
4697 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004698 Result.set(E, Info.CurrentCall->Index);
4699 }
4700
Richard Smithea4ad5d2013-06-06 08:19:16 +00004701 QualType Type = Inner->getType();
4702
Richard Smith84401042013-06-03 05:03:02 +00004703 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004704 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4705 (E->getStorageDuration() == SD_Static &&
4706 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4707 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004708 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004709 }
Richard Smith84401042013-06-03 05:03:02 +00004710
4711 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004712 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4713 --I;
4714 switch (Adjustments[I].Kind) {
4715 case SubobjectAdjustment::DerivedToBaseAdjustment:
4716 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4717 Type, Result))
4718 return false;
4719 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4720 break;
4721
4722 case SubobjectAdjustment::FieldAdjustment:
4723 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4724 return false;
4725 Type = Adjustments[I].Field->getType();
4726 break;
4727
4728 case SubobjectAdjustment::MemberPointerAdjustment:
4729 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4730 Adjustments[I].Ptr.RHS))
4731 return false;
4732 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4733 break;
4734 }
4735 }
4736
4737 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004738}
4739
Peter Collingbournee9200682011-05-13 03:29:01 +00004740bool
4741LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004742 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4743 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4744 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004745 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004746}
4747
Richard Smith6e525142011-12-27 12:18:28 +00004748bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004749 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004750 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004751
4752 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4753 << E->getExprOperand()->getType()
4754 << E->getExprOperand()->getSourceRange();
4755 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004756}
4757
Francois Pichet0066db92012-04-16 04:08:35 +00004758bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4759 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004760}
Francois Pichet0066db92012-04-16 04:08:35 +00004761
Peter Collingbournee9200682011-05-13 03:29:01 +00004762bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004763 // Handle static data members.
4764 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004765 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004766 return VisitVarDecl(E, VD);
4767 }
4768
Richard Smith254a73d2011-10-28 22:34:42 +00004769 // Handle static member functions.
4770 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4771 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004772 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004773 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004774 }
4775 }
4776
Richard Smithd62306a2011-11-10 06:34:14 +00004777 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004778 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004779}
4780
Peter Collingbournee9200682011-05-13 03:29:01 +00004781bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004782 // FIXME: Deal with vectors as array subscript bases.
4783 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004784 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004785
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004786 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004787 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004788
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004789 APSInt Index;
4790 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004791 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004792
Richard Smith861b5b52013-05-07 23:34:45 +00004793 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4794 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004795}
Eli Friedman9a156e52008-11-12 09:44:48 +00004796
Peter Collingbournee9200682011-05-13 03:29:01 +00004797bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004798 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004799}
4800
Richard Smith66c96992012-02-18 22:04:06 +00004801bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4802 if (!Visit(E->getSubExpr()))
4803 return false;
4804 // __real is a no-op on scalar lvalues.
4805 if (E->getSubExpr()->getType()->isAnyComplexType())
4806 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4807 return true;
4808}
4809
4810bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4811 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4812 "lvalue __imag__ on scalar?");
4813 if (!Visit(E->getSubExpr()))
4814 return false;
4815 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4816 return true;
4817}
4818
Richard Smith243ef902013-05-05 23:31:59 +00004819bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004820 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004821 return Error(UO);
4822
4823 if (!this->Visit(UO->getSubExpr()))
4824 return false;
4825
Richard Smith243ef902013-05-05 23:31:59 +00004826 return handleIncDec(
4827 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004828 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004829}
4830
4831bool LValueExprEvaluator::VisitCompoundAssignOperator(
4832 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004833 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004834 return Error(CAO);
4835
Richard Smith3229b742013-05-05 21:17:10 +00004836 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004837
4838 // The overall lvalue result is the result of evaluating the LHS.
4839 if (!this->Visit(CAO->getLHS())) {
4840 if (Info.keepEvaluatingAfterFailure())
4841 Evaluate(RHS, this->Info, CAO->getRHS());
4842 return false;
4843 }
4844
Richard Smith3229b742013-05-05 21:17:10 +00004845 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4846 return false;
4847
Richard Smith43e77732013-05-07 04:50:00 +00004848 return handleCompoundAssignment(
4849 this->Info, CAO,
4850 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4851 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004852}
4853
4854bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004855 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004856 return Error(E);
4857
Richard Smith3229b742013-05-05 21:17:10 +00004858 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004859
4860 if (!this->Visit(E->getLHS())) {
4861 if (Info.keepEvaluatingAfterFailure())
4862 Evaluate(NewVal, this->Info, E->getRHS());
4863 return false;
4864 }
4865
Richard Smith3229b742013-05-05 21:17:10 +00004866 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4867 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004868
4869 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004870 NewVal);
4871}
4872
Eli Friedman9a156e52008-11-12 09:44:48 +00004873//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004874// Pointer Evaluation
4875//===----------------------------------------------------------------------===//
4876
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004877namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004878class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004879 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004880 LValue &Result;
4881
Peter Collingbournee9200682011-05-13 03:29:01 +00004882 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004883 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004884 return true;
4885 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004886public:
Mike Stump11289f42009-09-09 15:08:12 +00004887
John McCall45d55e42010-05-07 21:00:08 +00004888 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004889 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004890
Richard Smith2e312c82012-03-03 22:46:17 +00004891 bool Success(const APValue &V, const Expr *E) {
4892 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004893 return true;
4894 }
Richard Smithfddd3842011-12-30 21:15:51 +00004895 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004896 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004897 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004898
John McCall45d55e42010-05-07 21:00:08 +00004899 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004900 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004901 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004902 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004903 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004904 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004905 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004906 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004907 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004908 bool VisitCallExpr(const CallExpr *E);
4909 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004910 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004911 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004912 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004913 }
Richard Smithd62306a2011-11-10 06:34:14 +00004914 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004915 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004916 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004917 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004918 if (!Info.CurrentCall->This) {
4919 if (Info.getLangOpts().CPlusPlus11)
4920 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4921 else
4922 Info.Diag(E);
4923 return false;
4924 }
Richard Smithd62306a2011-11-10 06:34:14 +00004925 Result = *Info.CurrentCall->This;
4926 return true;
4927 }
John McCallc07a0c72011-02-17 10:25:35 +00004928
Eli Friedman449fe542009-03-23 04:56:01 +00004929 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004930};
Chris Lattner05706e882008-07-11 18:11:29 +00004931} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004932
John McCall45d55e42010-05-07 21:00:08 +00004933static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004934 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004935 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004936}
4937
John McCall45d55e42010-05-07 21:00:08 +00004938bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004939 if (E->getOpcode() != BO_Add &&
4940 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004941 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004942
Chris Lattner05706e882008-07-11 18:11:29 +00004943 const Expr *PExp = E->getLHS();
4944 const Expr *IExp = E->getRHS();
4945 if (IExp->getType()->isPointerType())
4946 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004947
Richard Smith253c2a32012-01-27 01:14:48 +00004948 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4949 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004950 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004951
John McCall45d55e42010-05-07 21:00:08 +00004952 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004953 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004954 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004955
4956 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004957 if (E->getOpcode() == BO_Sub)
4958 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004959
Ted Kremenek28831752012-08-23 20:46:57 +00004960 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004961 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4962 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004963}
Eli Friedman9a156e52008-11-12 09:44:48 +00004964
John McCall45d55e42010-05-07 21:00:08 +00004965bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4966 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004967}
Mike Stump11289f42009-09-09 15:08:12 +00004968
Peter Collingbournee9200682011-05-13 03:29:01 +00004969bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4970 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004971
Eli Friedman847a2bc2009-12-27 05:43:15 +00004972 switch (E->getCastKind()) {
4973 default:
4974 break;
4975
John McCalle3027922010-08-25 11:45:40 +00004976 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004977 case CK_CPointerToObjCPointerCast:
4978 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004979 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004980 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004981 if (!Visit(SubExpr))
4982 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004983 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4984 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4985 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004986 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004987 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004988 if (SubExpr->getType()->isVoidPointerType())
4989 CCEDiag(E, diag::note_constexpr_invalid_cast)
4990 << 3 << SubExpr->getType();
4991 else
4992 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4993 }
Richard Smith96e0c102011-11-04 02:25:55 +00004994 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004995
Anders Carlsson18275092010-10-31 20:41:46 +00004996 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004997 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004998 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004999 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005000 if (!Result.Base && Result.Offset.isZero())
5001 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005002
Richard Smithd62306a2011-11-10 06:34:14 +00005003 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005004 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005005 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5006 castAs<PointerType>()->getPointeeType(),
5007 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005008
Richard Smith027bf112011-11-17 22:56:20 +00005009 case CK_BaseToDerived:
5010 if (!Visit(E->getSubExpr()))
5011 return false;
5012 if (!Result.Base && Result.Offset.isZero())
5013 return true;
5014 return HandleBaseToDerivedCast(Info, E, Result);
5015
Richard Smith0b0a0b62011-10-29 20:57:55 +00005016 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005017 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005018 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005019
John McCalle3027922010-08-25 11:45:40 +00005020 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005021 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5022
Richard Smith2e312c82012-03-03 22:46:17 +00005023 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005024 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005025 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005026
John McCall45d55e42010-05-07 21:00:08 +00005027 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005028 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5029 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005030 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005031 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005032 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005033 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005034 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005035 return true;
5036 } else {
5037 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005038 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005039 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005040 }
5041 }
John McCalle3027922010-08-25 11:45:40 +00005042 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005043 if (SubExpr->isGLValue()) {
5044 if (!EvaluateLValue(SubExpr, Result, Info))
5045 return false;
5046 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005047 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005048 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005049 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005050 return false;
5051 }
Richard Smith96e0c102011-11-04 02:25:55 +00005052 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005053 if (const ConstantArrayType *CAT
5054 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5055 Result.addArray(Info, E, CAT);
5056 else
5057 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005058 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005059
John McCalle3027922010-08-25 11:45:40 +00005060 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005061 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005062 }
5063
Richard Smith11562c52011-10-28 17:51:58 +00005064 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005065}
Chris Lattner05706e882008-07-11 18:11:29 +00005066
Hal Finkel0dd05d42014-10-03 17:18:37 +00005067static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5068 // C++ [expr.alignof]p3:
5069 // When alignof is applied to a reference type, the result is the
5070 // alignment of the referenced type.
5071 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5072 T = Ref->getPointeeType();
5073
5074 // __alignof is defined to return the preferred alignment.
5075 return Info.Ctx.toCharUnitsFromBits(
5076 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5077}
5078
5079static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5080 E = E->IgnoreParens();
5081
5082 // The kinds of expressions that we have special-case logic here for
5083 // should be kept up to date with the special checks for those
5084 // expressions in Sema.
5085
5086 // alignof decl is always accepted, even if it doesn't make sense: we default
5087 // to 1 in those cases.
5088 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5089 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5090 /*RefAsPointee*/true);
5091
5092 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5093 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5094 /*RefAsPointee*/true);
5095
5096 return GetAlignOfType(Info, E->getType());
5097}
5098
Peter Collingbournee9200682011-05-13 03:29:01 +00005099bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005100 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005101 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005102
Alp Tokera724cff2013-12-28 21:59:02 +00005103 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005104 case Builtin::BI__builtin_addressof:
5105 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005106 case Builtin::BI__builtin_assume_aligned: {
5107 // We need to be very careful here because: if the pointer does not have the
5108 // asserted alignment, then the behavior is undefined, and undefined
5109 // behavior is non-constant.
5110 if (!EvaluatePointer(E->getArg(0), Result, Info))
5111 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005112
Hal Finkel0dd05d42014-10-03 17:18:37 +00005113 LValue OffsetResult(Result);
5114 APSInt Alignment;
5115 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5116 return false;
5117 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5118
5119 if (E->getNumArgs() > 2) {
5120 APSInt Offset;
5121 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5122 return false;
5123
5124 int64_t AdditionalOffset = -getExtValue(Offset);
5125 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5126 }
5127
5128 // If there is a base object, then it must have the correct alignment.
5129 if (OffsetResult.Base) {
5130 CharUnits BaseAlignment;
5131 if (const ValueDecl *VD =
5132 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5133 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5134 } else {
5135 BaseAlignment =
5136 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5137 }
5138
5139 if (BaseAlignment < Align) {
5140 Result.Designator.setInvalid();
5141 // FIXME: Quantities here cast to integers because the plural modifier
5142 // does not work on APSInts yet.
5143 CCEDiag(E->getArg(0),
5144 diag::note_constexpr_baa_insufficient_alignment) << 0
5145 << (int) BaseAlignment.getQuantity()
5146 << (unsigned) getExtValue(Alignment);
5147 return false;
5148 }
5149 }
5150
5151 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005152 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005153 Result.Designator.setInvalid();
5154 APSInt Offset(64, false);
5155 Offset = OffsetResult.Offset.getQuantity();
5156
5157 if (OffsetResult.Base)
5158 CCEDiag(E->getArg(0),
5159 diag::note_constexpr_baa_insufficient_alignment) << 1
5160 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5161 else
5162 CCEDiag(E->getArg(0),
5163 diag::note_constexpr_baa_value_insufficient_alignment)
5164 << Offset << (unsigned) getExtValue(Alignment);
5165
5166 return false;
5167 }
5168
5169 return true;
5170 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005171 default:
5172 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5173 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005174}
Chris Lattner05706e882008-07-11 18:11:29 +00005175
5176//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005177// Member Pointer Evaluation
5178//===----------------------------------------------------------------------===//
5179
5180namespace {
5181class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005182 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005183 MemberPtr &Result;
5184
5185 bool Success(const ValueDecl *D) {
5186 Result = MemberPtr(D);
5187 return true;
5188 }
5189public:
5190
5191 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5192 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5193
Richard Smith2e312c82012-03-03 22:46:17 +00005194 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005195 Result.setFrom(V);
5196 return true;
5197 }
Richard Smithfddd3842011-12-30 21:15:51 +00005198 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005199 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005200 }
5201
5202 bool VisitCastExpr(const CastExpr *E);
5203 bool VisitUnaryAddrOf(const UnaryOperator *E);
5204};
5205} // end anonymous namespace
5206
5207static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5208 EvalInfo &Info) {
5209 assert(E->isRValue() && E->getType()->isMemberPointerType());
5210 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5211}
5212
5213bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5214 switch (E->getCastKind()) {
5215 default:
5216 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5217
5218 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005219 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005220 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005221
5222 case CK_BaseToDerivedMemberPointer: {
5223 if (!Visit(E->getSubExpr()))
5224 return false;
5225 if (E->path_empty())
5226 return true;
5227 // Base-to-derived member pointer casts store the path in derived-to-base
5228 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5229 // the wrong end of the derived->base arc, so stagger the path by one class.
5230 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5231 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5232 PathI != PathE; ++PathI) {
5233 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5234 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5235 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005236 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005237 }
5238 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5239 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005240 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005241 return true;
5242 }
5243
5244 case CK_DerivedToBaseMemberPointer:
5245 if (!Visit(E->getSubExpr()))
5246 return false;
5247 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5248 PathE = E->path_end(); PathI != PathE; ++PathI) {
5249 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5250 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5251 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005252 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005253 }
5254 return true;
5255 }
5256}
5257
5258bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5259 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5260 // member can be formed.
5261 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5262}
5263
5264//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005265// Record Evaluation
5266//===----------------------------------------------------------------------===//
5267
5268namespace {
5269 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005270 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005271 const LValue &This;
5272 APValue &Result;
5273 public:
5274
5275 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5276 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5277
Richard Smith2e312c82012-03-03 22:46:17 +00005278 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005279 Result = V;
5280 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005281 }
Richard Smithfddd3842011-12-30 21:15:51 +00005282 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005283
Richard Smith52a980a2015-08-28 02:43:42 +00005284 bool VisitCallExpr(const CallExpr *E) {
5285 return handleCallExpr(E, Result, &This);
5286 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005287 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005288 bool VisitInitListExpr(const InitListExpr *E);
5289 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005290 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005291 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005292}
Richard Smithd62306a2011-11-10 06:34:14 +00005293
Richard Smithfddd3842011-12-30 21:15:51 +00005294/// Perform zero-initialization on an object of non-union class type.
5295/// C++11 [dcl.init]p5:
5296/// To zero-initialize an object or reference of type T means:
5297/// [...]
5298/// -- if T is a (possibly cv-qualified) non-union class type,
5299/// each non-static data member and each base-class subobject is
5300/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005301static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5302 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005303 const LValue &This, APValue &Result) {
5304 assert(!RD->isUnion() && "Expected non-union class type");
5305 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5306 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005307 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005308
John McCalld7bca762012-05-01 00:38:49 +00005309 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005310 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5311
5312 if (CD) {
5313 unsigned Index = 0;
5314 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005315 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005316 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5317 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005318 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5319 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005320 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005321 Result.getStructBase(Index)))
5322 return false;
5323 }
5324 }
5325
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005326 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005327 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005328 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005329 continue;
5330
5331 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005332 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005333 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005334
David Blaikie2d7c57e2012-04-30 02:36:29 +00005335 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005336 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005337 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005338 return false;
5339 }
5340
5341 return true;
5342}
5343
5344bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5345 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005346 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005347 if (RD->isUnion()) {
5348 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5349 // object's first non-static named data member is zero-initialized
5350 RecordDecl::field_iterator I = RD->field_begin();
5351 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005352 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005353 return true;
5354 }
5355
5356 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005357 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005358 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005359 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005360 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005361 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005362 }
5363
Richard Smith5d108602012-02-17 00:44:16 +00005364 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005365 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005366 return false;
5367 }
5368
Richard Smitha8105bc2012-01-06 16:39:00 +00005369 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005370}
5371
Richard Smithe97cbd72011-11-11 04:05:33 +00005372bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5373 switch (E->getCastKind()) {
5374 default:
5375 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5376
5377 case CK_ConstructorConversion:
5378 return Visit(E->getSubExpr());
5379
5380 case CK_DerivedToBase:
5381 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005382 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005383 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005384 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005385 if (!DerivedObject.isStruct())
5386 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005387
5388 // Derived-to-base rvalue conversion: just slice off the derived part.
5389 APValue *Value = &DerivedObject;
5390 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5391 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5392 PathE = E->path_end(); PathI != PathE; ++PathI) {
5393 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5394 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5395 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5396 RD = Base;
5397 }
5398 Result = *Value;
5399 return true;
5400 }
5401 }
5402}
5403
Richard Smithd62306a2011-11-10 06:34:14 +00005404bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5405 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005406 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005407 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5408
5409 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005410 const FieldDecl *Field = E->getInitializedFieldInUnion();
5411 Result = APValue(Field);
5412 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005413 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005414
5415 // If the initializer list for a union does not contain any elements, the
5416 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005417 // FIXME: The element should be initialized from an initializer list.
5418 // Is this difference ever observable for initializer lists which
5419 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005420 ImplicitValueInitExpr VIE(Field->getType());
5421 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5422
Richard Smithd62306a2011-11-10 06:34:14 +00005423 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005424 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5425 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005426
5427 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5428 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5429 isa<CXXDefaultInitExpr>(InitExpr));
5430
Richard Smithb228a862012-02-15 02:18:13 +00005431 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005432 }
5433
Richard Smith872307e2016-03-08 22:17:41 +00005434 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
5435 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005436 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005437 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005438 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005439
5440 // Initialize base classes.
5441 if (CXXRD) {
5442 for (const auto &Base : CXXRD->bases()) {
5443 assert(ElementNo < E->getNumInits() && "missing init for base class");
5444 const Expr *Init = E->getInit(ElementNo);
5445
5446 LValue Subobject = This;
5447 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5448 return false;
5449
5450 APValue &FieldVal = Result.getStructBase(ElementNo);
5451 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
5452 if (!Info.keepEvaluatingAfterFailure())
5453 return false;
5454 Success = false;
5455 }
5456 ++ElementNo;
5457 }
5458 }
5459
5460 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005461 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005462 // Anonymous bit-fields are not considered members of the class for
5463 // purposes of aggregate initialization.
5464 if (Field->isUnnamedBitfield())
5465 continue;
5466
5467 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005468
Richard Smith253c2a32012-01-27 01:14:48 +00005469 bool HaveInit = ElementNo < E->getNumInits();
5470
5471 // FIXME: Diagnostics here should point to the end of the initializer
5472 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005473 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005474 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005475 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005476
5477 // Perform an implicit value-initialization for members beyond the end of
5478 // the initializer list.
5479 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005480 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005481
Richard Smith852c9db2013-04-20 22:23:05 +00005482 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5483 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5484 isa<CXXDefaultInitExpr>(Init));
5485
Richard Smith49ca8aa2013-08-06 07:09:20 +00005486 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5487 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5488 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005489 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005490 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005491 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005492 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005493 }
5494 }
5495
Richard Smith253c2a32012-01-27 01:14:48 +00005496 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005497}
5498
5499bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5500 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005501 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5502
Richard Smithfddd3842011-12-30 21:15:51 +00005503 bool ZeroInit = E->requiresZeroInitialization();
5504 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005505 // If we've already performed zero-initialization, we're already done.
5506 if (!Result.isUninit())
5507 return true;
5508
Richard Smithda3f4fd2014-03-05 23:32:50 +00005509 // We can get here in two different ways:
5510 // 1) We're performing value-initialization, and should zero-initialize
5511 // the object, or
5512 // 2) We're performing default-initialization of an object with a trivial
5513 // constexpr default constructor, in which case we should start the
5514 // lifetimes of all the base subobjects (there can be no data member
5515 // subobjects in this case) per [basic.life]p1.
5516 // Either way, ZeroInitialization is appropriate.
5517 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005518 }
5519
Craig Topper36250ad2014-05-12 05:36:57 +00005520 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005521 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005522
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005523 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005524 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005525
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005526 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005527 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005528 if (const MaterializeTemporaryExpr *ME
5529 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5530 return Visit(ME->GetTemporaryExpr());
5531
Richard Smithfddd3842011-12-30 21:15:51 +00005532 if (ZeroInit && !ZeroInitialization(E))
5533 return false;
5534
Craig Topper5fc8fc22014-08-27 06:28:36 +00005535 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005536 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005537 cast<CXXConstructorDecl>(Definition), Info,
5538 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005539}
5540
Richard Smithcc1b96d2013-06-12 22:31:48 +00005541bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5542 const CXXStdInitializerListExpr *E) {
5543 const ConstantArrayType *ArrayType =
5544 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5545
5546 LValue Array;
5547 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5548 return false;
5549
5550 // Get a pointer to the first element of the array.
5551 Array.addArray(Info, E, ArrayType);
5552
5553 // FIXME: Perform the checks on the field types in SemaInit.
5554 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5555 RecordDecl::field_iterator Field = Record->field_begin();
5556 if (Field == Record->field_end())
5557 return Error(E);
5558
5559 // Start pointer.
5560 if (!Field->getType()->isPointerType() ||
5561 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5562 ArrayType->getElementType()))
5563 return Error(E);
5564
5565 // FIXME: What if the initializer_list type has base classes, etc?
5566 Result = APValue(APValue::UninitStruct(), 0, 2);
5567 Array.moveInto(Result.getStructField(0));
5568
5569 if (++Field == Record->field_end())
5570 return Error(E);
5571
5572 if (Field->getType()->isPointerType() &&
5573 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5574 ArrayType->getElementType())) {
5575 // End pointer.
5576 if (!HandleLValueArrayAdjustment(Info, E, Array,
5577 ArrayType->getElementType(),
5578 ArrayType->getSize().getZExtValue()))
5579 return false;
5580 Array.moveInto(Result.getStructField(1));
5581 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5582 // Length.
5583 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5584 else
5585 return Error(E);
5586
5587 if (++Field != Record->field_end())
5588 return Error(E);
5589
5590 return true;
5591}
5592
Richard Smithd62306a2011-11-10 06:34:14 +00005593static bool EvaluateRecord(const Expr *E, const LValue &This,
5594 APValue &Result, EvalInfo &Info) {
5595 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005596 "can't evaluate expression as a record rvalue");
5597 return RecordExprEvaluator(Info, This, Result).Visit(E);
5598}
5599
5600//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005601// Temporary Evaluation
5602//
5603// Temporaries are represented in the AST as rvalues, but generally behave like
5604// lvalues. The full-object of which the temporary is a subobject is implicitly
5605// materialized so that a reference can bind to it.
5606//===----------------------------------------------------------------------===//
5607namespace {
5608class TemporaryExprEvaluator
5609 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5610public:
5611 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5612 LValueExprEvaluatorBaseTy(Info, Result) {}
5613
5614 /// Visit an expression which constructs the value of this temporary.
5615 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005616 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005617 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5618 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005619 }
5620
5621 bool VisitCastExpr(const CastExpr *E) {
5622 switch (E->getCastKind()) {
5623 default:
5624 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5625
5626 case CK_ConstructorConversion:
5627 return VisitConstructExpr(E->getSubExpr());
5628 }
5629 }
5630 bool VisitInitListExpr(const InitListExpr *E) {
5631 return VisitConstructExpr(E);
5632 }
5633 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5634 return VisitConstructExpr(E);
5635 }
5636 bool VisitCallExpr(const CallExpr *E) {
5637 return VisitConstructExpr(E);
5638 }
Richard Smith513955c2014-12-17 19:24:30 +00005639 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5640 return VisitConstructExpr(E);
5641 }
Richard Smith027bf112011-11-17 22:56:20 +00005642};
5643} // end anonymous namespace
5644
5645/// Evaluate an expression of record type as a temporary.
5646static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005647 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005648 return TemporaryExprEvaluator(Info, Result).Visit(E);
5649}
5650
5651//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005652// Vector Evaluation
5653//===----------------------------------------------------------------------===//
5654
5655namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005656 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005657 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005658 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005659 public:
Mike Stump11289f42009-09-09 15:08:12 +00005660
Richard Smith2d406342011-10-22 21:10:00 +00005661 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5662 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005663
Craig Topper9798b932015-09-29 04:30:05 +00005664 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005665 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5666 // FIXME: remove this APValue copy.
5667 Result = APValue(V.data(), V.size());
5668 return true;
5669 }
Richard Smith2e312c82012-03-03 22:46:17 +00005670 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005671 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005672 Result = V;
5673 return true;
5674 }
Richard Smithfddd3842011-12-30 21:15:51 +00005675 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005676
Richard Smith2d406342011-10-22 21:10:00 +00005677 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005678 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005679 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005680 bool VisitInitListExpr(const InitListExpr *E);
5681 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005682 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005683 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005684 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005685 };
5686} // end anonymous namespace
5687
5688static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005689 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005690 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005691}
5692
George Burgess IV533ff002015-12-11 00:23:35 +00005693bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005694 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005695 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005696
Richard Smith161f09a2011-12-06 22:44:34 +00005697 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005698 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005699
Eli Friedmanc757de22011-03-25 00:43:55 +00005700 switch (E->getCastKind()) {
5701 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005702 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005703 if (SETy->isIntegerType()) {
5704 APSInt IntResult;
5705 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005706 return false;
5707 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005708 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005709 APFloat FloatResult(0.0);
5710 if (!EvaluateFloat(SE, FloatResult, Info))
5711 return false;
5712 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005713 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005714 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005715 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005716
5717 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005718 SmallVector<APValue, 4> Elts(NElts, Val);
5719 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005720 }
Eli Friedman803acb32011-12-22 03:51:45 +00005721 case CK_BitCast: {
5722 // Evaluate the operand into an APInt we can extract from.
5723 llvm::APInt SValInt;
5724 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5725 return false;
5726 // Extract the elements
5727 QualType EltTy = VTy->getElementType();
5728 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5729 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5730 SmallVector<APValue, 4> Elts;
5731 if (EltTy->isRealFloatingType()) {
5732 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005733 unsigned FloatEltSize = EltSize;
5734 if (&Sem == &APFloat::x87DoubleExtended)
5735 FloatEltSize = 80;
5736 for (unsigned i = 0; i < NElts; i++) {
5737 llvm::APInt Elt;
5738 if (BigEndian)
5739 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5740 else
5741 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005742 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005743 }
5744 } else if (EltTy->isIntegerType()) {
5745 for (unsigned i = 0; i < NElts; i++) {
5746 llvm::APInt Elt;
5747 if (BigEndian)
5748 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5749 else
5750 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5751 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5752 }
5753 } else {
5754 return Error(E);
5755 }
5756 return Success(Elts, E);
5757 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005758 default:
Richard Smith11562c52011-10-28 17:51:58 +00005759 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005760 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005761}
5762
Richard Smith2d406342011-10-22 21:10:00 +00005763bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005764VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005765 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005766 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005767 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005768
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005769 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005770 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005771
Eli Friedmanb9c71292012-01-03 23:24:20 +00005772 // The number of initializers can be less than the number of
5773 // vector elements. For OpenCL, this can be due to nested vector
5774 // initialization. For GCC compatibility, missing trailing elements
5775 // should be initialized with zeroes.
5776 unsigned CountInits = 0, CountElts = 0;
5777 while (CountElts < NumElements) {
5778 // Handle nested vector initialization.
5779 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005780 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005781 APValue v;
5782 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5783 return Error(E);
5784 unsigned vlen = v.getVectorLength();
5785 for (unsigned j = 0; j < vlen; j++)
5786 Elements.push_back(v.getVectorElt(j));
5787 CountElts += vlen;
5788 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005789 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005790 if (CountInits < NumInits) {
5791 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005792 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005793 } else // trailing integer zero.
5794 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5795 Elements.push_back(APValue(sInt));
5796 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005797 } else {
5798 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005799 if (CountInits < NumInits) {
5800 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005801 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005802 } else // trailing float zero.
5803 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5804 Elements.push_back(APValue(f));
5805 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005806 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005807 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005808 }
Richard Smith2d406342011-10-22 21:10:00 +00005809 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005810}
5811
Richard Smith2d406342011-10-22 21:10:00 +00005812bool
Richard Smithfddd3842011-12-30 21:15:51 +00005813VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005814 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005815 QualType EltTy = VT->getElementType();
5816 APValue ZeroElement;
5817 if (EltTy->isIntegerType())
5818 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5819 else
5820 ZeroElement =
5821 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5822
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005823 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005824 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005825}
5826
Richard Smith2d406342011-10-22 21:10:00 +00005827bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005828 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005829 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005830}
5831
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005832//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005833// Array Evaluation
5834//===----------------------------------------------------------------------===//
5835
5836namespace {
5837 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005838 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005839 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005840 APValue &Result;
5841 public:
5842
Richard Smithd62306a2011-11-10 06:34:14 +00005843 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5844 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005845
5846 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005847 assert((V.isArray() || V.isLValue()) &&
5848 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005849 Result = V;
5850 return true;
5851 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005852
Richard Smithfddd3842011-12-30 21:15:51 +00005853 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005854 const ConstantArrayType *CAT =
5855 Info.Ctx.getAsConstantArrayType(E->getType());
5856 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005857 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005858
5859 Result = APValue(APValue::UninitArray(), 0,
5860 CAT->getSize().getZExtValue());
5861 if (!Result.hasArrayFiller()) return true;
5862
Richard Smithfddd3842011-12-30 21:15:51 +00005863 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005864 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005865 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005866 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005867 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005868 }
5869
Richard Smith52a980a2015-08-28 02:43:42 +00005870 bool VisitCallExpr(const CallExpr *E) {
5871 return handleCallExpr(E, Result, &This);
5872 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005873 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005874 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005875 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5876 const LValue &Subobject,
5877 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005878 };
5879} // end anonymous namespace
5880
Richard Smithd62306a2011-11-10 06:34:14 +00005881static bool EvaluateArray(const Expr *E, const LValue &This,
5882 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005883 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005884 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005885}
5886
5887bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5888 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5889 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005890 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005891
Richard Smithca2cfbf2011-12-22 01:07:19 +00005892 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5893 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005894 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005895 LValue LV;
5896 if (!EvaluateLValue(E->getInit(0), LV, Info))
5897 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005898 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005899 LV.moveInto(Val);
5900 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005901 }
5902
Richard Smith253c2a32012-01-27 01:14:48 +00005903 bool Success = true;
5904
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005905 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5906 "zero-initialized array shouldn't have any initialized elts");
5907 APValue Filler;
5908 if (Result.isArray() && Result.hasArrayFiller())
5909 Filler = Result.getArrayFiller();
5910
Richard Smith9543c5e2013-04-22 14:44:29 +00005911 unsigned NumEltsToInit = E->getNumInits();
5912 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005913 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005914
5915 // If the initializer might depend on the array index, run it for each
5916 // array element. For now, just whitelist non-class value-initialization.
5917 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5918 NumEltsToInit = NumElts;
5919
5920 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005921
5922 // If the array was previously zero-initialized, preserve the
5923 // zero-initialized values.
5924 if (!Filler.isUninit()) {
5925 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5926 Result.getArrayInitializedElt(I) = Filler;
5927 if (Result.hasArrayFiller())
5928 Result.getArrayFiller() = Filler;
5929 }
5930
Richard Smithd62306a2011-11-10 06:34:14 +00005931 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005932 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005933 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5934 const Expr *Init =
5935 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005936 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005937 Info, Subobject, Init) ||
5938 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005939 CAT->getElementType(), 1)) {
5940 if (!Info.keepEvaluatingAfterFailure())
5941 return false;
5942 Success = false;
5943 }
Richard Smithd62306a2011-11-10 06:34:14 +00005944 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005945
Richard Smith9543c5e2013-04-22 14:44:29 +00005946 if (!Result.hasArrayFiller())
5947 return Success;
5948
5949 // If we get here, we have a trivial filler, which we can just evaluate
5950 // once and splat over the rest of the array elements.
5951 assert(FillerExpr && "no array filler for incomplete init list");
5952 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5953 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005954}
5955
Richard Smith027bf112011-11-17 22:56:20 +00005956bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005957 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5958}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005959
Richard Smith9543c5e2013-04-22 14:44:29 +00005960bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5961 const LValue &Subobject,
5962 APValue *Value,
5963 QualType Type) {
5964 bool HadZeroInit = !Value->isUninit();
5965
5966 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5967 unsigned N = CAT->getSize().getZExtValue();
5968
5969 // Preserve the array filler if we had prior zero-initialization.
5970 APValue Filler =
5971 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5972 : APValue();
5973
5974 *Value = APValue(APValue::UninitArray(), N, N);
5975
5976 if (HadZeroInit)
5977 for (unsigned I = 0; I != N; ++I)
5978 Value->getArrayInitializedElt(I) = Filler;
5979
5980 // Initialize the elements.
5981 LValue ArrayElt = Subobject;
5982 ArrayElt.addArray(Info, E, CAT);
5983 for (unsigned I = 0; I != N; ++I)
5984 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5985 CAT->getElementType()) ||
5986 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5987 CAT->getElementType(), 1))
5988 return false;
5989
5990 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005991 }
Richard Smith027bf112011-11-17 22:56:20 +00005992
Richard Smith9543c5e2013-04-22 14:44:29 +00005993 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005994 return Error(E);
5995
Richard Smith027bf112011-11-17 22:56:20 +00005996 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005997
Richard Smithfddd3842011-12-30 21:15:51 +00005998 bool ZeroInit = E->requiresZeroInitialization();
5999 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006000 if (HadZeroInit)
6001 return true;
6002
Richard Smithda3f4fd2014-03-05 23:32:50 +00006003 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
6004 ImplicitValueInitExpr VIE(Type);
6005 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00006006 }
6007
Craig Topper36250ad2014-05-12 05:36:57 +00006008 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006009 auto Body = FD->getBody(Definition);
Richard Smith027bf112011-11-17 22:56:20 +00006010
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006011 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006012 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006013
Richard Smith9eae7232012-01-12 18:54:33 +00006014 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006015 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006016 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006017 return false;
6018 }
6019
Craig Topper5fc8fc22014-08-27 06:28:36 +00006020 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00006021 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00006022 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006023 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00006024}
6025
Richard Smithf3e9e432011-11-07 09:22:26 +00006026//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006027// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006028//
6029// As a GNU extension, we support casting pointers to sufficiently-wide integer
6030// types and back in constant folding. Integer values are thus represented
6031// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006032//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006033
6034namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006035class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006036 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006037 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006038public:
Richard Smith2e312c82012-03-03 22:46:17 +00006039 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006040 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006041
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006042 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006043 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006044 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006045 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006046 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006047 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006048 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006049 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006050 return true;
6051 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006052 bool Success(const llvm::APSInt &SI, const Expr *E) {
6053 return Success(SI, E, Result);
6054 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006055
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006056 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006057 assert(E->getType()->isIntegralOrEnumerationType() &&
6058 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006059 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006060 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006061 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006062 Result.getInt().setIsUnsigned(
6063 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006064 return true;
6065 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006066 bool Success(const llvm::APInt &I, const Expr *E) {
6067 return Success(I, E, Result);
6068 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006069
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006070 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006071 assert(E->getType()->isIntegralOrEnumerationType() &&
6072 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006073 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006074 return true;
6075 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006076 bool Success(uint64_t Value, const Expr *E) {
6077 return Success(Value, E, Result);
6078 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006079
Ken Dyckdbc01912011-03-11 02:13:43 +00006080 bool Success(CharUnits Size, const Expr *E) {
6081 return Success(Size.getQuantity(), E);
6082 }
6083
Richard Smith2e312c82012-03-03 22:46:17 +00006084 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006085 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006086 Result = V;
6087 return true;
6088 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006089 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006090 }
Mike Stump11289f42009-09-09 15:08:12 +00006091
Richard Smithfddd3842011-12-30 21:15:51 +00006092 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006093
Peter Collingbournee9200682011-05-13 03:29:01 +00006094 //===--------------------------------------------------------------------===//
6095 // Visitor Methods
6096 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006097
Chris Lattner7174bf32008-07-12 00:38:25 +00006098 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006099 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006100 }
6101 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006102 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006103 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006104
6105 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6106 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006107 if (CheckReferencedDecl(E, E->getDecl()))
6108 return true;
6109
6110 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006111 }
6112 bool VisitMemberExpr(const MemberExpr *E) {
6113 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006114 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006115 return true;
6116 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006117
6118 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006119 }
6120
Peter Collingbournee9200682011-05-13 03:29:01 +00006121 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006122 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006123 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006124 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006125
Peter Collingbournee9200682011-05-13 03:29:01 +00006126 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006127 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006128
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006129 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006130 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006131 }
Mike Stump11289f42009-09-09 15:08:12 +00006132
Ted Kremeneke65b0862012-03-06 20:05:56 +00006133 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6134 return Success(E->getValue(), E);
6135 }
6136
Richard Smith4ce706a2011-10-11 21:43:33 +00006137 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006138 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006139 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006140 }
6141
Douglas Gregor29c42f22012-02-24 07:38:34 +00006142 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6143 return Success(E->getValue(), E);
6144 }
6145
John Wiegley6242b6a2011-04-28 00:16:57 +00006146 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6147 return Success(E->getValue(), E);
6148 }
6149
John Wiegleyf9f65842011-04-25 06:54:41 +00006150 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6151 return Success(E->getValue(), E);
6152 }
6153
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006154 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006155 bool VisitUnaryImag(const UnaryOperator *E);
6156
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006157 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006158 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006159
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006160private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006161 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006162 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006163};
Chris Lattner05706e882008-07-11 18:11:29 +00006164} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006165
Richard Smith11562c52011-10-28 17:51:58 +00006166/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6167/// produce either the integer value or a pointer.
6168///
6169/// GCC has a heinous extension which folds casts between pointer types and
6170/// pointer-sized integral types. We support this by allowing the evaluation of
6171/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6172/// Some simple arithmetic on such values is supported (they are treated much
6173/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006174static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006175 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006176 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006177 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006178}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006179
Richard Smithf57d8cb2011-12-09 22:58:01 +00006180static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006181 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006182 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006183 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006184 if (!Val.isInt()) {
6185 // FIXME: It would be better to produce the diagnostic for casting
6186 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006187 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006188 return false;
6189 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006190 Result = Val.getInt();
6191 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006192}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006193
Richard Smithf57d8cb2011-12-09 22:58:01 +00006194/// Check whether the given declaration can be directly converted to an integral
6195/// rvalue. If not, no diagnostic is produced; there are other things we can
6196/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006197bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006198 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006199 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006200 // Check for signedness/width mismatches between E type and ECD value.
6201 bool SameSign = (ECD->getInitVal().isSigned()
6202 == E->getType()->isSignedIntegerOrEnumerationType());
6203 bool SameWidth = (ECD->getInitVal().getBitWidth()
6204 == Info.Ctx.getIntWidth(E->getType()));
6205 if (SameSign && SameWidth)
6206 return Success(ECD->getInitVal(), E);
6207 else {
6208 // Get rid of mismatch (otherwise Success assertions will fail)
6209 // by computing a new value matching the type of E.
6210 llvm::APSInt Val = ECD->getInitVal();
6211 if (!SameSign)
6212 Val.setIsSigned(!ECD->getInitVal().isSigned());
6213 if (!SameWidth)
6214 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6215 return Success(Val, E);
6216 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006217 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006218 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006219}
6220
Chris Lattner86ee2862008-10-06 06:40:35 +00006221/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6222/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006223static int EvaluateBuiltinClassifyType(const CallExpr *E,
6224 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006225 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006226 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006227 enum gcc_type_class {
6228 no_type_class = -1,
6229 void_type_class, integer_type_class, char_type_class,
6230 enumeral_type_class, boolean_type_class,
6231 pointer_type_class, reference_type_class, offset_type_class,
6232 real_type_class, complex_type_class,
6233 function_type_class, method_type_class,
6234 record_type_class, union_type_class,
6235 array_type_class, string_type_class,
6236 lang_type_class
6237 };
Mike Stump11289f42009-09-09 15:08:12 +00006238
6239 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006240 // ideal, however it is what gcc does.
6241 if (E->getNumArgs() == 0)
6242 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006243
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006244 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6245 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6246
6247 switch (CanTy->getTypeClass()) {
6248#define TYPE(ID, BASE)
6249#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6250#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6251#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6252#include "clang/AST/TypeNodes.def"
6253 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6254
6255 case Type::Builtin:
6256 switch (BT->getKind()) {
6257#define BUILTIN_TYPE(ID, SINGLETON_ID)
6258#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6259#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6260#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6261#include "clang/AST/BuiltinTypes.def"
6262 case BuiltinType::Void:
6263 return void_type_class;
6264
6265 case BuiltinType::Bool:
6266 return boolean_type_class;
6267
6268 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6269 case BuiltinType::UChar:
6270 case BuiltinType::UShort:
6271 case BuiltinType::UInt:
6272 case BuiltinType::ULong:
6273 case BuiltinType::ULongLong:
6274 case BuiltinType::UInt128:
6275 return integer_type_class;
6276
6277 case BuiltinType::NullPtr:
6278 return pointer_type_class;
6279
6280 case BuiltinType::WChar_U:
6281 case BuiltinType::Char16:
6282 case BuiltinType::Char32:
6283 case BuiltinType::ObjCId:
6284 case BuiltinType::ObjCClass:
6285 case BuiltinType::ObjCSel:
6286 case BuiltinType::OCLImage1d:
6287 case BuiltinType::OCLImage1dArray:
6288 case BuiltinType::OCLImage2d:
6289 case BuiltinType::OCLImage2dArray:
6290 case BuiltinType::OCLImage1dBuffer:
6291 case BuiltinType::OCLImage2dDepth:
6292 case BuiltinType::OCLImage2dArrayDepth:
6293 case BuiltinType::OCLImage2dMSAA:
6294 case BuiltinType::OCLImage2dArrayMSAA:
6295 case BuiltinType::OCLImage2dMSAADepth:
6296 case BuiltinType::OCLImage2dArrayMSAADepth:
6297 case BuiltinType::OCLImage3d:
6298 case BuiltinType::OCLSampler:
6299 case BuiltinType::OCLEvent:
6300 case BuiltinType::OCLClkEvent:
6301 case BuiltinType::OCLQueue:
6302 case BuiltinType::OCLNDRange:
6303 case BuiltinType::OCLReserveID:
6304 case BuiltinType::Dependent:
6305 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6306 };
6307
6308 case Type::Enum:
6309 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6310 break;
6311
6312 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006313 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006314 break;
6315
6316 case Type::MemberPointer:
6317 if (CanTy->isMemberDataPointerType())
6318 return offset_type_class;
6319 else {
6320 // We expect member pointers to be either data or function pointers,
6321 // nothing else.
6322 assert(CanTy->isMemberFunctionPointerType());
6323 return method_type_class;
6324 }
6325
6326 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006327 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006328
6329 case Type::FunctionNoProto:
6330 case Type::FunctionProto:
6331 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6332
6333 case Type::Record:
6334 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6335 switch (RT->getDecl()->getTagKind()) {
6336 case TagTypeKind::TTK_Struct:
6337 case TagTypeKind::TTK_Class:
6338 case TagTypeKind::TTK_Interface:
6339 return record_type_class;
6340
6341 case TagTypeKind::TTK_Enum:
6342 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6343
6344 case TagTypeKind::TTK_Union:
6345 return union_type_class;
6346 }
6347 }
David Blaikie83d382b2011-09-23 05:06:16 +00006348 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006349
6350 case Type::ConstantArray:
6351 case Type::VariableArray:
6352 case Type::IncompleteArray:
6353 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6354
6355 case Type::BlockPointer:
6356 case Type::LValueReference:
6357 case Type::RValueReference:
6358 case Type::Vector:
6359 case Type::ExtVector:
6360 case Type::Auto:
6361 case Type::ObjCObject:
6362 case Type::ObjCInterface:
6363 case Type::ObjCObjectPointer:
6364 case Type::Pipe:
6365 case Type::Atomic:
6366 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6367 }
6368
6369 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006370}
6371
Richard Smith5fab0c92011-12-28 19:48:30 +00006372/// EvaluateBuiltinConstantPForLValue - Determine the result of
6373/// __builtin_constant_p when applied to the given lvalue.
6374///
6375/// An lvalue is only "constant" if it is a pointer or reference to the first
6376/// character of a string literal.
6377template<typename LValue>
6378static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006379 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006380 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6381}
6382
6383/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6384/// GCC as we can manage.
6385static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6386 QualType ArgType = Arg->getType();
6387
6388 // __builtin_constant_p always has one operand. The rules which gcc follows
6389 // are not precisely documented, but are as follows:
6390 //
6391 // - If the operand is of integral, floating, complex or enumeration type,
6392 // and can be folded to a known value of that type, it returns 1.
6393 // - If the operand and can be folded to a pointer to the first character
6394 // of a string literal (or such a pointer cast to an integral type), it
6395 // returns 1.
6396 //
6397 // Otherwise, it returns 0.
6398 //
6399 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6400 // its support for this does not currently work.
6401 if (ArgType->isIntegralOrEnumerationType()) {
6402 Expr::EvalResult Result;
6403 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6404 return false;
6405
6406 APValue &V = Result.Val;
6407 if (V.getKind() == APValue::Int)
6408 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006409 if (V.getKind() == APValue::LValue)
6410 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006411 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6412 return Arg->isEvaluatable(Ctx);
6413 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6414 LValue LV;
6415 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006416 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006417 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6418 : EvaluatePointer(Arg, LV, Info)) &&
6419 !Status.HasSideEffects)
6420 return EvaluateBuiltinConstantPForLValue(LV);
6421 }
6422
6423 // Anything else isn't considered to be sufficiently constant.
6424 return false;
6425}
6426
John McCall95007602010-05-10 23:27:23 +00006427/// Retrieves the "underlying object type" of the given expression,
6428/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006429static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006430 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6431 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006432 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006433 } else if (const Expr *E = B.get<const Expr*>()) {
6434 if (isa<CompoundLiteralExpr>(E))
6435 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006436 }
6437
6438 return QualType();
6439}
6440
George Burgess IV3a03fab2015-09-04 21:28:13 +00006441/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006442/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6443/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006444/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6445///
6446/// Always returns an RValue with a pointer representation.
6447static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6448 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6449
6450 auto *NoParens = E->IgnoreParens();
6451 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006452 if (Cast == nullptr)
6453 return NoParens;
6454
6455 // We only conservatively allow a few kinds of casts, because this code is
6456 // inherently a simple solution that seeks to support the common case.
6457 auto CastKind = Cast->getCastKind();
6458 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6459 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006460 return NoParens;
6461
6462 auto *SubExpr = Cast->getSubExpr();
6463 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6464 return NoParens;
6465 return ignorePointerCastsAndParens(SubExpr);
6466}
6467
George Burgess IVa51c4072015-10-16 01:49:01 +00006468/// Checks to see if the given LValue's Designator is at the end of the LValue's
6469/// record layout. e.g.
6470/// struct { struct { int a, b; } fst, snd; } obj;
6471/// obj.fst // no
6472/// obj.snd // yes
6473/// obj.fst.a // no
6474/// obj.fst.b // no
6475/// obj.snd.a // no
6476/// obj.snd.b // yes
6477///
6478/// Please note: this function is specialized for how __builtin_object_size
6479/// views "objects".
6480static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6481 assert(!LVal.Designator.Invalid);
6482
6483 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6484 if (FD->getParent()->isUnion())
6485 return true;
6486 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6487 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6488 };
6489
6490 auto &Base = LVal.getLValueBase();
6491 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6492 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6493 if (!IsLastFieldDecl(FD))
6494 return false;
6495 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6496 for (auto *FD : IFD->chain())
6497 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6498 return false;
6499 }
6500 }
6501
6502 QualType BaseType = getType(Base);
6503 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6504 if (BaseType->isArrayType()) {
6505 // Because __builtin_object_size treats arrays as objects, we can ignore
6506 // the index iff this is the last array in the Designator.
6507 if (I + 1 == E)
6508 return true;
6509 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6510 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6511 if (Index + 1 != CAT->getSize())
6512 return false;
6513 BaseType = CAT->getElementType();
6514 } else if (BaseType->isAnyComplexType()) {
6515 auto *CT = BaseType->castAs<ComplexType>();
6516 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6517 if (Index != 1)
6518 return false;
6519 BaseType = CT->getElementType();
6520 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6521 if (!IsLastFieldDecl(FD))
6522 return false;
6523 BaseType = FD->getType();
6524 } else {
6525 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6526 "Expecting cast to a base class");
6527 return false;
6528 }
6529 }
6530 return true;
6531}
6532
6533/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6534static bool refersToCompleteObject(const LValue &LVal) {
6535 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6536 return false;
6537
6538 if (!LVal.InvalidBase)
6539 return true;
6540
6541 auto *E = LVal.Base.dyn_cast<const Expr *>();
6542 (void)E;
6543 assert(E != nullptr && isa<MemberExpr>(E));
6544 return false;
6545}
6546
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006547/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6548/// true and stores the result in @p Size.
6549///
6550/// If @p WasError is non-null, this will report whether the failure to evaluate
6551/// is to be treated as an Error in IntExprEvaluator.
6552static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6553 EvalInfo &Info, uint64_t &Size,
6554 bool *WasError = nullptr) {
6555 if (WasError != nullptr)
6556 *WasError = false;
6557
6558 auto Error = [&](const Expr *E) {
6559 if (WasError != nullptr)
6560 *WasError = true;
6561 return false;
6562 };
6563
6564 auto Success = [&](uint64_t S, const Expr *E) {
6565 Size = S;
6566 return true;
6567 };
6568
George Burgess IVbdb5b262015-08-19 02:19:07 +00006569 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006570 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006571 {
6572 // The operand of __builtin_object_size is never evaluated for side-effects.
6573 // If there are any, but we can determine the pointed-to object anyway, then
6574 // ignore the side-effects.
6575 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006576 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006577
6578 if (E->isGLValue()) {
6579 // It's possible for us to be given GLValues if we're called via
6580 // Expr::tryEvaluateObjectSize.
6581 APValue RVal;
6582 if (!EvaluateAsRValue(Info, E, RVal))
6583 return false;
6584 Base.setFrom(Info.Ctx, RVal);
6585 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006586 return false;
6587 }
John McCall95007602010-05-10 23:27:23 +00006588
George Burgess IVbdb5b262015-08-19 02:19:07 +00006589 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006590 // If we point to before the start of the object, there are no accessible
6591 // bytes.
6592 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006593 return Success(0, E);
6594
George Burgess IV3a03fab2015-09-04 21:28:13 +00006595 // In the case where we're not dealing with a subobject, we discard the
6596 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006597 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006598
6599 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6600 // exist. If we can't verify the base, then we can't do that.
6601 //
6602 // As a special case, we produce a valid object size for an unknown object
6603 // with a known designator if Type & 1 is 1. For instance:
6604 //
6605 // extern struct X { char buff[32]; int a, b, c; } *p;
6606 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6607 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6608 //
6609 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006610 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006611 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006612
George Burgess IVa51c4072015-10-16 01:49:01 +00006613 // If we're not examining only the subobject, then we reset to a complete
6614 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006615 //
6616 // If Type is 1 and we've lost track of the subobject, just find the complete
6617 // object instead. (If Type is 3, that's not correct behavior and we should
6618 // return 0 instead.)
6619 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006620 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006621 QualType T = getObjectType(End.getLValueBase());
6622 if (T.isNull())
6623 End.Designator.setInvalid();
6624 else {
6625 End.Designator = SubobjectDesignator(T);
6626 End.Offset = CharUnits::Zero();
6627 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006628 }
John McCall95007602010-05-10 23:27:23 +00006629
George Burgess IVbdb5b262015-08-19 02:19:07 +00006630 // If it is not possible to determine which objects ptr points to at compile
6631 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6632 // and (size_t) 0 for type 2 or 3.
6633 if (End.Designator.Invalid)
6634 return false;
6635
6636 // According to the GCC documentation, we want the size of the subobject
6637 // denoted by the pointer. But that's not quite right -- what we actually
6638 // want is the size of the immediately-enclosing array, if there is one.
6639 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006640 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006641 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6642 // We got a pointer to an array. Step to its end.
6643 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006644 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006645 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006646 // We're already pointing at the end of the object.
6647 AmountToAdd = 0;
6648 }
6649
George Burgess IV3a03fab2015-09-04 21:28:13 +00006650 QualType PointeeType = End.Designator.MostDerivedType;
6651 assert(!PointeeType.isNull());
6652 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006653 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006654
George Burgess IVbdb5b262015-08-19 02:19:07 +00006655 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6656 AmountToAdd))
6657 return false;
John McCall95007602010-05-10 23:27:23 +00006658
George Burgess IVbdb5b262015-08-19 02:19:07 +00006659 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006660
6661 // The following is a moderately common idiom in C:
6662 //
6663 // struct Foo { int a; char c[1]; };
6664 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6665 // strcpy(&F->c[0], Bar);
6666 //
6667 // So, if we see that we're examining a 1-length (or 0-length) array at the
6668 // end of a struct with an unknown base, we give up instead of breaking code
6669 // that behaves this way. Note that we only do this when Type=1, because
6670 // Type=3 is a lower bound, so answering conservatively is fine.
6671 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6672 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6673 End.Designator.MostDerivedIsArrayElement &&
6674 End.Designator.MostDerivedArraySize < 2 &&
6675 isDesignatorAtObjectEnd(Info.Ctx, End))
6676 return false;
6677
George Burgess IVbdb5b262015-08-19 02:19:07 +00006678 if (BaseOffset > EndOffset)
6679 return Success(0, E);
6680
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006681 return Success((EndOffset - BaseOffset).getQuantity(), E);
6682}
6683
6684bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6685 unsigned Type) {
6686 uint64_t Size;
6687 bool WasError;
6688 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6689 return Success(Size, E);
6690 if (WasError)
6691 return Error(E);
6692 return false;
John McCall95007602010-05-10 23:27:23 +00006693}
6694
Peter Collingbournee9200682011-05-13 03:29:01 +00006695bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006696 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006697 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006698 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006699
6700 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006701 // The type was checked when we built the expression.
6702 unsigned Type =
6703 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6704 assert(Type <= 3 && "unexpected type");
6705
6706 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006707 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006708
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006709 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006710 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006711
Richard Smith01ade172012-05-23 04:13:20 +00006712 // Expression had no side effects, but we couldn't statically determine the
6713 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006714 switch (Info.EvalMode) {
6715 case EvalInfo::EM_ConstantExpression:
6716 case EvalInfo::EM_PotentialConstantExpression:
6717 case EvalInfo::EM_ConstantFold:
6718 case EvalInfo::EM_EvaluateForOverflow:
6719 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006720 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006721 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006722 return Error(E);
6723 case EvalInfo::EM_ConstantExpressionUnevaluated:
6724 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006725 // Reduce it to a constant now.
6726 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006727 }
Mike Stump722cedf2009-10-26 18:35:08 +00006728 }
6729
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006730 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006731 case Builtin::BI__builtin_bswap32:
6732 case Builtin::BI__builtin_bswap64: {
6733 APSInt Val;
6734 if (!EvaluateInteger(E->getArg(0), Val, Info))
6735 return false;
6736
6737 return Success(Val.byteSwap(), E);
6738 }
6739
Richard Smith8889a3d2013-06-13 06:26:32 +00006740 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006741 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006742
6743 // FIXME: BI__builtin_clrsb
6744 // FIXME: BI__builtin_clrsbl
6745 // FIXME: BI__builtin_clrsbll
6746
Richard Smith80b3c8e2013-06-13 05:04:16 +00006747 case Builtin::BI__builtin_clz:
6748 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006749 case Builtin::BI__builtin_clzll:
6750 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006751 APSInt Val;
6752 if (!EvaluateInteger(E->getArg(0), Val, Info))
6753 return false;
6754 if (!Val)
6755 return Error(E);
6756
6757 return Success(Val.countLeadingZeros(), E);
6758 }
6759
Richard Smith8889a3d2013-06-13 06:26:32 +00006760 case Builtin::BI__builtin_constant_p:
6761 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6762
Richard Smith80b3c8e2013-06-13 05:04:16 +00006763 case Builtin::BI__builtin_ctz:
6764 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006765 case Builtin::BI__builtin_ctzll:
6766 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006767 APSInt Val;
6768 if (!EvaluateInteger(E->getArg(0), Val, Info))
6769 return false;
6770 if (!Val)
6771 return Error(E);
6772
6773 return Success(Val.countTrailingZeros(), E);
6774 }
6775
Richard Smith8889a3d2013-06-13 06:26:32 +00006776 case Builtin::BI__builtin_eh_return_data_regno: {
6777 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6778 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6779 return Success(Operand, E);
6780 }
6781
6782 case Builtin::BI__builtin_expect:
6783 return Visit(E->getArg(0));
6784
6785 case Builtin::BI__builtin_ffs:
6786 case Builtin::BI__builtin_ffsl:
6787 case Builtin::BI__builtin_ffsll: {
6788 APSInt Val;
6789 if (!EvaluateInteger(E->getArg(0), Val, Info))
6790 return false;
6791
6792 unsigned N = Val.countTrailingZeros();
6793 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6794 }
6795
6796 case Builtin::BI__builtin_fpclassify: {
6797 APFloat Val(0.0);
6798 if (!EvaluateFloat(E->getArg(5), Val, Info))
6799 return false;
6800 unsigned Arg;
6801 switch (Val.getCategory()) {
6802 case APFloat::fcNaN: Arg = 0; break;
6803 case APFloat::fcInfinity: Arg = 1; break;
6804 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6805 case APFloat::fcZero: Arg = 4; break;
6806 }
6807 return Visit(E->getArg(Arg));
6808 }
6809
6810 case Builtin::BI__builtin_isinf_sign: {
6811 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006812 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006813 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6814 }
6815
Richard Smithea3019d2013-10-15 19:07:14 +00006816 case Builtin::BI__builtin_isinf: {
6817 APFloat Val(0.0);
6818 return EvaluateFloat(E->getArg(0), Val, Info) &&
6819 Success(Val.isInfinity() ? 1 : 0, E);
6820 }
6821
6822 case Builtin::BI__builtin_isfinite: {
6823 APFloat Val(0.0);
6824 return EvaluateFloat(E->getArg(0), Val, Info) &&
6825 Success(Val.isFinite() ? 1 : 0, E);
6826 }
6827
6828 case Builtin::BI__builtin_isnan: {
6829 APFloat Val(0.0);
6830 return EvaluateFloat(E->getArg(0), Val, Info) &&
6831 Success(Val.isNaN() ? 1 : 0, E);
6832 }
6833
6834 case Builtin::BI__builtin_isnormal: {
6835 APFloat Val(0.0);
6836 return EvaluateFloat(E->getArg(0), Val, Info) &&
6837 Success(Val.isNormal() ? 1 : 0, E);
6838 }
6839
Richard Smith8889a3d2013-06-13 06:26:32 +00006840 case Builtin::BI__builtin_parity:
6841 case Builtin::BI__builtin_parityl:
6842 case Builtin::BI__builtin_parityll: {
6843 APSInt Val;
6844 if (!EvaluateInteger(E->getArg(0), Val, Info))
6845 return false;
6846
6847 return Success(Val.countPopulation() % 2, E);
6848 }
6849
Richard Smith80b3c8e2013-06-13 05:04:16 +00006850 case Builtin::BI__builtin_popcount:
6851 case Builtin::BI__builtin_popcountl:
6852 case Builtin::BI__builtin_popcountll: {
6853 APSInt Val;
6854 if (!EvaluateInteger(E->getArg(0), Val, Info))
6855 return false;
6856
6857 return Success(Val.countPopulation(), E);
6858 }
6859
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006860 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006861 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006862 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006863 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006864 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6865 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006866 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006867 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006868 case Builtin::BI__builtin_strlen: {
6869 // As an extension, we support __builtin_strlen() as a constant expression,
6870 // and support folding strlen() to a constant.
6871 LValue String;
6872 if (!EvaluatePointer(E->getArg(0), String, Info))
6873 return false;
6874
6875 // Fast path: if it's a string literal, search the string value.
6876 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6877 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006878 // The string literal may have embedded null characters. Find the first
6879 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006880 StringRef Str = S->getBytes();
6881 int64_t Off = String.Offset.getQuantity();
6882 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6883 S->getCharByteWidth() == 1) {
6884 Str = Str.substr(Off);
6885
6886 StringRef::size_type Pos = Str.find(0);
6887 if (Pos != StringRef::npos)
6888 Str = Str.substr(0, Pos);
6889
6890 return Success(Str.size(), E);
6891 }
6892
6893 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006894 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006895
6896 // Slow path: scan the bytes of the string looking for the terminating 0.
6897 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6898 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6899 APValue Char;
6900 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6901 !Char.isInt())
6902 return false;
6903 if (!Char.getInt())
6904 return Success(Strlen, E);
6905 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6906 return false;
6907 }
6908 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006909
Richard Smith01ba47d2012-04-13 00:45:38 +00006910 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006911 case Builtin::BI__atomic_is_lock_free:
6912 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006913 APSInt SizeVal;
6914 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6915 return false;
6916
6917 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6918 // of two less than the maximum inline atomic width, we know it is
6919 // lock-free. If the size isn't a power of two, or greater than the
6920 // maximum alignment where we promote atomics, we know it is not lock-free
6921 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6922 // the answer can only be determined at runtime; for example, 16-byte
6923 // atomics have lock-free implementations on some, but not all,
6924 // x86-64 processors.
6925
6926 // Check power-of-two.
6927 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006928 if (Size.isPowerOfTwo()) {
6929 // Check against inlining width.
6930 unsigned InlineWidthBits =
6931 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6932 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6933 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6934 Size == CharUnits::One() ||
6935 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6936 Expr::NPC_NeverValueDependent))
6937 // OK, we will inline appropriately-aligned operations of this size,
6938 // and _Atomic(T) is appropriately-aligned.
6939 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006940
Richard Smith01ba47d2012-04-13 00:45:38 +00006941 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6942 castAs<PointerType>()->getPointeeType();
6943 if (!PointeeType->isIncompleteType() &&
6944 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6945 // OK, we will inline operations on this object.
6946 return Success(1, E);
6947 }
6948 }
6949 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006950
Richard Smith01ba47d2012-04-13 00:45:38 +00006951 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6952 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006953 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006954 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006955}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006956
Richard Smith8b3497e2011-10-31 01:37:14 +00006957static bool HasSameBase(const LValue &A, const LValue &B) {
6958 if (!A.getLValueBase())
6959 return !B.getLValueBase();
6960 if (!B.getLValueBase())
6961 return false;
6962
Richard Smithce40ad62011-11-12 22:28:03 +00006963 if (A.getLValueBase().getOpaqueValue() !=
6964 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006965 const Decl *ADecl = GetLValueBaseDecl(A);
6966 if (!ADecl)
6967 return false;
6968 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006969 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006970 return false;
6971 }
6972
6973 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006974 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006975}
6976
Richard Smithd20f1e62014-10-21 23:01:04 +00006977/// \brief Determine whether this is a pointer past the end of the complete
6978/// object referred to by the lvalue.
6979static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6980 const LValue &LV) {
6981 // A null pointer can be viewed as being "past the end" but we don't
6982 // choose to look at it that way here.
6983 if (!LV.getLValueBase())
6984 return false;
6985
6986 // If the designator is valid and refers to a subobject, we're not pointing
6987 // past the end.
6988 if (!LV.getLValueDesignator().Invalid &&
6989 !LV.getLValueDesignator().isOnePastTheEnd())
6990 return false;
6991
David Majnemerc378ca52015-08-29 08:32:55 +00006992 // A pointer to an incomplete type might be past-the-end if the type's size is
6993 // zero. We cannot tell because the type is incomplete.
6994 QualType Ty = getType(LV.getLValueBase());
6995 if (Ty->isIncompleteType())
6996 return true;
6997
Richard Smithd20f1e62014-10-21 23:01:04 +00006998 // We're a past-the-end pointer if we point to the byte after the object,
6999 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007000 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007001 return LV.getLValueOffset() == Size;
7002}
7003
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007004namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007005
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007006/// \brief Data recursive integer evaluator of certain binary operators.
7007///
7008/// We use a data recursive algorithm for binary operators so that we are able
7009/// to handle extreme cases of chained binary operators without causing stack
7010/// overflow.
7011class DataRecursiveIntBinOpEvaluator {
7012 struct EvalResult {
7013 APValue Val;
7014 bool Failed;
7015
7016 EvalResult() : Failed(false) { }
7017
7018 void swap(EvalResult &RHS) {
7019 Val.swap(RHS.Val);
7020 Failed = RHS.Failed;
7021 RHS.Failed = false;
7022 }
7023 };
7024
7025 struct Job {
7026 const Expr *E;
7027 EvalResult LHSResult; // meaningful only for binary operator expression.
7028 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007029
David Blaikie73726062015-08-12 23:09:24 +00007030 Job() = default;
7031 Job(Job &&J)
7032 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
7033 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
7034 J.StoredInfo = nullptr;
7035 }
7036
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007037 void startSpeculativeEval(EvalInfo &Info) {
7038 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00007039 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007040 StoredInfo = &Info;
7041 }
7042 ~Job() {
7043 if (StoredInfo) {
7044 StoredInfo->EvalStatus = OldEvalStatus;
7045 }
7046 }
7047 private:
David Blaikie73726062015-08-12 23:09:24 +00007048 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007049 Expr::EvalStatus OldEvalStatus;
7050 };
7051
7052 SmallVector<Job, 16> Queue;
7053
7054 IntExprEvaluator &IntEval;
7055 EvalInfo &Info;
7056 APValue &FinalResult;
7057
7058public:
7059 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7060 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7061
7062 /// \brief True if \param E is a binary operator that we are going to handle
7063 /// data recursively.
7064 /// We handle binary operators that are comma, logical, or that have operands
7065 /// with integral or enumeration type.
7066 static bool shouldEnqueue(const BinaryOperator *E) {
7067 return E->getOpcode() == BO_Comma ||
7068 E->isLogicalOp() ||
7069 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7070 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007071 }
7072
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007073 bool Traverse(const BinaryOperator *E) {
7074 enqueue(E);
7075 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007076 while (!Queue.empty())
7077 process(PrevResult);
7078
7079 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007080
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007081 FinalResult.swap(PrevResult.Val);
7082 return true;
7083 }
7084
7085private:
7086 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7087 return IntEval.Success(Value, E, Result);
7088 }
7089 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7090 return IntEval.Success(Value, E, Result);
7091 }
7092 bool Error(const Expr *E) {
7093 return IntEval.Error(E);
7094 }
7095 bool Error(const Expr *E, diag::kind D) {
7096 return IntEval.Error(E, D);
7097 }
7098
7099 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7100 return Info.CCEDiag(E, D);
7101 }
7102
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007103 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7104 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007105 bool &SuppressRHSDiags);
7106
7107 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7108 const BinaryOperator *E, APValue &Result);
7109
7110 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7111 Result.Failed = !Evaluate(Result.Val, Info, E);
7112 if (Result.Failed)
7113 Result.Val = APValue();
7114 }
7115
Richard Trieuba4d0872012-03-21 23:30:30 +00007116 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007117
7118 void enqueue(const Expr *E) {
7119 E = E->IgnoreParens();
7120 Queue.resize(Queue.size()+1);
7121 Queue.back().E = E;
7122 Queue.back().Kind = Job::AnyExprKind;
7123 }
7124};
7125
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007126}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007127
7128bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007129 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007130 bool &SuppressRHSDiags) {
7131 if (E->getOpcode() == BO_Comma) {
7132 // Ignore LHS but note if we could not evaluate it.
7133 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007134 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007135 return true;
7136 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007137
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007138 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007139 bool LHSAsBool;
7140 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007141 // We were able to evaluate the LHS, see if we can get away with not
7142 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007143 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7144 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007145 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007146 }
7147 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007148 LHSResult.Failed = true;
7149
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007150 // Since we weren't able to evaluate the left hand side, it
7151 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007152 if (!Info.noteSideEffect())
7153 return false;
7154
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007155 // We can't evaluate the LHS; however, sometimes the result
7156 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7157 // Don't ignore RHS and suppress diagnostics from this arm.
7158 SuppressRHSDiags = true;
7159 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007160
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007161 return true;
7162 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007163
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007164 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7165 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007166
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007167 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007168 return false; // Ignore RHS;
7169
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007170 return true;
7171}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007172
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007173bool DataRecursiveIntBinOpEvaluator::
7174 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7175 const BinaryOperator *E, APValue &Result) {
7176 if (E->getOpcode() == BO_Comma) {
7177 if (RHSResult.Failed)
7178 return false;
7179 Result = RHSResult.Val;
7180 return true;
7181 }
7182
7183 if (E->isLogicalOp()) {
7184 bool lhsResult, rhsResult;
7185 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7186 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7187
7188 if (LHSIsOK) {
7189 if (RHSIsOK) {
7190 if (E->getOpcode() == BO_LOr)
7191 return Success(lhsResult || rhsResult, E, Result);
7192 else
7193 return Success(lhsResult && rhsResult, E, Result);
7194 }
7195 } else {
7196 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007197 // We can't evaluate the LHS; however, sometimes the result
7198 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7199 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007200 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007201 }
7202 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007203
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007204 return false;
7205 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007206
7207 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7208 E->getRHS()->getType()->isIntegralOrEnumerationType());
7209
7210 if (LHSResult.Failed || RHSResult.Failed)
7211 return false;
7212
7213 const APValue &LHSVal = LHSResult.Val;
7214 const APValue &RHSVal = RHSResult.Val;
7215
7216 // Handle cases like (unsigned long)&a + 4.
7217 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7218 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007219 CharUnits AdditionalOffset =
7220 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007221 if (E->getOpcode() == BO_Add)
7222 Result.getLValueOffset() += AdditionalOffset;
7223 else
7224 Result.getLValueOffset() -= AdditionalOffset;
7225 return true;
7226 }
7227
7228 // Handle cases like 4 + (unsigned long)&a
7229 if (E->getOpcode() == BO_Add &&
7230 RHSVal.isLValue() && LHSVal.isInt()) {
7231 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007232 Result.getLValueOffset() +=
7233 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007234 return true;
7235 }
7236
7237 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7238 // Handle (intptr_t)&&A - (intptr_t)&&B.
7239 if (!LHSVal.getLValueOffset().isZero() ||
7240 !RHSVal.getLValueOffset().isZero())
7241 return false;
7242 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7243 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7244 if (!LHSExpr || !RHSExpr)
7245 return false;
7246 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7247 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7248 if (!LHSAddrExpr || !RHSAddrExpr)
7249 return false;
7250 // Make sure both labels come from the same function.
7251 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7252 RHSAddrExpr->getLabel()->getDeclContext())
7253 return false;
7254 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7255 return true;
7256 }
Richard Smith43e77732013-05-07 04:50:00 +00007257
7258 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007259 if (!LHSVal.isInt() || !RHSVal.isInt())
7260 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007261
7262 // Set up the width and signedness manually, in case it can't be deduced
7263 // from the operation we're performing.
7264 // FIXME: Don't do this in the cases where we can deduce it.
7265 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7266 E->getType()->isUnsignedIntegerOrEnumerationType());
7267 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7268 RHSVal.getInt(), Value))
7269 return false;
7270 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007271}
7272
Richard Trieuba4d0872012-03-21 23:30:30 +00007273void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007274 Job &job = Queue.back();
7275
7276 switch (job.Kind) {
7277 case Job::AnyExprKind: {
7278 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7279 if (shouldEnqueue(Bop)) {
7280 job.Kind = Job::BinOpKind;
7281 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007282 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007283 }
7284 }
7285
7286 EvaluateExpr(job.E, Result);
7287 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007288 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007289 }
7290
7291 case Job::BinOpKind: {
7292 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007293 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007294 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007295 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007296 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007297 }
7298 if (SuppressRHSDiags)
7299 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007300 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007301 job.Kind = Job::BinOpVisitedLHSKind;
7302 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007303 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007304 }
7305
7306 case Job::BinOpVisitedLHSKind: {
7307 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7308 EvalResult RHS;
7309 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007310 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007311 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007312 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007313 }
7314 }
7315
7316 llvm_unreachable("Invalid Job::Kind!");
7317}
7318
7319bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00007320 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007321 return Error(E);
7322
7323 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7324 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007325
Anders Carlssonacc79812008-11-16 07:17:21 +00007326 QualType LHSTy = E->getLHS()->getType();
7327 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007328
Chandler Carruthb29a7432014-10-11 11:03:30 +00007329 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007330 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007331 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007332 if (E->isAssignmentOp()) {
7333 LValue LV;
7334 EvaluateLValue(E->getLHS(), LV, Info);
7335 LHSOK = false;
7336 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007337 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7338 if (LHSOK) {
7339 LHS.makeComplexFloat();
7340 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7341 }
7342 } else {
7343 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7344 }
Richard Smith253c2a32012-01-27 01:14:48 +00007345 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007346 return false;
7347
Chandler Carruthb29a7432014-10-11 11:03:30 +00007348 if (E->getRHS()->getType()->isRealFloatingType()) {
7349 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7350 return false;
7351 RHS.makeComplexFloat();
7352 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7353 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007354 return false;
7355
7356 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007357 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007358 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007359 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007360 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7361
John McCalle3027922010-08-25 11:45:40 +00007362 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007363 return Success((CR_r == APFloat::cmpEqual &&
7364 CR_i == APFloat::cmpEqual), E);
7365 else {
John McCalle3027922010-08-25 11:45:40 +00007366 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007367 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007368 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007369 CR_r == APFloat::cmpLessThan ||
7370 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007371 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007372 CR_i == APFloat::cmpLessThan ||
7373 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007374 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007375 } else {
John McCalle3027922010-08-25 11:45:40 +00007376 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007377 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7378 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7379 else {
John McCalle3027922010-08-25 11:45:40 +00007380 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007381 "Invalid compex comparison.");
7382 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7383 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7384 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007385 }
7386 }
Mike Stump11289f42009-09-09 15:08:12 +00007387
Anders Carlssonacc79812008-11-16 07:17:21 +00007388 if (LHSTy->isRealFloatingType() &&
7389 RHSTy->isRealFloatingType()) {
7390 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007391
Richard Smith253c2a32012-01-27 01:14:48 +00007392 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7393 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007395
Richard Smith253c2a32012-01-27 01:14:48 +00007396 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007397 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007398
Anders Carlssonacc79812008-11-16 07:17:21 +00007399 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007400
Anders Carlssonacc79812008-11-16 07:17:21 +00007401 switch (E->getOpcode()) {
7402 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007403 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007404 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007405 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007406 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007407 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007408 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007409 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007410 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007411 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007412 E);
John McCalle3027922010-08-25 11:45:40 +00007413 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007414 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007415 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007416 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007417 || CR == APFloat::cmpLessThan
7418 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007419 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007420 }
Mike Stump11289f42009-09-09 15:08:12 +00007421
Eli Friedmana38da572009-04-28 19:17:36 +00007422 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007423 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007424 LValue LHSValue, RHSValue;
7425
7426 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
Richard Smith0c6124b2015-12-03 01:36:22 +00007427 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007428 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007429
Richard Smith253c2a32012-01-27 01:14:48 +00007430 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007431 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007432
Richard Smith8b3497e2011-10-31 01:37:14 +00007433 // Reject differing bases from the normal codepath; we special-case
7434 // comparisons to null.
7435 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007436 if (E->getOpcode() == BO_Sub) {
7437 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007438 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007439 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007440 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007441 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007442 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007443 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007444 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7445 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7446 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007447 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007448 // Make sure both labels come from the same function.
7449 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7450 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007451 return Error(E);
7452 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007453 }
Richard Smith83c68212011-10-31 05:11:32 +00007454 // Inequalities and subtractions between unrelated pointers have
7455 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007456 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007457 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007458 // A constant address may compare equal to the address of a symbol.
7459 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007460 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007461 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7462 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007463 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007464 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007465 // distinct addresses. In clang, the result of such a comparison is
7466 // unspecified, so it is not a constant expression. However, we do know
7467 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007468 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7469 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007470 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007471 // We can't tell whether weak symbols will end up pointing to the same
7472 // object.
7473 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007474 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007475 // We can't compare the address of the start of one object with the
7476 // past-the-end address of another object, per C++ DR1652.
7477 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7478 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7479 (RHSValue.Base && RHSValue.Offset.isZero() &&
7480 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7481 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007482 // We can't tell whether an object is at the same address as another
7483 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007484 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7485 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007486 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007487 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007488 // (Note that clang defaults to -fmerge-all-constants, which can
7489 // lead to inconsistent results for comparisons involving the address
7490 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007491 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007492 }
Eli Friedman64004332009-03-23 04:38:34 +00007493
Richard Smith1b470412012-02-01 08:10:20 +00007494 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7495 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7496
Richard Smith84f6dcf2012-02-02 01:16:57 +00007497 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7498 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7499
John McCalle3027922010-08-25 11:45:40 +00007500 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007501 // C++11 [expr.add]p6:
7502 // Unless both pointers point to elements of the same array object, or
7503 // one past the last element of the array object, the behavior is
7504 // undefined.
7505 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7506 !AreElementsOfSameArray(getType(LHSValue.Base),
7507 LHSDesignator, RHSDesignator))
7508 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7509
Chris Lattner882bdf22010-04-20 17:13:14 +00007510 QualType Type = E->getLHS()->getType();
7511 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007512
Richard Smithd62306a2011-11-10 06:34:14 +00007513 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007514 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007515 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007516
Richard Smith84c6b3d2013-09-10 21:34:14 +00007517 // As an extension, a type may have zero size (empty struct or union in
7518 // C, array of zero length). Pointer subtraction in such cases has
7519 // undefined behavior, so is not constant.
7520 if (ElementSize.isZero()) {
7521 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7522 << ElementType;
7523 return false;
7524 }
7525
Richard Smith1b470412012-02-01 08:10:20 +00007526 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7527 // and produce incorrect results when it overflows. Such behavior
7528 // appears to be non-conforming, but is common, so perhaps we should
7529 // assume the standard intended for such cases to be undefined behavior
7530 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007531
Richard Smith1b470412012-02-01 08:10:20 +00007532 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7533 // overflow in the final conversion to ptrdiff_t.
7534 APSInt LHS(
7535 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7536 APSInt RHS(
7537 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7538 APSInt ElemSize(
7539 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7540 APSInt TrueResult = (LHS - RHS) / ElemSize;
7541 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7542
Richard Smith0c6124b2015-12-03 01:36:22 +00007543 if (Result.extend(65) != TrueResult &&
7544 !HandleOverflow(Info, E, TrueResult, E->getType()))
7545 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007546 return Success(Result, E);
7547 }
Richard Smithde21b242012-01-31 06:41:30 +00007548
7549 // C++11 [expr.rel]p3:
7550 // Pointers to void (after pointer conversions) can be compared, with a
7551 // result defined as follows: If both pointers represent the same
7552 // address or are both the null pointer value, the result is true if the
7553 // operator is <= or >= and false otherwise; otherwise the result is
7554 // unspecified.
7555 // We interpret this as applying to pointers to *cv* void.
7556 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007557 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007558 CCEDiag(E, diag::note_constexpr_void_comparison);
7559
Richard Smith84f6dcf2012-02-02 01:16:57 +00007560 // C++11 [expr.rel]p2:
7561 // - If two pointers point to non-static data members of the same object,
7562 // or to subobjects or array elements fo such members, recursively, the
7563 // pointer to the later declared member compares greater provided the
7564 // two members have the same access control and provided their class is
7565 // not a union.
7566 // [...]
7567 // - Otherwise pointer comparisons are unspecified.
7568 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7569 E->isRelationalOp()) {
7570 bool WasArrayIndex;
7571 unsigned Mismatch =
7572 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7573 RHSDesignator, WasArrayIndex);
7574 // At the point where the designators diverge, the comparison has a
7575 // specified value if:
7576 // - we are comparing array indices
7577 // - we are comparing fields of a union, or fields with the same access
7578 // Otherwise, the result is unspecified and thus the comparison is not a
7579 // constant expression.
7580 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7581 Mismatch < RHSDesignator.Entries.size()) {
7582 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7583 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7584 if (!LF && !RF)
7585 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7586 else if (!LF)
7587 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7588 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7589 << RF->getParent() << RF;
7590 else if (!RF)
7591 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7592 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7593 << LF->getParent() << LF;
7594 else if (!LF->getParent()->isUnion() &&
7595 LF->getAccess() != RF->getAccess())
7596 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7597 << LF << LF->getAccess() << RF << RF->getAccess()
7598 << LF->getParent();
7599 }
7600 }
7601
Eli Friedman6c31cb42012-04-16 04:30:08 +00007602 // The comparison here must be unsigned, and performed with the same
7603 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007604 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7605 uint64_t CompareLHS = LHSOffset.getQuantity();
7606 uint64_t CompareRHS = RHSOffset.getQuantity();
7607 assert(PtrSize <= 64 && "Unexpected pointer width");
7608 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7609 CompareLHS &= Mask;
7610 CompareRHS &= Mask;
7611
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007612 // If there is a base and this is a relational operator, we can only
7613 // compare pointers within the object in question; otherwise, the result
7614 // depends on where the object is located in memory.
7615 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7616 QualType BaseTy = getType(LHSValue.Base);
7617 if (BaseTy->isIncompleteType())
7618 return Error(E);
7619 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7620 uint64_t OffsetLimit = Size.getQuantity();
7621 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7622 return Error(E);
7623 }
7624
Richard Smith8b3497e2011-10-31 01:37:14 +00007625 switch (E->getOpcode()) {
7626 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007627 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7628 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7629 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7630 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7631 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7632 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007633 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007634 }
7635 }
Richard Smith7bb00672012-02-01 01:42:44 +00007636
7637 if (LHSTy->isMemberPointerType()) {
7638 assert(E->isEqualityOp() && "unexpected member pointer operation");
7639 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7640
7641 MemberPtr LHSValue, RHSValue;
7642
7643 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7644 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7645 return false;
7646
7647 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7648 return false;
7649
7650 // C++11 [expr.eq]p2:
7651 // If both operands are null, they compare equal. Otherwise if only one is
7652 // null, they compare unequal.
7653 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7654 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7655 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7656 }
7657
7658 // Otherwise if either is a pointer to a virtual member function, the
7659 // result is unspecified.
7660 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7661 if (MD->isVirtual())
7662 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7663 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7664 if (MD->isVirtual())
7665 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7666
7667 // Otherwise they compare equal if and only if they would refer to the
7668 // same member of the same most derived object or the same subobject if
7669 // they were dereferenced with a hypothetical object of the associated
7670 // class type.
7671 bool Equal = LHSValue == RHSValue;
7672 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7673 }
7674
Richard Smithab44d9b2012-02-14 22:35:28 +00007675 if (LHSTy->isNullPtrType()) {
7676 assert(E->isComparisonOp() && "unexpected nullptr operation");
7677 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7678 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7679 // are compared, the result is true of the operator is <=, >= or ==, and
7680 // false otherwise.
7681 BinaryOperator::Opcode Opcode = E->getOpcode();
7682 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7683 }
7684
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007685 assert((!LHSTy->isIntegralOrEnumerationType() ||
7686 !RHSTy->isIntegralOrEnumerationType()) &&
7687 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7688 // We can't continue from here for non-integral types.
7689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007690}
7691
Peter Collingbournee190dee2011-03-11 19:24:49 +00007692/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7693/// a result as the expression's type.
7694bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7695 const UnaryExprOrTypeTraitExpr *E) {
7696 switch(E->getKind()) {
7697 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007698 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007699 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007700 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007701 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007702 }
Eli Friedman64004332009-03-23 04:38:34 +00007703
Peter Collingbournee190dee2011-03-11 19:24:49 +00007704 case UETT_VecStep: {
7705 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007706
Peter Collingbournee190dee2011-03-11 19:24:49 +00007707 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007708 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007709
Peter Collingbournee190dee2011-03-11 19:24:49 +00007710 // The vec_step built-in functions that take a 3-component
7711 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7712 if (n == 3)
7713 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007714
Peter Collingbournee190dee2011-03-11 19:24:49 +00007715 return Success(n, E);
7716 } else
7717 return Success(1, E);
7718 }
7719
7720 case UETT_SizeOf: {
7721 QualType SrcTy = E->getTypeOfArgument();
7722 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7723 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007724 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7725 SrcTy = Ref->getPointeeType();
7726
Richard Smithd62306a2011-11-10 06:34:14 +00007727 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007728 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007729 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007730 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007731 }
Alexey Bataev00396512015-07-02 03:40:19 +00007732 case UETT_OpenMPRequiredSimdAlign:
7733 assert(E->isArgumentType());
7734 return Success(
7735 Info.Ctx.toCharUnitsFromBits(
7736 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7737 .getQuantity(),
7738 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007739 }
7740
7741 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007742}
7743
Peter Collingbournee9200682011-05-13 03:29:01 +00007744bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007745 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007746 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007747 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007748 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007749 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007750 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007751 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007752 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007753 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007754 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007755 APSInt IdxResult;
7756 if (!EvaluateInteger(Idx, IdxResult, Info))
7757 return false;
7758 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7759 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007760 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007761 CurrentType = AT->getElementType();
7762 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7763 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007764 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007765 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007766
James Y Knight7281c352015-12-29 22:31:18 +00007767 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007768 FieldDecl *MemberDecl = ON.getField();
7769 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007770 if (!RT)
7771 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007772 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007773 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007774 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007775 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007776 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007777 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007778 CurrentType = MemberDecl->getType().getNonReferenceType();
7779 break;
7780 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007781
James Y Knight7281c352015-12-29 22:31:18 +00007782 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007783 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007784
James Y Knight7281c352015-12-29 22:31:18 +00007785 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007786 CXXBaseSpecifier *BaseSpec = ON.getBase();
7787 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007788 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007789
7790 // Find the layout of the class whose base we are looking into.
7791 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007792 if (!RT)
7793 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007794 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007795 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007796 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7797
7798 // Find the base class itself.
7799 CurrentType = BaseSpec->getType();
7800 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7801 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007802 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007803
7804 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007805 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007806 break;
7807 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007808 }
7809 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007810 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007811}
7812
Chris Lattnere13042c2008-07-11 19:10:17 +00007813bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007814 switch (E->getOpcode()) {
7815 default:
7816 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7817 // See C99 6.6p3.
7818 return Error(E);
7819 case UO_Extension:
7820 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7821 // If so, we could clear the diagnostic ID.
7822 return Visit(E->getSubExpr());
7823 case UO_Plus:
7824 // The result is just the value.
7825 return Visit(E->getSubExpr());
7826 case UO_Minus: {
7827 if (!Visit(E->getSubExpr()))
7828 return false;
7829 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007830 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007831 if (Value.isSigned() && Value.isMinSignedValue() &&
7832 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7833 E->getType()))
7834 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007835 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007836 }
7837 case UO_Not: {
7838 if (!Visit(E->getSubExpr()))
7839 return false;
7840 if (!Result.isInt()) return Error(E);
7841 return Success(~Result.getInt(), E);
7842 }
7843 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007844 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007845 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007846 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007847 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007848 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007849 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007850}
Mike Stump11289f42009-09-09 15:08:12 +00007851
Chris Lattner477c4be2008-07-12 01:15:53 +00007852/// HandleCast - This is used to evaluate implicit or explicit casts where the
7853/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007854bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7855 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007856 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007857 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007858
Eli Friedmanc757de22011-03-25 00:43:55 +00007859 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007860 case CK_BaseToDerived:
7861 case CK_DerivedToBase:
7862 case CK_UncheckedDerivedToBase:
7863 case CK_Dynamic:
7864 case CK_ToUnion:
7865 case CK_ArrayToPointerDecay:
7866 case CK_FunctionToPointerDecay:
7867 case CK_NullToPointer:
7868 case CK_NullToMemberPointer:
7869 case CK_BaseToDerivedMemberPointer:
7870 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007871 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007872 case CK_ConstructorConversion:
7873 case CK_IntegralToPointer:
7874 case CK_ToVoid:
7875 case CK_VectorSplat:
7876 case CK_IntegralToFloating:
7877 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007878 case CK_CPointerToObjCPointerCast:
7879 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007880 case CK_AnyPointerToBlockPointerCast:
7881 case CK_ObjCObjectLValueCast:
7882 case CK_FloatingRealToComplex:
7883 case CK_FloatingComplexToReal:
7884 case CK_FloatingComplexCast:
7885 case CK_FloatingComplexToIntegralComplex:
7886 case CK_IntegralRealToComplex:
7887 case CK_IntegralComplexCast:
7888 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007889 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007890 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007891 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007892 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007893 llvm_unreachable("invalid cast kind for integral value");
7894
Eli Friedman9faf2f92011-03-25 19:07:11 +00007895 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007896 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007897 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007898 case CK_ARCProduceObject:
7899 case CK_ARCConsumeObject:
7900 case CK_ARCReclaimReturnedObject:
7901 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007902 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007903 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007904
Richard Smith4ef685b2012-01-17 21:17:26 +00007905 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007906 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007907 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007908 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007909 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007910
7911 case CK_MemberPointerToBoolean:
7912 case CK_PointerToBoolean:
7913 case CK_IntegralToBoolean:
7914 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00007915 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00007916 case CK_FloatingComplexToBoolean:
7917 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007918 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007919 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007920 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00007921 uint64_t IntResult = BoolResult;
7922 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
7923 IntResult = (uint64_t)-1;
7924 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007925 }
7926
Eli Friedmanc757de22011-03-25 00:43:55 +00007927 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007928 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007929 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007930
Eli Friedman742421e2009-02-20 01:15:07 +00007931 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007932 // Allow casts of address-of-label differences if they are no-ops
7933 // or narrowing. (The narrowing case isn't actually guaranteed to
7934 // be constant-evaluatable except in some narrow cases which are hard
7935 // to detect here. We let it through on the assumption the user knows
7936 // what they are doing.)
7937 if (Result.isAddrLabelDiff())
7938 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007939 // Only allow casts of lvalues if they are lossless.
7940 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7941 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007942
Richard Smith911e1422012-01-30 22:27:01 +00007943 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7944 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007945 }
Mike Stump11289f42009-09-09 15:08:12 +00007946
Eli Friedmanc757de22011-03-25 00:43:55 +00007947 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007948 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7949
John McCall45d55e42010-05-07 21:00:08 +00007950 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007951 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007952 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007953
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007954 if (LV.getLValueBase()) {
7955 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007956 // FIXME: Allow a larger integer size than the pointer size, and allow
7957 // narrowing back down to pointer width in subsequent integral casts.
7958 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007959 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007960 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007961
Richard Smithcf74da72011-11-16 07:18:12 +00007962 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007963 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007964 return true;
7965 }
7966
Ken Dyck02990832010-01-15 12:37:54 +00007967 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7968 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007969 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007970 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007971
Eli Friedmanc757de22011-03-25 00:43:55 +00007972 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007973 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007974 if (!EvaluateComplex(SubExpr, C, Info))
7975 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007976 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007977 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007978
Eli Friedmanc757de22011-03-25 00:43:55 +00007979 case CK_FloatingToIntegral: {
7980 APFloat F(0.0);
7981 if (!EvaluateFloat(SubExpr, F, Info))
7982 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007983
Richard Smith357362d2011-12-13 06:39:58 +00007984 APSInt Value;
7985 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7986 return false;
7987 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007988 }
7989 }
Mike Stump11289f42009-09-09 15:08:12 +00007990
Eli Friedmanc757de22011-03-25 00:43:55 +00007991 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007992}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007993
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007994bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7995 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007996 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007997 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7998 return false;
7999 if (!LV.isComplexInt())
8000 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008001 return Success(LV.getComplexIntReal(), E);
8002 }
8003
8004 return Visit(E->getSubExpr());
8005}
8006
Eli Friedman4e7a2412009-02-27 04:45:43 +00008007bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008008 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008009 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008010 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8011 return false;
8012 if (!LV.isComplexInt())
8013 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008014 return Success(LV.getComplexIntImag(), E);
8015 }
8016
Richard Smith4a678122011-10-24 18:44:57 +00008017 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008018 return Success(0, E);
8019}
8020
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008021bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8022 return Success(E->getPackLength(), E);
8023}
8024
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008025bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8026 return Success(E->getValue(), E);
8027}
8028
Chris Lattner05706e882008-07-11 18:11:29 +00008029//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008030// Float Evaluation
8031//===----------------------------------------------------------------------===//
8032
8033namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008034class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008035 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008036 APFloat &Result;
8037public:
8038 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008039 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008040
Richard Smith2e312c82012-03-03 22:46:17 +00008041 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008042 Result = V.getFloat();
8043 return true;
8044 }
Eli Friedman24c01542008-08-22 00:06:13 +00008045
Richard Smithfddd3842011-12-30 21:15:51 +00008046 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008047 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8048 return true;
8049 }
8050
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008051 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008052
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008053 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008054 bool VisitBinaryOperator(const BinaryOperator *E);
8055 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008056 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008057
John McCallb1fb0d32010-05-07 22:08:54 +00008058 bool VisitUnaryReal(const UnaryOperator *E);
8059 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008060
Richard Smithfddd3842011-12-30 21:15:51 +00008061 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008062};
8063} // end anonymous namespace
8064
8065static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008066 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008067 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008068}
8069
Jay Foad39c79802011-01-12 09:06:06 +00008070static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008071 QualType ResultTy,
8072 const Expr *Arg,
8073 bool SNaN,
8074 llvm::APFloat &Result) {
8075 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8076 if (!S) return false;
8077
8078 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8079
8080 llvm::APInt fill;
8081
8082 // Treat empty strings as if they were zero.
8083 if (S->getString().empty())
8084 fill = llvm::APInt(32, 0);
8085 else if (S->getString().getAsInteger(0, fill))
8086 return false;
8087
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008088 if (Context.getTargetInfo().isNan2008()) {
8089 if (SNaN)
8090 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8091 else
8092 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8093 } else {
8094 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8095 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8096 // a different encoding to what became a standard in 2008, and for pre-
8097 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8098 // sNaN. This is now known as "legacy NaN" encoding.
8099 if (SNaN)
8100 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8101 else
8102 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8103 }
8104
John McCall16291492010-02-28 13:00:19 +00008105 return true;
8106}
8107
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008108bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008109 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008110 default:
8111 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8112
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008113 case Builtin::BI__builtin_huge_val:
8114 case Builtin::BI__builtin_huge_valf:
8115 case Builtin::BI__builtin_huge_vall:
8116 case Builtin::BI__builtin_inf:
8117 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008118 case Builtin::BI__builtin_infl: {
8119 const llvm::fltSemantics &Sem =
8120 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008121 Result = llvm::APFloat::getInf(Sem);
8122 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008123 }
Mike Stump11289f42009-09-09 15:08:12 +00008124
John McCall16291492010-02-28 13:00:19 +00008125 case Builtin::BI__builtin_nans:
8126 case Builtin::BI__builtin_nansf:
8127 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008128 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8129 true, Result))
8130 return Error(E);
8131 return true;
John McCall16291492010-02-28 13:00:19 +00008132
Chris Lattner0b7282e2008-10-06 06:31:58 +00008133 case Builtin::BI__builtin_nan:
8134 case Builtin::BI__builtin_nanf:
8135 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008136 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008137 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008138 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8139 false, Result))
8140 return Error(E);
8141 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008142
8143 case Builtin::BI__builtin_fabs:
8144 case Builtin::BI__builtin_fabsf:
8145 case Builtin::BI__builtin_fabsl:
8146 if (!EvaluateFloat(E->getArg(0), Result, Info))
8147 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008148
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008149 if (Result.isNegative())
8150 Result.changeSign();
8151 return true;
8152
Richard Smith8889a3d2013-06-13 06:26:32 +00008153 // FIXME: Builtin::BI__builtin_powi
8154 // FIXME: Builtin::BI__builtin_powif
8155 // FIXME: Builtin::BI__builtin_powil
8156
Mike Stump11289f42009-09-09 15:08:12 +00008157 case Builtin::BI__builtin_copysign:
8158 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008159 case Builtin::BI__builtin_copysignl: {
8160 APFloat RHS(0.);
8161 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8162 !EvaluateFloat(E->getArg(1), RHS, Info))
8163 return false;
8164 Result.copySign(RHS);
8165 return true;
8166 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008167 }
8168}
8169
John McCallb1fb0d32010-05-07 22:08:54 +00008170bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008171 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8172 ComplexValue CV;
8173 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8174 return false;
8175 Result = CV.FloatReal;
8176 return true;
8177 }
8178
8179 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008180}
8181
8182bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008183 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8184 ComplexValue CV;
8185 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8186 return false;
8187 Result = CV.FloatImag;
8188 return true;
8189 }
8190
Richard Smith4a678122011-10-24 18:44:57 +00008191 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008192 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8193 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008194 return true;
8195}
8196
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008197bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008198 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008199 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008200 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008201 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008202 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008203 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8204 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008205 Result.changeSign();
8206 return true;
8207 }
8208}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008209
Eli Friedman24c01542008-08-22 00:06:13 +00008210bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008211 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8212 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008213
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008214 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008215 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8216 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008217 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008218 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8219 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008220}
8221
8222bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8223 Result = E->getValue();
8224 return true;
8225}
8226
Peter Collingbournee9200682011-05-13 03:29:01 +00008227bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8228 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008229
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008230 switch (E->getCastKind()) {
8231 default:
Richard Smith11562c52011-10-28 17:51:58 +00008232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008233
8234 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008235 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008236 return EvaluateInteger(SubExpr, IntResult, Info) &&
8237 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8238 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008239 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008240
8241 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008242 if (!Visit(SubExpr))
8243 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008244 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8245 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008246 }
John McCalld7646252010-11-14 08:17:51 +00008247
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008248 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008249 ComplexValue V;
8250 if (!EvaluateComplex(SubExpr, V, Info))
8251 return false;
8252 Result = V.getComplexFloatReal();
8253 return true;
8254 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008255 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008256}
8257
Eli Friedman24c01542008-08-22 00:06:13 +00008258//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008259// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008260//===----------------------------------------------------------------------===//
8261
8262namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008263class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008264 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008265 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008266
Anders Carlsson537969c2008-11-16 20:27:53 +00008267public:
John McCall93d91dc2010-05-07 17:22:02 +00008268 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008269 : ExprEvaluatorBaseTy(info), Result(Result) {}
8270
Richard Smith2e312c82012-03-03 22:46:17 +00008271 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008272 Result.setFrom(V);
8273 return true;
8274 }
Mike Stump11289f42009-09-09 15:08:12 +00008275
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008276 bool ZeroInitialization(const Expr *E);
8277
Anders Carlsson537969c2008-11-16 20:27:53 +00008278 //===--------------------------------------------------------------------===//
8279 // Visitor Methods
8280 //===--------------------------------------------------------------------===//
8281
Peter Collingbournee9200682011-05-13 03:29:01 +00008282 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008283 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008284 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008285 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008286 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008287};
8288} // end anonymous namespace
8289
John McCall93d91dc2010-05-07 17:22:02 +00008290static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8291 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008292 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008293 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008294}
8295
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008296bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008297 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008298 if (ElemTy->isRealFloatingType()) {
8299 Result.makeComplexFloat();
8300 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8301 Result.FloatReal = Zero;
8302 Result.FloatImag = Zero;
8303 } else {
8304 Result.makeComplexInt();
8305 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8306 Result.IntReal = Zero;
8307 Result.IntImag = Zero;
8308 }
8309 return true;
8310}
8311
Peter Collingbournee9200682011-05-13 03:29:01 +00008312bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8313 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008314
8315 if (SubExpr->getType()->isRealFloatingType()) {
8316 Result.makeComplexFloat();
8317 APFloat &Imag = Result.FloatImag;
8318 if (!EvaluateFloat(SubExpr, Imag, Info))
8319 return false;
8320
8321 Result.FloatReal = APFloat(Imag.getSemantics());
8322 return true;
8323 } else {
8324 assert(SubExpr->getType()->isIntegerType() &&
8325 "Unexpected imaginary literal.");
8326
8327 Result.makeComplexInt();
8328 APSInt &Imag = Result.IntImag;
8329 if (!EvaluateInteger(SubExpr, Imag, Info))
8330 return false;
8331
8332 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8333 return true;
8334 }
8335}
8336
Peter Collingbournee9200682011-05-13 03:29:01 +00008337bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008338
John McCallfcef3cf2010-12-14 17:51:41 +00008339 switch (E->getCastKind()) {
8340 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008341 case CK_BaseToDerived:
8342 case CK_DerivedToBase:
8343 case CK_UncheckedDerivedToBase:
8344 case CK_Dynamic:
8345 case CK_ToUnion:
8346 case CK_ArrayToPointerDecay:
8347 case CK_FunctionToPointerDecay:
8348 case CK_NullToPointer:
8349 case CK_NullToMemberPointer:
8350 case CK_BaseToDerivedMemberPointer:
8351 case CK_DerivedToBaseMemberPointer:
8352 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008353 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008354 case CK_ConstructorConversion:
8355 case CK_IntegralToPointer:
8356 case CK_PointerToIntegral:
8357 case CK_PointerToBoolean:
8358 case CK_ToVoid:
8359 case CK_VectorSplat:
8360 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008361 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008362 case CK_IntegralToBoolean:
8363 case CK_IntegralToFloating:
8364 case CK_FloatingToIntegral:
8365 case CK_FloatingToBoolean:
8366 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008367 case CK_CPointerToObjCPointerCast:
8368 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008369 case CK_AnyPointerToBlockPointerCast:
8370 case CK_ObjCObjectLValueCast:
8371 case CK_FloatingComplexToReal:
8372 case CK_FloatingComplexToBoolean:
8373 case CK_IntegralComplexToReal:
8374 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008375 case CK_ARCProduceObject:
8376 case CK_ARCConsumeObject:
8377 case CK_ARCReclaimReturnedObject:
8378 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008379 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008380 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008381 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008382 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008383 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008384 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008385
John McCallfcef3cf2010-12-14 17:51:41 +00008386 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008387 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008388 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008389 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008390
8391 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008392 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008393 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008394 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008395
8396 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008397 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008398 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008399 return false;
8400
John McCallfcef3cf2010-12-14 17:51:41 +00008401 Result.makeComplexFloat();
8402 Result.FloatImag = APFloat(Real.getSemantics());
8403 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008404 }
8405
John McCallfcef3cf2010-12-14 17:51:41 +00008406 case CK_FloatingComplexCast: {
8407 if (!Visit(E->getSubExpr()))
8408 return false;
8409
8410 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8411 QualType From
8412 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8413
Richard Smith357362d2011-12-13 06:39:58 +00008414 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8415 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008416 }
8417
8418 case CK_FloatingComplexToIntegralComplex: {
8419 if (!Visit(E->getSubExpr()))
8420 return false;
8421
8422 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8423 QualType From
8424 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8425 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008426 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8427 To, Result.IntReal) &&
8428 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8429 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008430 }
8431
8432 case CK_IntegralRealToComplex: {
8433 APSInt &Real = Result.IntReal;
8434 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8435 return false;
8436
8437 Result.makeComplexInt();
8438 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8439 return true;
8440 }
8441
8442 case CK_IntegralComplexCast: {
8443 if (!Visit(E->getSubExpr()))
8444 return false;
8445
8446 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8447 QualType From
8448 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8449
Richard Smith911e1422012-01-30 22:27:01 +00008450 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8451 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008452 return true;
8453 }
8454
8455 case CK_IntegralComplexToFloatingComplex: {
8456 if (!Visit(E->getSubExpr()))
8457 return false;
8458
Ted Kremenek28831752012-08-23 20:46:57 +00008459 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008460 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008461 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008462 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008463 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8464 To, Result.FloatReal) &&
8465 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8466 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008467 }
8468 }
8469
8470 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008471}
8472
John McCall93d91dc2010-05-07 17:22:02 +00008473bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008474 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008475 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8476
Chandler Carrutha216cad2014-10-11 00:57:18 +00008477 // Track whether the LHS or RHS is real at the type system level. When this is
8478 // the case we can simplify our evaluation strategy.
8479 bool LHSReal = false, RHSReal = false;
8480
8481 bool LHSOK;
8482 if (E->getLHS()->getType()->isRealFloatingType()) {
8483 LHSReal = true;
8484 APFloat &Real = Result.FloatReal;
8485 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8486 if (LHSOK) {
8487 Result.makeComplexFloat();
8488 Result.FloatImag = APFloat(Real.getSemantics());
8489 }
8490 } else {
8491 LHSOK = Visit(E->getLHS());
8492 }
Richard Smith253c2a32012-01-27 01:14:48 +00008493 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008494 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008495
John McCall93d91dc2010-05-07 17:22:02 +00008496 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008497 if (E->getRHS()->getType()->isRealFloatingType()) {
8498 RHSReal = true;
8499 APFloat &Real = RHS.FloatReal;
8500 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8501 return false;
8502 RHS.makeComplexFloat();
8503 RHS.FloatImag = APFloat(Real.getSemantics());
8504 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008505 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008506
Chandler Carrutha216cad2014-10-11 00:57:18 +00008507 assert(!(LHSReal && RHSReal) &&
8508 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008509 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008510 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008511 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008512 if (Result.isComplexFloat()) {
8513 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8514 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008515 if (LHSReal)
8516 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8517 else if (!RHSReal)
8518 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8519 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008520 } else {
8521 Result.getComplexIntReal() += RHS.getComplexIntReal();
8522 Result.getComplexIntImag() += RHS.getComplexIntImag();
8523 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008524 break;
John McCalle3027922010-08-25 11:45:40 +00008525 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008526 if (Result.isComplexFloat()) {
8527 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8528 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008529 if (LHSReal) {
8530 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8531 Result.getComplexFloatImag().changeSign();
8532 } else if (!RHSReal) {
8533 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8534 APFloat::rmNearestTiesToEven);
8535 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008536 } else {
8537 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8538 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8539 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008540 break;
John McCalle3027922010-08-25 11:45:40 +00008541 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008542 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008543 // This is an implementation of complex multiplication according to the
8544 // constraints laid out in C11 Annex G. The implemantion uses the
8545 // following naming scheme:
8546 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008547 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008548 APFloat &A = LHS.getComplexFloatReal();
8549 APFloat &B = LHS.getComplexFloatImag();
8550 APFloat &C = RHS.getComplexFloatReal();
8551 APFloat &D = RHS.getComplexFloatImag();
8552 APFloat &ResR = Result.getComplexFloatReal();
8553 APFloat &ResI = Result.getComplexFloatImag();
8554 if (LHSReal) {
8555 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8556 ResR = A * C;
8557 ResI = A * D;
8558 } else if (RHSReal) {
8559 ResR = C * A;
8560 ResI = C * B;
8561 } else {
8562 // In the fully general case, we need to handle NaNs and infinities
8563 // robustly.
8564 APFloat AC = A * C;
8565 APFloat BD = B * D;
8566 APFloat AD = A * D;
8567 APFloat BC = B * C;
8568 ResR = AC - BD;
8569 ResI = AD + BC;
8570 if (ResR.isNaN() && ResI.isNaN()) {
8571 bool Recalc = false;
8572 if (A.isInfinity() || B.isInfinity()) {
8573 A = APFloat::copySign(
8574 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8575 B = APFloat::copySign(
8576 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8577 if (C.isNaN())
8578 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8579 if (D.isNaN())
8580 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8581 Recalc = true;
8582 }
8583 if (C.isInfinity() || D.isInfinity()) {
8584 C = APFloat::copySign(
8585 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8586 D = APFloat::copySign(
8587 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8588 if (A.isNaN())
8589 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8590 if (B.isNaN())
8591 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8592 Recalc = true;
8593 }
8594 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8595 AD.isInfinity() || BC.isInfinity())) {
8596 if (A.isNaN())
8597 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8598 if (B.isNaN())
8599 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8600 if (C.isNaN())
8601 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8602 if (D.isNaN())
8603 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8604 Recalc = true;
8605 }
8606 if (Recalc) {
8607 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8608 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8609 }
8610 }
8611 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008612 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008613 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008614 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008615 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8616 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008617 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008618 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8619 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8620 }
8621 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008622 case BO_Div:
8623 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008624 // This is an implementation of complex division according to the
8625 // constraints laid out in C11 Annex G. The implemantion uses the
8626 // following naming scheme:
8627 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008628 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008629 APFloat &A = LHS.getComplexFloatReal();
8630 APFloat &B = LHS.getComplexFloatImag();
8631 APFloat &C = RHS.getComplexFloatReal();
8632 APFloat &D = RHS.getComplexFloatImag();
8633 APFloat &ResR = Result.getComplexFloatReal();
8634 APFloat &ResI = Result.getComplexFloatImag();
8635 if (RHSReal) {
8636 ResR = A / C;
8637 ResI = B / C;
8638 } else {
8639 if (LHSReal) {
8640 // No real optimizations we can do here, stub out with zero.
8641 B = APFloat::getZero(A.getSemantics());
8642 }
8643 int DenomLogB = 0;
8644 APFloat MaxCD = maxnum(abs(C), abs(D));
8645 if (MaxCD.isFinite()) {
8646 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008647 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8648 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008649 }
8650 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008651 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8652 APFloat::rmNearestTiesToEven);
8653 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8654 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008655 if (ResR.isNaN() && ResI.isNaN()) {
8656 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8657 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8658 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8659 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8660 D.isFinite()) {
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 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8666 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8667 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8668 C = APFloat::copySign(
8669 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8670 D = APFloat::copySign(
8671 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8672 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8673 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8674 }
8675 }
8676 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008677 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008678 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8679 return Error(E, diag::note_expr_divide_by_zero);
8680
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008681 ComplexValue LHS = Result;
8682 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8683 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8684 Result.getComplexIntReal() =
8685 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8686 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8687 Result.getComplexIntImag() =
8688 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8689 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8690 }
8691 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008692 }
8693
John McCall93d91dc2010-05-07 17:22:02 +00008694 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008695}
8696
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008697bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8698 // Get the operand value into 'Result'.
8699 if (!Visit(E->getSubExpr()))
8700 return false;
8701
8702 switch (E->getOpcode()) {
8703 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008704 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008705 case UO_Extension:
8706 return true;
8707 case UO_Plus:
8708 // The result is always just the subexpr.
8709 return true;
8710 case UO_Minus:
8711 if (Result.isComplexFloat()) {
8712 Result.getComplexFloatReal().changeSign();
8713 Result.getComplexFloatImag().changeSign();
8714 }
8715 else {
8716 Result.getComplexIntReal() = -Result.getComplexIntReal();
8717 Result.getComplexIntImag() = -Result.getComplexIntImag();
8718 }
8719 return true;
8720 case UO_Not:
8721 if (Result.isComplexFloat())
8722 Result.getComplexFloatImag().changeSign();
8723 else
8724 Result.getComplexIntImag() = -Result.getComplexIntImag();
8725 return true;
8726 }
8727}
8728
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008729bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8730 if (E->getNumInits() == 2) {
8731 if (E->getType()->isComplexType()) {
8732 Result.makeComplexFloat();
8733 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8734 return false;
8735 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8736 return false;
8737 } else {
8738 Result.makeComplexInt();
8739 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8740 return false;
8741 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8742 return false;
8743 }
8744 return true;
8745 }
8746 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8747}
8748
Anders Carlsson537969c2008-11-16 20:27:53 +00008749//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008750// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8751// implicit conversion.
8752//===----------------------------------------------------------------------===//
8753
8754namespace {
8755class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008756 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008757 APValue &Result;
8758public:
8759 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8760 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8761
8762 bool Success(const APValue &V, const Expr *E) {
8763 Result = V;
8764 return true;
8765 }
8766
8767 bool ZeroInitialization(const Expr *E) {
8768 ImplicitValueInitExpr VIE(
8769 E->getType()->castAs<AtomicType>()->getValueType());
8770 return Evaluate(Result, Info, &VIE);
8771 }
8772
8773 bool VisitCastExpr(const CastExpr *E) {
8774 switch (E->getCastKind()) {
8775 default:
8776 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8777 case CK_NonAtomicToAtomic:
8778 return Evaluate(Result, Info, E->getSubExpr());
8779 }
8780 }
8781};
8782} // end anonymous namespace
8783
8784static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8785 assert(E->isRValue() && E->getType()->isAtomicType());
8786 return AtomicExprEvaluator(Info, Result).Visit(E);
8787}
8788
8789//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008790// Void expression evaluation, primarily for a cast to void on the LHS of a
8791// comma operator
8792//===----------------------------------------------------------------------===//
8793
8794namespace {
8795class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008796 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008797public:
8798 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8799
Richard Smith2e312c82012-03-03 22:46:17 +00008800 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008801
8802 bool VisitCastExpr(const CastExpr *E) {
8803 switch (E->getCastKind()) {
8804 default:
8805 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8806 case CK_ToVoid:
8807 VisitIgnoredValue(E->getSubExpr());
8808 return true;
8809 }
8810 }
Hal Finkela8443c32014-07-17 14:49:58 +00008811
8812 bool VisitCallExpr(const CallExpr *E) {
8813 switch (E->getBuiltinCallee()) {
8814 default:
8815 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8816 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008817 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008818 // The argument is not evaluated!
8819 return true;
8820 }
8821 }
Richard Smith42d3af92011-12-07 00:43:50 +00008822};
8823} // end anonymous namespace
8824
8825static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8826 assert(E->isRValue() && E->getType()->isVoidType());
8827 return VoidExprEvaluator(Info).Visit(E);
8828}
8829
8830//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008831// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008832//===----------------------------------------------------------------------===//
8833
Richard Smith2e312c82012-03-03 22:46:17 +00008834static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008835 // In C, function designators are not lvalues, but we evaluate them as if they
8836 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008837 QualType T = E->getType();
8838 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008839 LValue LV;
8840 if (!EvaluateLValue(E, LV, Info))
8841 return false;
8842 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008843 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008844 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008845 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008846 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008847 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008848 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008849 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008850 LValue LV;
8851 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008852 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008853 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008854 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008855 llvm::APFloat F(0.0);
8856 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008857 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008858 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008859 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008860 ComplexValue C;
8861 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008862 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008863 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008864 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008865 MemberPtr P;
8866 if (!EvaluateMemberPointer(E, P, Info))
8867 return false;
8868 P.moveInto(Result);
8869 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008870 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008871 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008872 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008873 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8874 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008875 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008876 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008877 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008878 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008879 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008880 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8881 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008882 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008883 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008884 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008885 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008886 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008887 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008888 if (!EvaluateVoid(E, Info))
8889 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008890 } else if (T->isAtomicType()) {
8891 if (!EvaluateAtomic(E, Result, Info))
8892 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008893 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008894 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008895 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008896 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008897 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008898 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008899 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008900
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008901 return true;
8902}
8903
Richard Smithb228a862012-02-15 02:18:13 +00008904/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8905/// cases, the in-place evaluation is essential, since later initializers for
8906/// an object can indirectly refer to subobjects which were initialized earlier.
8907static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008908 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008909 assert(!E->isValueDependent());
8910
Richard Smith7525ff62013-05-09 07:14:00 +00008911 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008912 return false;
8913
8914 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008915 // Evaluate arrays and record types in-place, so that later initializers can
8916 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008917 if (E->getType()->isArrayType())
8918 return EvaluateArray(E, This, Result, Info);
8919 else if (E->getType()->isRecordType())
8920 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008921 }
8922
8923 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008924 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008925}
8926
Richard Smithf57d8cb2011-12-09 22:58:01 +00008927/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8928/// lvalue-to-rvalue cast if it is an lvalue.
8929static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008930 if (E->getType().isNull())
8931 return false;
8932
Richard Smithfddd3842011-12-30 21:15:51 +00008933 if (!CheckLiteralType(Info, E))
8934 return false;
8935
Richard Smith2e312c82012-03-03 22:46:17 +00008936 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008937 return false;
8938
8939 if (E->isGLValue()) {
8940 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008941 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008942 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008943 return false;
8944 }
8945
Richard Smith2e312c82012-03-03 22:46:17 +00008946 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008947 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008948}
Richard Smith11562c52011-10-28 17:51:58 +00008949
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008950static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8951 const ASTContext &Ctx, bool &IsConst) {
8952 // Fast-path evaluations of integer literals, since we sometimes see files
8953 // containing vast quantities of these.
8954 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8955 Result.Val = APValue(APSInt(L->getValue(),
8956 L->getType()->isUnsignedIntegerType()));
8957 IsConst = true;
8958 return true;
8959 }
James Dennett0492ef02014-03-14 17:44:10 +00008960
8961 // This case should be rare, but we need to check it before we check on
8962 // the type below.
8963 if (Exp->getType().isNull()) {
8964 IsConst = false;
8965 return true;
8966 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008967
8968 // FIXME: Evaluating values of large array and record types can cause
8969 // performance problems. Only do so in C++11 for now.
8970 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8971 Exp->getType()->isRecordType()) &&
8972 !Ctx.getLangOpts().CPlusPlus11) {
8973 IsConst = false;
8974 return true;
8975 }
8976 return false;
8977}
8978
8979
Richard Smith7b553f12011-10-29 00:50:52 +00008980/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008981/// any crazy technique (that has nothing to do with language standards) that
8982/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008983/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8984/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008985bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008986 bool IsConst;
8987 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8988 return IsConst;
8989
Richard Smith6d4c6582013-11-05 22:18:15 +00008990 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008991 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008992}
8993
Jay Foad39c79802011-01-12 09:06:06 +00008994bool Expr::EvaluateAsBooleanCondition(bool &Result,
8995 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008996 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008997 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008998 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008999}
9000
Richard Smithce8eca52015-12-08 03:21:47 +00009001static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9002 Expr::SideEffectsKind SEK) {
9003 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9004 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9005}
9006
Richard Smith5fab0c92011-12-28 19:48:30 +00009007bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9008 SideEffectsKind AllowSideEffects) const {
9009 if (!getType()->isIntegralOrEnumerationType())
9010 return false;
9011
Richard Smith11562c52011-10-28 17:51:58 +00009012 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009013 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009014 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009015 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009016
Richard Smith11562c52011-10-28 17:51:58 +00009017 Result = ExprResult.Val.getInt();
9018 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009019}
9020
Jay Foad39c79802011-01-12 09:06:06 +00009021bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009022 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009023
John McCall45d55e42010-05-07 21:00:08 +00009024 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009025 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9026 !CheckLValueConstantExpression(Info, getExprLoc(),
9027 Ctx.getLValueReferenceType(getType()), LV))
9028 return false;
9029
Richard Smith2e312c82012-03-03 22:46:17 +00009030 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009031 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009032}
9033
Richard Smithd0b4dd62011-12-19 06:19:21 +00009034bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9035 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009036 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009037 // FIXME: Evaluating initializers for large array and record types can cause
9038 // performance problems. Only do so in C++11 for now.
9039 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009040 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009041 return false;
9042
Richard Smithd0b4dd62011-12-19 06:19:21 +00009043 Expr::EvalStatus EStatus;
9044 EStatus.Diag = &Notes;
9045
Richard Smith0c6124b2015-12-03 01:36:22 +00009046 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9047 ? EvalInfo::EM_ConstantExpression
9048 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009049 InitInfo.setEvaluatingDecl(VD, Value);
9050
9051 LValue LVal;
9052 LVal.set(VD);
9053
Richard Smithfddd3842011-12-30 21:15:51 +00009054 // C++11 [basic.start.init]p2:
9055 // Variables with static storage duration or thread storage duration shall be
9056 // zero-initialized before any other initialization takes place.
9057 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009058 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009059 !VD->getType()->isReferenceType()) {
9060 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009061 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009062 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009063 return false;
9064 }
9065
Richard Smith7525ff62013-05-09 07:14:00 +00009066 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9067 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009068 EStatus.HasSideEffects)
9069 return false;
9070
9071 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9072 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009073}
9074
Richard Smith7b553f12011-10-29 00:50:52 +00009075/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9076/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009077bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009078 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009079 return EvaluateAsRValue(Result, Ctx) &&
9080 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009081}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009082
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009083APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009084 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009085 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009086 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009087 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009088 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009089 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009090 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009091
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009092 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009093}
John McCall864e3962010-05-07 05:32:02 +00009094
Richard Smithe9ff7702013-11-05 22:23:30 +00009095void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009096 bool IsConst;
9097 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009098 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009099 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009100 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9101 }
9102}
9103
Richard Smithe6c01442013-06-05 00:46:14 +00009104bool Expr::EvalResult::isGlobalLValue() const {
9105 assert(Val.isLValue());
9106 return IsGlobalLValue(Val.getLValueBase());
9107}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009108
9109
John McCall864e3962010-05-07 05:32:02 +00009110/// isIntegerConstantExpr - this recursive routine will test if an expression is
9111/// an integer constant expression.
9112
9113/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9114/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009115
9116// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009117// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9118// and a (possibly null) SourceLocation indicating the location of the problem.
9119//
John McCall864e3962010-05-07 05:32:02 +00009120// Note that to reduce code duplication, this helper does no evaluation
9121// itself; the caller checks whether the expression is evaluatable, and
9122// in the rare cases where CheckICE actually cares about the evaluated
9123// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009124
Dan Gohman28ade552010-07-26 21:25:24 +00009125namespace {
9126
Richard Smith9e575da2012-12-28 13:25:52 +00009127enum ICEKind {
9128 /// This expression is an ICE.
9129 IK_ICE,
9130 /// This expression is not an ICE, but if it isn't evaluated, it's
9131 /// a legal subexpression for an ICE. This return value is used to handle
9132 /// the comma operator in C99 mode, and non-constant subexpressions.
9133 IK_ICEIfUnevaluated,
9134 /// This expression is not an ICE, and is not a legal subexpression for one.
9135 IK_NotICE
9136};
9137
John McCall864e3962010-05-07 05:32:02 +00009138struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009139 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009140 SourceLocation Loc;
9141
Richard Smith9e575da2012-12-28 13:25:52 +00009142 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009143};
9144
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009145}
Dan Gohman28ade552010-07-26 21:25:24 +00009146
Richard Smith9e575da2012-12-28 13:25:52 +00009147static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9148
9149static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009150
Craig Toppera31a8822013-08-22 07:09:37 +00009151static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009152 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009153 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009154 !EVResult.Val.isInt())
9155 return ICEDiag(IK_NotICE, E->getLocStart());
9156
John McCall864e3962010-05-07 05:32:02 +00009157 return NoDiag();
9158}
9159
Craig Toppera31a8822013-08-22 07:09:37 +00009160static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009161 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009162 if (!E->getType()->isIntegralOrEnumerationType())
9163 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009164
9165 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009166#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009167#define STMT(Node, Base) case Expr::Node##Class:
9168#define EXPR(Node, Base)
9169#include "clang/AST/StmtNodes.inc"
9170 case Expr::PredefinedExprClass:
9171 case Expr::FloatingLiteralClass:
9172 case Expr::ImaginaryLiteralClass:
9173 case Expr::StringLiteralClass:
9174 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009175 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009176 case Expr::MemberExprClass:
9177 case Expr::CompoundAssignOperatorClass:
9178 case Expr::CompoundLiteralExprClass:
9179 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009180 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009181 case Expr::NoInitExprClass:
9182 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009183 case Expr::ImplicitValueInitExprClass:
9184 case Expr::ParenListExprClass:
9185 case Expr::VAArgExprClass:
9186 case Expr::AddrLabelExprClass:
9187 case Expr::StmtExprClass:
9188 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009189 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009190 case Expr::CXXDynamicCastExprClass:
9191 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009192 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009193 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009194 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009195 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009196 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009197 case Expr::CXXThisExprClass:
9198 case Expr::CXXThrowExprClass:
9199 case Expr::CXXNewExprClass:
9200 case Expr::CXXDeleteExprClass:
9201 case Expr::CXXPseudoDestructorExprClass:
9202 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009203 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009204 case Expr::DependentScopeDeclRefExprClass:
9205 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009206 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009207 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009208 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009209 case Expr::CXXTemporaryObjectExprClass:
9210 case Expr::CXXUnresolvedConstructExprClass:
9211 case Expr::CXXDependentScopeMemberExprClass:
9212 case Expr::UnresolvedMemberExprClass:
9213 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009214 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009215 case Expr::ObjCArrayLiteralClass:
9216 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009217 case Expr::ObjCEncodeExprClass:
9218 case Expr::ObjCMessageExprClass:
9219 case Expr::ObjCSelectorExprClass:
9220 case Expr::ObjCProtocolExprClass:
9221 case Expr::ObjCIvarRefExprClass:
9222 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009223 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009224 case Expr::ObjCIsaExprClass:
9225 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009226 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009227 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009228 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009229 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009230 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009231 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009232 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009233 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009234 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009235 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009236 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009237 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009238 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009239 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009240 case Expr::CoawaitExprClass:
9241 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009242 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009243
Richard Smithf137f932014-01-25 20:50:08 +00009244 case Expr::InitListExprClass: {
9245 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9246 // form "T x = { a };" is equivalent to "T x = a;".
9247 // Unless we're initializing a reference, T is a scalar as it is known to be
9248 // of integral or enumeration type.
9249 if (E->isRValue())
9250 if (cast<InitListExpr>(E)->getNumInits() == 1)
9251 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9252 return ICEDiag(IK_NotICE, E->getLocStart());
9253 }
9254
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009255 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009256 case Expr::GNUNullExprClass:
9257 // GCC considers the GNU __null value to be an integral constant expression.
9258 return NoDiag();
9259
John McCall7c454bb2011-07-15 05:09:51 +00009260 case Expr::SubstNonTypeTemplateParmExprClass:
9261 return
9262 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9263
John McCall864e3962010-05-07 05:32:02 +00009264 case Expr::ParenExprClass:
9265 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009266 case Expr::GenericSelectionExprClass:
9267 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009268 case Expr::IntegerLiteralClass:
9269 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009270 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009271 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009272 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009273 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009274 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009275 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009276 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009277 return NoDiag();
9278 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009279 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009280 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9281 // constant expressions, but they can never be ICEs because an ICE cannot
9282 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009283 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009284 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009285 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009286 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009287 }
Richard Smith6365c912012-02-24 22:12:32 +00009288 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009289 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9290 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009291 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009292 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009293 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009294 // Parameter variables are never constants. Without this check,
9295 // getAnyInitializer() can find a default argument, which leads
9296 // to chaos.
9297 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009298 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009299
9300 // C++ 7.1.5.1p2
9301 // A variable of non-volatile const-qualified integral or enumeration
9302 // type initialized by an ICE can be used in ICEs.
9303 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009304 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009305 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009306
Richard Smithd0b4dd62011-12-19 06:19:21 +00009307 const VarDecl *VD;
9308 // Look for a declaration of this variable that has an initializer, and
9309 // check whether it is an ICE.
9310 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9311 return NoDiag();
9312 else
Richard Smith9e575da2012-12-28 13:25:52 +00009313 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009314 }
9315 }
Richard Smith9e575da2012-12-28 13:25:52 +00009316 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009317 }
John McCall864e3962010-05-07 05:32:02 +00009318 case Expr::UnaryOperatorClass: {
9319 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9320 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009321 case UO_PostInc:
9322 case UO_PostDec:
9323 case UO_PreInc:
9324 case UO_PreDec:
9325 case UO_AddrOf:
9326 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009327 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009328 // C99 6.6/3 allows increment and decrement within unevaluated
9329 // subexpressions of constant expressions, but they can never be ICEs
9330 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009331 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009332 case UO_Extension:
9333 case UO_LNot:
9334 case UO_Plus:
9335 case UO_Minus:
9336 case UO_Not:
9337 case UO_Real:
9338 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009339 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009340 }
Richard Smith9e575da2012-12-28 13:25:52 +00009341
John McCall864e3962010-05-07 05:32:02 +00009342 // OffsetOf falls through here.
9343 }
9344 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009345 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9346 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9347 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9348 // compliance: we should warn earlier for offsetof expressions with
9349 // array subscripts that aren't ICEs, and if the array subscripts
9350 // are ICEs, the value of the offsetof must be an integer constant.
9351 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009352 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009353 case Expr::UnaryExprOrTypeTraitExprClass: {
9354 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9355 if ((Exp->getKind() == UETT_SizeOf) &&
9356 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009357 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009358 return NoDiag();
9359 }
9360 case Expr::BinaryOperatorClass: {
9361 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9362 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009363 case BO_PtrMemD:
9364 case BO_PtrMemI:
9365 case BO_Assign:
9366 case BO_MulAssign:
9367 case BO_DivAssign:
9368 case BO_RemAssign:
9369 case BO_AddAssign:
9370 case BO_SubAssign:
9371 case BO_ShlAssign:
9372 case BO_ShrAssign:
9373 case BO_AndAssign:
9374 case BO_XorAssign:
9375 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009376 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9377 // constant expressions, but they can never be ICEs because an ICE cannot
9378 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009379 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009380
John McCalle3027922010-08-25 11:45:40 +00009381 case BO_Mul:
9382 case BO_Div:
9383 case BO_Rem:
9384 case BO_Add:
9385 case BO_Sub:
9386 case BO_Shl:
9387 case BO_Shr:
9388 case BO_LT:
9389 case BO_GT:
9390 case BO_LE:
9391 case BO_GE:
9392 case BO_EQ:
9393 case BO_NE:
9394 case BO_And:
9395 case BO_Xor:
9396 case BO_Or:
9397 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009398 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9399 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009400 if (Exp->getOpcode() == BO_Div ||
9401 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009402 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009403 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009404 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009405 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009406 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009407 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009408 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009409 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009410 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009411 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009412 }
9413 }
9414 }
John McCalle3027922010-08-25 11:45:40 +00009415 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009416 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009417 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9418 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009419 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9420 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009421 } else {
9422 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009423 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009424 }
9425 }
Richard Smith9e575da2012-12-28 13:25:52 +00009426 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009427 }
John McCalle3027922010-08-25 11:45:40 +00009428 case BO_LAnd:
9429 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009430 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9431 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009432 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009433 // Rare case where the RHS has a comma "side-effect"; we need
9434 // to actually check the condition to see whether the side
9435 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009436 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009437 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009438 return RHSResult;
9439 return NoDiag();
9440 }
9441
Richard Smith9e575da2012-12-28 13:25:52 +00009442 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009443 }
9444 }
9445 }
9446 case Expr::ImplicitCastExprClass:
9447 case Expr::CStyleCastExprClass:
9448 case Expr::CXXFunctionalCastExprClass:
9449 case Expr::CXXStaticCastExprClass:
9450 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009451 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009452 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009453 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009454 if (isa<ExplicitCastExpr>(E)) {
9455 if (const FloatingLiteral *FL
9456 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9457 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9458 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9459 APSInt IgnoredVal(DestWidth, !DestSigned);
9460 bool Ignored;
9461 // If the value does not fit in the destination type, the behavior is
9462 // undefined, so we are not required to treat it as a constant
9463 // expression.
9464 if (FL->getValue().convertToInteger(IgnoredVal,
9465 llvm::APFloat::rmTowardZero,
9466 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009467 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009468 return NoDiag();
9469 }
9470 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009471 switch (cast<CastExpr>(E)->getCastKind()) {
9472 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009473 case CK_AtomicToNonAtomic:
9474 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009475 case CK_NoOp:
9476 case CK_IntegralToBoolean:
9477 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009478 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009479 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009480 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009481 }
John McCall864e3962010-05-07 05:32:02 +00009482 }
John McCallc07a0c72011-02-17 10:25:35 +00009483 case Expr::BinaryConditionalOperatorClass: {
9484 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9485 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009486 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009487 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009488 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9489 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9490 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009491 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009492 return FalseResult;
9493 }
John McCall864e3962010-05-07 05:32:02 +00009494 case Expr::ConditionalOperatorClass: {
9495 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9496 // If the condition (ignoring parens) is a __builtin_constant_p call,
9497 // then only the true side is actually considered in an integer constant
9498 // expression, and it is fully evaluated. This is an important GNU
9499 // extension. See GCC PR38377 for discussion.
9500 if (const CallExpr *CallCE
9501 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009502 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009503 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009504 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009505 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009506 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009507
Richard Smithf57d8cb2011-12-09 22:58:01 +00009508 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9509 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009510
Richard Smith9e575da2012-12-28 13:25:52 +00009511 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009512 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009513 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009514 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009515 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009516 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009517 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009518 return NoDiag();
9519 // Rare case where the diagnostics depend on which side is evaluated
9520 // Note that if we get here, CondResult is 0, and at least one of
9521 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009522 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009523 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009524 return TrueResult;
9525 }
9526 case Expr::CXXDefaultArgExprClass:
9527 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009528 case Expr::CXXDefaultInitExprClass:
9529 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009530 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009531 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009532 }
9533 }
9534
David Blaikiee4d798f2012-01-20 21:50:17 +00009535 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009536}
9537
Richard Smithf57d8cb2011-12-09 22:58:01 +00009538/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009539static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009540 const Expr *E,
9541 llvm::APSInt *Value,
9542 SourceLocation *Loc) {
9543 if (!E->getType()->isIntegralOrEnumerationType()) {
9544 if (Loc) *Loc = E->getExprLoc();
9545 return false;
9546 }
9547
Richard Smith66e05fe2012-01-18 05:21:49 +00009548 APValue Result;
9549 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009550 return false;
9551
Richard Smith98710fc2014-11-13 23:03:19 +00009552 if (!Result.isInt()) {
9553 if (Loc) *Loc = E->getExprLoc();
9554 return false;
9555 }
9556
Richard Smith66e05fe2012-01-18 05:21:49 +00009557 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009558 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009559}
9560
Craig Toppera31a8822013-08-22 07:09:37 +00009561bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9562 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009563 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009564 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009565
Richard Smith9e575da2012-12-28 13:25:52 +00009566 ICEDiag D = CheckICE(this, Ctx);
9567 if (D.Kind != IK_ICE) {
9568 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009569 return false;
9570 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009571 return true;
9572}
9573
Craig Toppera31a8822013-08-22 07:09:37 +00009574bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009575 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009576 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009577 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9578
9579 if (!isIntegerConstantExpr(Ctx, Loc))
9580 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009581 // The only possible side-effects here are due to UB discovered in the
9582 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9583 // required to treat the expression as an ICE, so we produce the folded
9584 // value.
9585 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009586 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009587 return true;
9588}
Richard Smith66e05fe2012-01-18 05:21:49 +00009589
Craig Toppera31a8822013-08-22 07:09:37 +00009590bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009591 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009592}
9593
Craig Toppera31a8822013-08-22 07:09:37 +00009594bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009595 SourceLocation *Loc) const {
9596 // We support this checking in C++98 mode in order to diagnose compatibility
9597 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009598 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009599
Richard Smith98a0a492012-02-14 21:38:30 +00009600 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009601 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009602 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009603 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009604 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009605
9606 APValue Scratch;
9607 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9608
9609 if (!Diags.empty()) {
9610 IsConstExpr = false;
9611 if (Loc) *Loc = Diags[0].first;
9612 } else if (!IsConstExpr) {
9613 // FIXME: This shouldn't happen.
9614 if (Loc) *Loc = getExprLoc();
9615 }
9616
9617 return IsConstExpr;
9618}
Richard Smith253c2a32012-01-27 01:14:48 +00009619
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009620bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9621 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009622 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009623 Expr::EvalStatus Status;
9624 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9625
9626 ArgVector ArgValues(Args.size());
9627 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9628 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009629 if ((*I)->isValueDependent() ||
9630 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009631 // If evaluation fails, throw away the argument entirely.
9632 ArgValues[I - Args.begin()] = APValue();
9633 if (Info.EvalStatus.HasSideEffects)
9634 return false;
9635 }
9636
9637 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009638 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009639 ArgValues.data());
9640 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9641}
9642
Richard Smith253c2a32012-01-27 01:14:48 +00009643bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009644 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009645 PartialDiagnosticAt> &Diags) {
9646 // FIXME: It would be useful to check constexpr function templates, but at the
9647 // moment the constant expression evaluator cannot cope with the non-rigorous
9648 // ASTs which we build for dependent expressions.
9649 if (FD->isDependentContext())
9650 return true;
9651
9652 Expr::EvalStatus Status;
9653 Status.Diag = &Diags;
9654
Richard Smith6d4c6582013-11-05 22:18:15 +00009655 EvalInfo Info(FD->getASTContext(), Status,
9656 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009657
9658 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009659 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009660
Richard Smith7525ff62013-05-09 07:14:00 +00009661 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009662 // is a temporary being used as the 'this' pointer.
9663 LValue This;
9664 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009665 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009666
Richard Smith253c2a32012-01-27 01:14:48 +00009667 ArrayRef<const Expr*> Args;
9668
9669 SourceLocation Loc = FD->getLocation();
9670
Richard Smith2e312c82012-03-03 22:46:17 +00009671 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009672 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9673 // Evaluate the call as a constant initializer, to allow the construction
9674 // of objects of non-literal types.
9675 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009676 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009677 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009678 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009679 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009680
9681 return Diags.empty();
9682}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009683
9684bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9685 const FunctionDecl *FD,
9686 SmallVectorImpl<
9687 PartialDiagnosticAt> &Diags) {
9688 Expr::EvalStatus Status;
9689 Status.Diag = &Diags;
9690
9691 EvalInfo Info(FD->getASTContext(), Status,
9692 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9693
9694 // Fabricate a call stack frame to give the arguments a plausible cover story.
9695 ArrayRef<const Expr*> Args;
9696 ArgVector ArgValues(0);
9697 bool Success = EvaluateArgs(Args, ArgValues, Info);
9698 (void)Success;
9699 assert(Success &&
9700 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009701 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009702
9703 APValue ResultScratch;
9704 Evaluate(ResultScratch, Info, E);
9705 return Diags.empty();
9706}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009707
9708bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9709 unsigned Type) const {
9710 if (!getType()->isPointerType())
9711 return false;
9712
9713 Expr::EvalStatus Status;
9714 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9715 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9716}