blob: 7fd817714c915f7cac85173b30b73d4fdc41173b [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
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.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000160 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000163 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000166 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
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 /// Callee - The function which was called.
314 const FunctionDecl *Callee;
315
Richard Smithd62306a2011-11-10 06:34:14 +0000316 /// This - The binding for the this pointer in this call, if any.
317 const LValue *This;
318
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000319 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000320 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000321 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000322
Eli Friedman4830ec82012-06-25 21:21:08 +0000323 // Note that we intentionally use std::map here so that references to
324 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000325 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000326 typedef MapTy::const_iterator temp_iterator;
327 /// Temporaries - Temporary lvalues materialized within this stack frame.
328 MapTy Temporaries;
329
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000330 /// CallLoc - The location of the call expression for this call.
331 SourceLocation CallLoc;
332
333 /// Index - The call index of this call.
334 unsigned Index;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
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
George Burgess IV8c892b52016-05-25 22:31:54 +0000480 /// \brief Whether or not we're currently speculatively evaluating.
481 bool IsSpeculativelyEvaluating;
482
Richard Smith6d4c6582013-11-05 22:18:15 +0000483 enum EvaluationMode {
484 /// Evaluate as a constant expression. Stop if we find that the expression
485 /// is not a constant expression.
486 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000487
Richard Smith6d4c6582013-11-05 22:18:15 +0000488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression.
492 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000493
Richard Smith6d4c6582013-11-05 22:18:15 +0000494 /// Fold the expression to a constant. Stop if we hit a side-effect that
495 /// we can't model.
496 EM_ConstantFold,
497
498 /// Evaluate the expression looking for integer overflow and similar
499 /// issues. Don't worry about side-effects, and try to visit all
500 /// subexpressions.
501 EM_EvaluateForOverflow,
502
503 /// Evaluate in any way we know how. Don't worry about side-effects that
504 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000505 EM_IgnoreSideEffects,
506
507 /// Evaluate as a constant expression. Stop if we find that the expression
508 /// is not a constant expression. Some expressions can be retried in the
509 /// optimizer if we don't constant fold them here, but in an unevaluated
510 /// context we try to fold them immediately since the optimizer never
511 /// gets a chance to look at it.
512 EM_ConstantExpressionUnevaluated,
513
514 /// Evaluate as a potential constant expression. Keep going if we hit a
515 /// construct that we can't evaluate yet (because we don't yet know the
516 /// value of something) but stop if we hit something that could never be
517 /// a constant expression. Some expressions can be retried in the
518 /// optimizer if we don't constant fold them here, but in an unevaluated
519 /// context we try to fold them immediately since the optimizer never
520 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000521 EM_PotentialConstantExpressionUnevaluated,
522
523 /// Evaluate as a constant expression. Continue evaluating if we find a
524 /// MemberExpr with a base that can't be evaluated.
525 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000526 } EvalMode;
527
528 /// Are we checking whether the expression is a potential constant
529 /// expression?
530 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000531 return EvalMode == EM_PotentialConstantExpression ||
532 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000533 }
534
535 /// Are we checking an expression for overflow?
536 // FIXME: We should check for any kind of undefined or suspicious behavior
537 // in such constructs, not just overflow.
538 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
539
540 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000541 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000542 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000543 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000544 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
545 EvaluatingDecl((const ValueDecl *)nullptr),
546 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000547 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
548 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000549
Richard Smith7525ff62013-05-09 07:14:00 +0000550 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
551 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000552 EvaluatingDeclValue = &Value;
553 }
554
David Blaikiebbafb8a2012-03-11 07:00:24 +0000555 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000556
Richard Smith357362d2011-12-13 06:39:58 +0000557 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000558 // Don't perform any constexpr calls (other than the call we're checking)
559 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000560 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000561 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000562 if (NextCallIndex == 0) {
563 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000564 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000565 return false;
566 }
Richard Smith357362d2011-12-13 06:39:58 +0000567 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
568 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000569 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000570 << getLangOpts().ConstexprCallDepth;
571 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000572 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000573
Richard Smithb228a862012-02-15 02:18:13 +0000574 CallStackFrame *getCallFrame(unsigned CallIndex) {
575 assert(CallIndex && "no call index in getCallFrame");
576 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
577 // be null in this loop.
578 CallStackFrame *Frame = CurrentCall;
579 while (Frame->Index > CallIndex)
580 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000582 }
583
Richard Smitha3d3bd22013-05-08 02:12:03 +0000584 bool nextStep(const Stmt *S) {
585 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000586 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000587 return false;
588 }
589 --StepsLeft;
590 return true;
591 }
592
Richard Smith357362d2011-12-13 06:39:58 +0000593 private:
594 /// Add a diagnostic to the diagnostics list.
595 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
596 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
597 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
598 return EvalStatus.Diag->back().second;
599 }
600
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 /// Add notes containing a call stack to the current point of evaluation.
602 void addCallStack(unsigned Limit);
603
Faisal Valie690b7a2016-07-02 22:34:24 +0000604 private:
605 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
606 unsigned ExtraNotes, bool IsCCEDiag) {
607
Richard Smith92b1ce02011-12-12 09:28:41 +0000608 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000609 // If we have a prior diagnostic, it will be noting that the expression
610 // isn't a constant expression. This diagnostic is more important,
611 // unless we require this evaluation to produce a constant expression.
612 //
613 // FIXME: We might want to show both diagnostics to the user in
614 // EM_ConstantFold mode.
615 if (!EvalStatus.Diag->empty()) {
616 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000617 case EM_ConstantFold:
618 case EM_IgnoreSideEffects:
619 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000620 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000621 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000622 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000623 case EM_ConstantExpression:
624 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000625 case EM_ConstantExpressionUnevaluated:
626 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000627 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000628 HasActiveDiagnostic = false;
629 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 }
631 }
632
Richard Smithf6f003a2011-12-16 19:06:07 +0000633 unsigned CallStackNotes = CallStackDepth - 1;
634 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
635 if (Limit)
636 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000637 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000638 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000639
Richard Smith357362d2011-12-13 06:39:58 +0000640 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000641 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000642 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000643 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
644 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000646 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000647 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000648 }
Richard Smith357362d2011-12-13 06:39:58 +0000649 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000650 return OptionalDiagnostic();
651 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000652 public:
653 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
654 OptionalDiagnostic
655 FFDiag(SourceLocation Loc,
656 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
657 unsigned ExtraNotes = 0) {
658 return Diag(Loc, DiagId, ExtraNotes, false);
659 }
660
661 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000662 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000663 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000664 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000665 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000666 HasActiveDiagnostic = false;
667 return OptionalDiagnostic();
668 }
669
Richard Smith92b1ce02011-12-12 09:28:41 +0000670 /// Diagnose that the evaluation does not produce a C++11 core constant
671 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000672 ///
673 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
674 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000675 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000676 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000677 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000678 // Don't override a previous diagnostic. Don't bother collecting
679 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000680 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000681 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000682 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000683 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000684 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000685 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000686 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
687 = diag::note_invalid_subexpr_in_const_expr,
688 unsigned ExtraNotes = 0) {
689 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
690 }
Richard Smith357362d2011-12-13 06:39:58 +0000691 /// Add a note to a prior diagnostic.
692 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
693 if (!HasActiveDiagnostic)
694 return OptionalDiagnostic();
695 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000696 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000697
698 /// Add a stack of notes to a prior diagnostic.
699 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
700 if (HasActiveDiagnostic) {
701 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
702 Diags.begin(), Diags.end());
703 }
704 }
Richard Smith253c2a32012-01-27 01:14:48 +0000705
Richard Smith6d4c6582013-11-05 22:18:15 +0000706 /// Should we continue evaluation after encountering a side-effect that we
707 /// couldn't model?
708 bool keepEvaluatingAfterSideEffect() {
709 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000710 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000711 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 case EM_EvaluateForOverflow:
713 case EM_IgnoreSideEffects:
714 return true;
715
Richard Smith6d4c6582013-11-05 22:18:15 +0000716 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000717 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000719 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 return false;
721 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000722 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000723 }
724
725 /// Note that we have had a side-effect, and determine whether we should
726 /// keep evaluating.
727 bool noteSideEffect() {
728 EvalStatus.HasSideEffects = true;
729 return keepEvaluatingAfterSideEffect();
730 }
731
Richard Smithce8eca52015-12-08 03:21:47 +0000732 /// Should we continue evaluation after encountering undefined behavior?
733 bool keepEvaluatingAfterUndefinedBehavior() {
734 switch (EvalMode) {
735 case EM_EvaluateForOverflow:
736 case EM_IgnoreSideEffects:
737 case EM_ConstantFold:
738 case EM_DesignatorFold:
739 return true;
740
741 case EM_PotentialConstantExpression:
742 case EM_PotentialConstantExpressionUnevaluated:
743 case EM_ConstantExpression:
744 case EM_ConstantExpressionUnevaluated:
745 return false;
746 }
747 llvm_unreachable("Missed EvalMode case");
748 }
749
750 /// Note that we hit something that was technically undefined behavior, but
751 /// that we can evaluate past it (such as signed overflow or floating-point
752 /// division by zero.)
753 bool noteUndefinedBehavior() {
754 EvalStatus.HasUndefinedBehavior = true;
755 return keepEvaluatingAfterUndefinedBehavior();
756 }
757
Richard Smith253c2a32012-01-27 01:14:48 +0000758 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000759 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000760 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 if (!StepsLeft)
762 return false;
763
764 switch (EvalMode) {
765 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000766 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000767 case EM_EvaluateForOverflow:
768 return true;
769
770 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000771 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000772 case EM_ConstantFold:
773 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000774 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000775 return false;
776 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000777 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000778 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000779
George Burgess IV8c892b52016-05-25 22:31:54 +0000780 /// Notes that we failed to evaluate an expression that other expressions
781 /// directly depend on, and determine if we should keep evaluating. This
782 /// should only be called if we actually intend to keep evaluating.
783 ///
784 /// Call noteSideEffect() instead if we may be able to ignore the value that
785 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
786 ///
787 /// (Foo(), 1) // use noteSideEffect
788 /// (Foo() || true) // use noteSideEffect
789 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000790 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000791 // Failure when evaluating some expression often means there is some
792 // subexpression whose evaluation was skipped. Therefore, (because we
793 // don't track whether we skipped an expression when unwinding after an
794 // evaluation failure) every evaluation failure that bubbles up from a
795 // subexpression implies that a side-effect has potentially happened. We
796 // skip setting the HasSideEffects flag to true until we decide to
797 // continue evaluating after that point, which happens here.
798 bool KeepGoing = keepEvaluatingAfterFailure();
799 EvalStatus.HasSideEffects |= KeepGoing;
800 return KeepGoing;
801 }
802
George Burgess IV3a03fab2015-09-04 21:28:13 +0000803 bool allowInvalidBaseExpr() const {
804 return EvalMode == EM_DesignatorFold;
805 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000806 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000807
808 /// Object used to treat all foldable expressions as constant expressions.
809 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000811 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000812 bool HadNoPriorDiags;
813 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000814
Richard Smith6d4c6582013-11-05 22:18:15 +0000815 explicit FoldConstant(EvalInfo &Info, bool Enabled)
816 : Info(Info),
817 Enabled(Enabled),
818 HadNoPriorDiags(Info.EvalStatus.Diag &&
819 Info.EvalStatus.Diag->empty() &&
820 !Info.EvalStatus.HasSideEffects),
821 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000822 if (Enabled &&
823 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
824 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000826 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000827 void keepDiagnostics() { Enabled = false; }
828 ~FoldConstant() {
829 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000830 !Info.EvalStatus.HasSideEffects)
831 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000832 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000833 }
834 };
Richard Smith17100ba2012-02-16 02:46:34 +0000835
George Burgess IV3a03fab2015-09-04 21:28:13 +0000836 /// RAII object used to treat the current evaluation as the correct pointer
837 /// offset fold for the current EvalMode
838 struct FoldOffsetRAII {
839 EvalInfo &Info;
840 EvalInfo::EvaluationMode OldMode;
841 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
842 : Info(Info), OldMode(Info.EvalMode) {
843 if (!Info.checkingPotentialConstantExpression())
844 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
845 : EvalInfo::EM_ConstantFold;
846 }
847
848 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
849 };
850
George Burgess IV8c892b52016-05-25 22:31:54 +0000851 /// RAII object used to optionally suppress diagnostics and side-effects from
852 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000853 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000854 /// Pair of EvalInfo, and a bit that stores whether or not we were
855 /// speculatively evaluating when we created this RAII.
856 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000857 Expr::EvalStatus Old;
858
George Burgess IV8c892b52016-05-25 22:31:54 +0000859 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
860 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
861 Old = Other.Old;
862 Other.InfoAndOldSpecEval.setPointer(nullptr);
863 }
864
865 void maybeRestoreState() {
866 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
867 if (!Info)
868 return;
869
870 Info->EvalStatus = Old;
871 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
872 }
873
Richard Smith17100ba2012-02-16 02:46:34 +0000874 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000875 SpeculativeEvaluationRAII() = default;
876
877 SpeculativeEvaluationRAII(
878 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
879 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
880 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000881 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000882 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000883 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000884
885 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
886 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
887 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000888 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000889
890 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
891 maybeRestoreState();
892 moveFromAndCancel(std::move(Other));
893 return *this;
894 }
895
896 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000897 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000898
899 /// RAII object wrapping a full-expression or block scope, and handling
900 /// the ending of the lifetime of temporaries created within it.
901 template<bool IsFullExpression>
902 class ScopeRAII {
903 EvalInfo &Info;
904 unsigned OldStackSize;
905 public:
906 ScopeRAII(EvalInfo &Info)
907 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
908 ~ScopeRAII() {
909 // Body moved to a static method to encourage the compiler to inline away
910 // instances of this class.
911 cleanup(Info, OldStackSize);
912 }
913 private:
914 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
915 unsigned NewEnd = OldStackSize;
916 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
917 I != N; ++I) {
918 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
919 // Full-expression cleanup of a lifetime-extended temporary: nothing
920 // to do, just move this cleanup to the right place in the stack.
921 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
922 ++NewEnd;
923 } else {
924 // End the lifetime of the object.
925 Info.CleanupStack[I].endLifetime();
926 }
927 }
928 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
929 Info.CleanupStack.end());
930 }
931 };
932 typedef ScopeRAII<false> BlockScopeRAII;
933 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000934}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000935
Richard Smitha8105bc2012-01-06 16:39:00 +0000936bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
937 CheckSubobjectKind CSK) {
938 if (Invalid)
939 return false;
940 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000941 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000942 << CSK;
943 setInvalid();
944 return false;
945 }
946 return true;
947}
948
949void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
950 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000951 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000952 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000953 << static_cast<int>(N) << /*array*/ 0
954 << static_cast<unsigned>(MostDerivedArraySize);
955 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000956 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000957 << static_cast<int>(N) << /*non-array*/ 1;
958 setInvalid();
959}
960
Richard Smithf6f003a2011-12-16 19:06:07 +0000961CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
962 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000963 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +0000964 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
965 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000966 Info.CurrentCall = this;
967 ++Info.CallStackDepth;
968}
969
970CallStackFrame::~CallStackFrame() {
971 assert(Info.CurrentCall == this && "calls retired out of order");
972 --Info.CallStackDepth;
973 Info.CurrentCall = Caller;
974}
975
Richard Smith08d6a2c2013-07-24 07:11:57 +0000976APValue &CallStackFrame::createTemporary(const void *Key,
977 bool IsLifetimeExtended) {
978 APValue &Result = Temporaries[Key];
979 assert(Result.isUninit() && "temporary created multiple times");
980 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
981 return Result;
982}
983
Richard Smith84401042013-06-03 05:03:02 +0000984static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000985
986void EvalInfo::addCallStack(unsigned Limit) {
987 // Determine which calls to skip, if any.
988 unsigned ActiveCalls = CallStackDepth - 1;
989 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
990 if (Limit && Limit < ActiveCalls) {
991 SkipStart = Limit / 2 + Limit % 2;
992 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000993 }
994
Richard Smithf6f003a2011-12-16 19:06:07 +0000995 // Walk the call stack and add the diagnostics.
996 unsigned CallIdx = 0;
997 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
998 Frame = Frame->Caller, ++CallIdx) {
999 // Skip this call?
1000 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1001 if (CallIdx == SkipStart) {
1002 // Note that we're skipping calls.
1003 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1004 << unsigned(ActiveCalls - Limit);
1005 }
1006 continue;
1007 }
1008
Richard Smith5179eb72016-06-28 19:03:57 +00001009 // Use a different note for an inheriting constructor, because from the
1010 // user's perspective it's not really a function at all.
1011 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1012 if (CD->isInheritingConstructor()) {
1013 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1014 << CD->getParent();
1015 continue;
1016 }
1017 }
1018
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001019 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001020 llvm::raw_svector_ostream Out(Buffer);
1021 describeCall(Frame, Out);
1022 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1023 }
1024}
1025
1026namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001027 struct ComplexValue {
1028 private:
1029 bool IsInt;
1030
1031 public:
1032 APSInt IntReal, IntImag;
1033 APFloat FloatReal, FloatImag;
1034
1035 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1036
1037 void makeComplexFloat() { IsInt = false; }
1038 bool isComplexFloat() const { return !IsInt; }
1039 APFloat &getComplexFloatReal() { return FloatReal; }
1040 APFloat &getComplexFloatImag() { return FloatImag; }
1041
1042 void makeComplexInt() { IsInt = true; }
1043 bool isComplexInt() const { return IsInt; }
1044 APSInt &getComplexIntReal() { return IntReal; }
1045 APSInt &getComplexIntImag() { return IntImag; }
1046
Richard Smith2e312c82012-03-03 22:46:17 +00001047 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001048 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001049 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001050 else
Richard Smith2e312c82012-03-03 22:46:17 +00001051 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001052 }
Richard Smith2e312c82012-03-03 22:46:17 +00001053 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001054 assert(v.isComplexFloat() || v.isComplexInt());
1055 if (v.isComplexFloat()) {
1056 makeComplexFloat();
1057 FloatReal = v.getComplexFloatReal();
1058 FloatImag = v.getComplexFloatImag();
1059 } else {
1060 makeComplexInt();
1061 IntReal = v.getComplexIntReal();
1062 IntImag = v.getComplexIntImag();
1063 }
1064 }
John McCall93d91dc2010-05-07 17:22:02 +00001065 };
John McCall45d55e42010-05-07 21:00:08 +00001066
1067 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001068 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001069 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001070 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001071 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001072 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001073
Richard Smithce40ad62011-11-12 22:28:03 +00001074 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001075 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001076 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001077 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001078 SubobjectDesignator &getLValueDesignator() { return Designator; }
1079 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001080
Richard Smith2e312c82012-03-03 22:46:17 +00001081 void moveInto(APValue &V) const {
1082 if (Designator.Invalid)
1083 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1084 else
1085 V = APValue(Base, Offset, Designator.Entries,
1086 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001087 }
Richard Smith2e312c82012-03-03 22:46:17 +00001088 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001089 assert(V.isLValue());
1090 Base = V.getLValueBase();
1091 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001093 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001094 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001095 }
1096
George Burgess IV3a03fab2015-09-04 21:28:13 +00001097 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001098 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001099 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001100 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001101 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001102 Designator = SubobjectDesignator(getType(B));
1103 }
1104
George Burgess IV3a03fab2015-09-04 21:28:13 +00001105 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1106 set(B, I, true);
1107 }
1108
Richard Smitha8105bc2012-01-06 16:39:00 +00001109 // Check that this LValue is not based on a null pointer. If it is, produce
1110 // a diagnostic and mark the designator as invalid.
1111 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1112 CheckSubobjectKind CSK) {
1113 if (Designator.Invalid)
1114 return false;
1115 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001116 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001117 << CSK;
1118 Designator.setInvalid();
1119 return false;
1120 }
1121 return true;
1122 }
1123
1124 // Check this LValue refers to an object. If not, set the designator to be
1125 // invalid and emit a diagnostic.
1126 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001127 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001128 Designator.checkSubobject(Info, E, CSK);
1129 }
1130
1131 void addDecl(EvalInfo &Info, const Expr *E,
1132 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001133 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1134 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001135 }
1136 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001137 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1138 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001139 }
Richard Smith66c96992012-02-18 22:04:06 +00001140 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001141 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1142 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001143 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001144 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001145 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001146 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001147 }
John McCall45d55e42010-05-07 21:00:08 +00001148 };
Richard Smith027bf112011-11-17 22:56:20 +00001149
1150 struct MemberPtr {
1151 MemberPtr() {}
1152 explicit MemberPtr(const ValueDecl *Decl) :
1153 DeclAndIsDerivedMember(Decl, false), Path() {}
1154
1155 /// The member or (direct or indirect) field referred to by this member
1156 /// pointer, or 0 if this is a null member pointer.
1157 const ValueDecl *getDecl() const {
1158 return DeclAndIsDerivedMember.getPointer();
1159 }
1160 /// Is this actually a member of some type derived from the relevant class?
1161 bool isDerivedMember() const {
1162 return DeclAndIsDerivedMember.getInt();
1163 }
1164 /// Get the class which the declaration actually lives in.
1165 const CXXRecordDecl *getContainingRecord() const {
1166 return cast<CXXRecordDecl>(
1167 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1168 }
1169
Richard Smith2e312c82012-03-03 22:46:17 +00001170 void moveInto(APValue &V) const {
1171 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001172 }
Richard Smith2e312c82012-03-03 22:46:17 +00001173 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001174 assert(V.isMemberPointer());
1175 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1176 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1177 Path.clear();
1178 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1179 Path.insert(Path.end(), P.begin(), P.end());
1180 }
1181
1182 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1183 /// whether the member is a member of some class derived from the class type
1184 /// of the member pointer.
1185 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1186 /// Path - The path of base/derived classes from the member declaration's
1187 /// class (exclusive) to the class type of the member pointer (inclusive).
1188 SmallVector<const CXXRecordDecl*, 4> Path;
1189
1190 /// Perform a cast towards the class of the Decl (either up or down the
1191 /// hierarchy).
1192 bool castBack(const CXXRecordDecl *Class) {
1193 assert(!Path.empty());
1194 const CXXRecordDecl *Expected;
1195 if (Path.size() >= 2)
1196 Expected = Path[Path.size() - 2];
1197 else
1198 Expected = getContainingRecord();
1199 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1200 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1201 // if B does not contain the original member and is not a base or
1202 // derived class of the class containing the original member, the result
1203 // of the cast is undefined.
1204 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1205 // (D::*). We consider that to be a language defect.
1206 return false;
1207 }
1208 Path.pop_back();
1209 return true;
1210 }
1211 /// Perform a base-to-derived member pointer cast.
1212 bool castToDerived(const CXXRecordDecl *Derived) {
1213 if (!getDecl())
1214 return true;
1215 if (!isDerivedMember()) {
1216 Path.push_back(Derived);
1217 return true;
1218 }
1219 if (!castBack(Derived))
1220 return false;
1221 if (Path.empty())
1222 DeclAndIsDerivedMember.setInt(false);
1223 return true;
1224 }
1225 /// Perform a derived-to-base member pointer cast.
1226 bool castToBase(const CXXRecordDecl *Base) {
1227 if (!getDecl())
1228 return true;
1229 if (Path.empty())
1230 DeclAndIsDerivedMember.setInt(true);
1231 if (isDerivedMember()) {
1232 Path.push_back(Base);
1233 return true;
1234 }
1235 return castBack(Base);
1236 }
1237 };
Richard Smith357362d2011-12-13 06:39:58 +00001238
Richard Smith7bb00672012-02-01 01:42:44 +00001239 /// Compare two member pointers, which are assumed to be of the same type.
1240 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1241 if (!LHS.getDecl() || !RHS.getDecl())
1242 return !LHS.getDecl() && !RHS.getDecl();
1243 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1244 return false;
1245 return LHS.Path == RHS.Path;
1246 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001247}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001248
Richard Smith2e312c82012-03-03 22:46:17 +00001249static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001250static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1251 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001252 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001253static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1254static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001255static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1256 EvalInfo &Info);
1257static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001258static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001259static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001260 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001261static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001262static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001263static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001264static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001265
1266//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001267// Misc utilities
1268//===----------------------------------------------------------------------===//
1269
Richard Smith84401042013-06-03 05:03:02 +00001270/// Produce a string describing the given constexpr call.
1271static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1272 unsigned ArgIndex = 0;
1273 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1274 !isa<CXXConstructorDecl>(Frame->Callee) &&
1275 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1276
1277 if (!IsMemberCall)
1278 Out << *Frame->Callee << '(';
1279
1280 if (Frame->This && IsMemberCall) {
1281 APValue Val;
1282 Frame->This->moveInto(Val);
1283 Val.printPretty(Out, Frame->Info.Ctx,
1284 Frame->This->Designator.MostDerivedType);
1285 // FIXME: Add parens around Val if needed.
1286 Out << "->" << *Frame->Callee << '(';
1287 IsMemberCall = false;
1288 }
1289
1290 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1291 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1292 if (ArgIndex > (unsigned)IsMemberCall)
1293 Out << ", ";
1294
1295 const ParmVarDecl *Param = *I;
1296 const APValue &Arg = Frame->Arguments[ArgIndex];
1297 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1298
1299 if (ArgIndex == 0 && IsMemberCall)
1300 Out << "->" << *Frame->Callee << '(';
1301 }
1302
1303 Out << ')';
1304}
1305
Richard Smithd9f663b2013-04-22 15:31:51 +00001306/// Evaluate an expression to see if it had side-effects, and discard its
1307/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001308/// \return \c true if the caller should keep evaluating.
1309static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001310 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001311 if (!Evaluate(Scratch, Info, E))
1312 // We don't need the value, but we might have skipped a side effect here.
1313 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001314 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001315}
1316
Richard Smith861b5b52013-05-07 23:34:45 +00001317/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1318/// return its existing value.
1319static int64_t getExtValue(const APSInt &Value) {
1320 return Value.isSigned() ? Value.getSExtValue()
1321 : static_cast<int64_t>(Value.getZExtValue());
1322}
1323
Richard Smithd62306a2011-11-10 06:34:14 +00001324/// Should this call expression be treated as a string literal?
1325static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001326 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001327 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1328 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1329}
1330
Richard Smithce40ad62011-11-12 22:28:03 +00001331static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001332 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1333 // constant expression of pointer type that evaluates to...
1334
1335 // ... a null pointer value, or a prvalue core constant expression of type
1336 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001337 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001338
Richard Smithce40ad62011-11-12 22:28:03 +00001339 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1340 // ... the address of an object with static storage duration,
1341 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1342 return VD->hasGlobalStorage();
1343 // ... the address of a function,
1344 return isa<FunctionDecl>(D);
1345 }
1346
1347 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001348 switch (E->getStmtClass()) {
1349 default:
1350 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001351 case Expr::CompoundLiteralExprClass: {
1352 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1353 return CLE->isFileScope() && CLE->isLValue();
1354 }
Richard Smithe6c01442013-06-05 00:46:14 +00001355 case Expr::MaterializeTemporaryExprClass:
1356 // A materialized temporary might have been lifetime-extended to static
1357 // storage duration.
1358 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001359 // A string literal has static storage duration.
1360 case Expr::StringLiteralClass:
1361 case Expr::PredefinedExprClass:
1362 case Expr::ObjCStringLiteralClass:
1363 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001364 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001365 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001366 return true;
1367 case Expr::CallExprClass:
1368 return IsStringLiteralCall(cast<CallExpr>(E));
1369 // For GCC compatibility, &&label has static storage duration.
1370 case Expr::AddrLabelExprClass:
1371 return true;
1372 // A Block literal expression may be used as the initialization value for
1373 // Block variables at global or local static scope.
1374 case Expr::BlockExprClass:
1375 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001376 case Expr::ImplicitValueInitExprClass:
1377 // FIXME:
1378 // We can never form an lvalue with an implicit value initialization as its
1379 // base through expression evaluation, so these only appear in one case: the
1380 // implicit variable declaration we invent when checking whether a constexpr
1381 // constructor can produce a constant expression. We must assume that such
1382 // an expression might be a global lvalue.
1383 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001384 }
John McCall95007602010-05-10 23:27:23 +00001385}
1386
Richard Smithb228a862012-02-15 02:18:13 +00001387static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1388 assert(Base && "no location for a null lvalue");
1389 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1390 if (VD)
1391 Info.Note(VD->getLocation(), diag::note_declared_at);
1392 else
Ted Kremenek28831752012-08-23 20:46:57 +00001393 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001394 diag::note_constexpr_temporary_here);
1395}
1396
Richard Smith80815602011-11-07 05:07:52 +00001397/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001398/// value for an address or reference constant expression. Return true if we
1399/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001400static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, const LValue &LVal) {
1402 bool IsReferenceType = Type->isReferenceType();
1403
Richard Smith357362d2011-12-13 06:39:58 +00001404 APValue::LValueBase Base = LVal.getLValueBase();
1405 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1406
Richard Smith0dea49e2012-02-18 04:58:18 +00001407 // Check that the object is a global. Note that the fake 'this' object we
1408 // manufacture when checking potential constant expressions is conservatively
1409 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001410 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001411 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001412 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001413 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001414 << IsReferenceType << !Designator.Entries.empty()
1415 << !!VD << VD;
1416 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001417 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001418 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001419 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001420 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001421 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001422 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001423 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001424 LVal.getLValueCallIndex() == 0) &&
1425 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001426
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001427 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1428 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001429 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001430 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001431 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001432
Hans Wennborg82dd8772014-06-25 22:19:48 +00001433 // A dllimport variable never acts like a constant.
1434 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001435 return false;
1436 }
1437 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1438 // __declspec(dllimport) must be handled very carefully:
1439 // We must never initialize an expression with the thunk in C++.
1440 // Doing otherwise would allow the same id-expression to yield
1441 // different addresses for the same function in different translation
1442 // units. However, this means that we must dynamically initialize the
1443 // expression with the contents of the import address table at runtime.
1444 //
1445 // The C language has no notion of ODR; furthermore, it has no notion of
1446 // dynamic initialization. This means that we are permitted to
1447 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001448 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001449 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001450 }
1451 }
1452
Richard Smitha8105bc2012-01-06 16:39:00 +00001453 // Allow address constant expressions to be past-the-end pointers. This is
1454 // an extension: the standard requires them to point to an object.
1455 if (!IsReferenceType)
1456 return true;
1457
1458 // A reference constant expression must refer to an object.
1459 if (!Base) {
1460 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001461 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001462 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
1464
Richard Smith357362d2011-12-13 06:39:58 +00001465 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001466 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001467 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001468 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001469 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001470 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001471 }
1472
Richard Smith80815602011-11-07 05:07:52 +00001473 return true;
1474}
1475
Richard Smithfddd3842011-12-30 21:15:51 +00001476/// Check that this core constant expression is of literal type, and if not,
1477/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001478static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001479 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001480 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001481 return true;
1482
Richard Smith7525ff62013-05-09 07:14:00 +00001483 // C++1y: A constant initializer for an object o [...] may also invoke
1484 // constexpr constructors for o and its subobjects even if those objects
1485 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001486 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001487 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001488 return true;
1489
Richard Smithfddd3842011-12-30 21:15:51 +00001490 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001491 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001492 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001493 << E->getType();
1494 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001495 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001496 return false;
1497}
1498
Richard Smith0b0a0b62011-10-29 20:57:55 +00001499/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001500/// constant expression. If not, report an appropriate diagnostic. Does not
1501/// check that the expression is of literal type.
1502static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1503 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001504 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001505 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001506 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001507 return false;
1508 }
1509
Richard Smith77be48a2014-07-31 06:31:19 +00001510 // We allow _Atomic(T) to be initialized from anything that T can be
1511 // initialized from.
1512 if (const AtomicType *AT = Type->getAs<AtomicType>())
1513 Type = AT->getValueType();
1514
Richard Smithb228a862012-02-15 02:18:13 +00001515 // Core issue 1454: For a literal constant expression of array or class type,
1516 // each subobject of its value shall have been initialized by a constant
1517 // expression.
1518 if (Value.isArray()) {
1519 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1520 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1521 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1522 Value.getArrayInitializedElt(I)))
1523 return false;
1524 }
1525 if (!Value.hasArrayFiller())
1526 return true;
1527 return CheckConstantExpression(Info, DiagLoc, EltTy,
1528 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001529 }
Richard Smithb228a862012-02-15 02:18:13 +00001530 if (Value.isUnion() && Value.getUnionField()) {
1531 return CheckConstantExpression(Info, DiagLoc,
1532 Value.getUnionField()->getType(),
1533 Value.getUnionValue());
1534 }
1535 if (Value.isStruct()) {
1536 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1537 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1538 unsigned BaseIndex = 0;
1539 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1540 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1541 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1542 Value.getStructBase(BaseIndex)))
1543 return false;
1544 }
1545 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001546 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001547 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1548 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001549 return false;
1550 }
1551 }
1552
1553 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001554 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001555 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001556 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1557 }
1558
1559 // Everything else is fine.
1560 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001561}
1562
Benjamin Kramer8407df72015-03-09 16:47:52 +00001563static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001564 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001565}
1566
1567static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001568 if (Value.CallIndex)
1569 return false;
1570 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1571 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001572}
1573
Richard Smithcecf1842011-11-01 21:06:14 +00001574static bool IsWeakLValue(const LValue &Value) {
1575 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001576 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001577}
1578
David Majnemerb5116032014-12-09 23:32:34 +00001579static bool isZeroSized(const LValue &Value) {
1580 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001581 if (Decl && isa<VarDecl>(Decl)) {
1582 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001583 if (Ty->isArrayType())
1584 return Ty->isIncompleteType() ||
1585 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001586 }
1587 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001588}
1589
Richard Smith2e312c82012-03-03 22:46:17 +00001590static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001591 // A null base expression indicates a null pointer. These are always
1592 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001593 if (!Value.getLValueBase()) {
1594 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001595 return true;
1596 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001597
Richard Smith027bf112011-11-17 22:56:20 +00001598 // We have a non-null base. These are generally known to be true, but if it's
1599 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001600 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001601 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001602 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001603}
1604
Richard Smith2e312c82012-03-03 22:46:17 +00001605static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001606 switch (Val.getKind()) {
1607 case APValue::Uninitialized:
1608 return false;
1609 case APValue::Int:
1610 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001611 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001612 case APValue::Float:
1613 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001614 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001615 case APValue::ComplexInt:
1616 Result = Val.getComplexIntReal().getBoolValue() ||
1617 Val.getComplexIntImag().getBoolValue();
1618 return true;
1619 case APValue::ComplexFloat:
1620 Result = !Val.getComplexFloatReal().isZero() ||
1621 !Val.getComplexFloatImag().isZero();
1622 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001623 case APValue::LValue:
1624 return EvalPointerValueAsBool(Val, Result);
1625 case APValue::MemberPointer:
1626 Result = Val.getMemberPointerDecl();
1627 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001628 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001629 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001630 case APValue::Struct:
1631 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001632 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001633 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001634 }
1635
Richard Smith11562c52011-10-28 17:51:58 +00001636 llvm_unreachable("unknown APValue kind");
1637}
1638
1639static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1640 EvalInfo &Info) {
1641 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001642 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001643 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001644 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001645 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001646}
1647
Richard Smith357362d2011-12-13 06:39:58 +00001648template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001649static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001650 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001651 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001652 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001653 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001654}
1655
1656static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1657 QualType SrcType, const APFloat &Value,
1658 QualType DestType, APSInt &Result) {
1659 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001660 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001661 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001662
Richard Smith357362d2011-12-13 06:39:58 +00001663 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001664 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001665 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1666 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001667 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001668 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001669}
1670
Richard Smith357362d2011-12-13 06:39:58 +00001671static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1672 QualType SrcType, QualType DestType,
1673 APFloat &Result) {
1674 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001675 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001676 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1677 APFloat::rmNearestTiesToEven, &ignored)
1678 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001679 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001680 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001681}
1682
Richard Smith911e1422012-01-30 22:27:01 +00001683static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1684 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001685 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001686 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001687 APSInt Result = Value;
1688 // Figure out if this is a truncate, extend or noop cast.
1689 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001690 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001691 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001692 return Result;
1693}
1694
Richard Smith357362d2011-12-13 06:39:58 +00001695static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1696 QualType SrcType, const APSInt &Value,
1697 QualType DestType, APFloat &Result) {
1698 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1699 if (Result.convertFromAPInt(Value, Value.isSigned(),
1700 APFloat::rmNearestTiesToEven)
1701 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001702 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001703 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001704}
1705
Richard Smith49ca8aa2013-08-06 07:09:20 +00001706static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1707 APValue &Value, const FieldDecl *FD) {
1708 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1709
1710 if (!Value.isInt()) {
1711 // Trying to store a pointer-cast-to-integer into a bitfield.
1712 // FIXME: In this case, we should provide the diagnostic for casting
1713 // a pointer to an integer.
1714 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001715 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001716 return false;
1717 }
1718
1719 APSInt &Int = Value.getInt();
1720 unsigned OldBitWidth = Int.getBitWidth();
1721 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1722 if (NewBitWidth < OldBitWidth)
1723 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1724 return true;
1725}
1726
Eli Friedman803acb32011-12-22 03:51:45 +00001727static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1728 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001729 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001730 if (!Evaluate(SVal, Info, E))
1731 return false;
1732 if (SVal.isInt()) {
1733 Res = SVal.getInt();
1734 return true;
1735 }
1736 if (SVal.isFloat()) {
1737 Res = SVal.getFloat().bitcastToAPInt();
1738 return true;
1739 }
1740 if (SVal.isVector()) {
1741 QualType VecTy = E->getType();
1742 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1743 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1744 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1745 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1746 Res = llvm::APInt::getNullValue(VecSize);
1747 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1748 APValue &Elt = SVal.getVectorElt(i);
1749 llvm::APInt EltAsInt;
1750 if (Elt.isInt()) {
1751 EltAsInt = Elt.getInt();
1752 } else if (Elt.isFloat()) {
1753 EltAsInt = Elt.getFloat().bitcastToAPInt();
1754 } else {
1755 // Don't try to handle vectors of anything other than int or float
1756 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001757 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001758 return false;
1759 }
1760 unsigned BaseEltSize = EltAsInt.getBitWidth();
1761 if (BigEndian)
1762 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1763 else
1764 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1765 }
1766 return true;
1767 }
1768 // Give up if the input isn't an int, float, or vector. For example, we
1769 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001771 return false;
1772}
1773
Richard Smith43e77732013-05-07 04:50:00 +00001774/// Perform the given integer operation, which is known to need at most BitWidth
1775/// bits, and check for overflow in the original type (if that type was not an
1776/// unsigned type).
1777template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001778static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1779 const APSInt &LHS, const APSInt &RHS,
1780 unsigned BitWidth, Operation Op,
1781 APSInt &Result) {
1782 if (LHS.isUnsigned()) {
1783 Result = Op(LHS, RHS);
1784 return true;
1785 }
Richard Smith43e77732013-05-07 04:50:00 +00001786
1787 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001788 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001789 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001790 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001791 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001792 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001793 << Result.toString(10) << E->getType();
1794 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001795 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001796 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001797 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001798}
1799
1800/// Perform the given binary integer operation.
1801static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1802 BinaryOperatorKind Opcode, APSInt RHS,
1803 APSInt &Result) {
1804 switch (Opcode) {
1805 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001806 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001807 return false;
1808 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1810 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001811 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001812 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1813 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001814 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001815 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1816 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001817 case BO_And: Result = LHS & RHS; return true;
1818 case BO_Xor: Result = LHS ^ RHS; return true;
1819 case BO_Or: Result = LHS | RHS; return true;
1820 case BO_Div:
1821 case BO_Rem:
1822 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001823 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001824 return false;
1825 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001826 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1827 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1828 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001829 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1830 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001831 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1832 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001833 return true;
1834 case BO_Shl: {
1835 if (Info.getLangOpts().OpenCL)
1836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1838 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1839 RHS.isUnsigned());
1840 else if (RHS.isSigned() && RHS.isNegative()) {
1841 // During constant-folding, a negative shift is an opposite shift. Such
1842 // a shift is not a constant expression.
1843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1844 RHS = -RHS;
1845 goto shift_right;
1846 }
1847 shift_left:
1848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1849 // the shifted type.
1850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1851 if (SA != RHS) {
1852 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1853 << RHS << E->getType() << LHS.getBitWidth();
1854 } else if (LHS.isSigned()) {
1855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1856 // operand, and must not overflow the corresponding unsigned type.
1857 if (LHS.isNegative())
1858 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1859 else if (LHS.countLeadingZeros() < SA)
1860 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1861 }
1862 Result = LHS << SA;
1863 return true;
1864 }
1865 case BO_Shr: {
1866 if (Info.getLangOpts().OpenCL)
1867 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1868 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1869 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1870 RHS.isUnsigned());
1871 else if (RHS.isSigned() && RHS.isNegative()) {
1872 // During constant-folding, a negative shift is an opposite shift. Such a
1873 // shift is not a constant expression.
1874 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1875 RHS = -RHS;
1876 goto shift_left;
1877 }
1878 shift_right:
1879 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1880 // shifted type.
1881 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1882 if (SA != RHS)
1883 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1884 << RHS << E->getType() << LHS.getBitWidth();
1885 Result = LHS >> SA;
1886 return true;
1887 }
1888
1889 case BO_LT: Result = LHS < RHS; return true;
1890 case BO_GT: Result = LHS > RHS; return true;
1891 case BO_LE: Result = LHS <= RHS; return true;
1892 case BO_GE: Result = LHS >= RHS; return true;
1893 case BO_EQ: Result = LHS == RHS; return true;
1894 case BO_NE: Result = LHS != RHS; return true;
1895 }
1896}
1897
Richard Smith861b5b52013-05-07 23:34:45 +00001898/// Perform the given binary floating-point operation, in-place, on LHS.
1899static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1900 APFloat &LHS, BinaryOperatorKind Opcode,
1901 const APFloat &RHS) {
1902 switch (Opcode) {
1903 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001904 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001905 return false;
1906 case BO_Mul:
1907 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1908 break;
1909 case BO_Add:
1910 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1911 break;
1912 case BO_Sub:
1913 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1914 break;
1915 case BO_Div:
1916 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1917 break;
1918 }
1919
Richard Smith0c6124b2015-12-03 01:36:22 +00001920 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001921 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001922 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001923 }
Richard Smith861b5b52013-05-07 23:34:45 +00001924 return true;
1925}
1926
Richard Smitha8105bc2012-01-06 16:39:00 +00001927/// Cast an lvalue referring to a base subobject to a derived class, by
1928/// truncating the lvalue's path to the given length.
1929static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1930 const RecordDecl *TruncatedType,
1931 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001932 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001933
1934 // Check we actually point to a derived class object.
1935 if (TruncatedElements == D.Entries.size())
1936 return true;
1937 assert(TruncatedElements >= D.MostDerivedPathLength &&
1938 "not casting to a derived class");
1939 if (!Result.checkSubobject(Info, E, CSK_Derived))
1940 return false;
1941
1942 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001943 const RecordDecl *RD = TruncatedType;
1944 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001945 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001946 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1947 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001948 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001949 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001950 else
Richard Smithd62306a2011-11-10 06:34:14 +00001951 Result.Offset -= Layout.getBaseClassOffset(Base);
1952 RD = Base;
1953 }
Richard Smith027bf112011-11-17 22:56:20 +00001954 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001955 return true;
1956}
1957
John McCalld7bca762012-05-01 00:38:49 +00001958static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001959 const CXXRecordDecl *Derived,
1960 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001961 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001962 if (!RL) {
1963 if (Derived->isInvalidDecl()) return false;
1964 RL = &Info.Ctx.getASTRecordLayout(Derived);
1965 }
1966
Richard Smithd62306a2011-11-10 06:34:14 +00001967 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001968 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001969 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001970}
1971
Richard Smitha8105bc2012-01-06 16:39:00 +00001972static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001973 const CXXRecordDecl *DerivedDecl,
1974 const CXXBaseSpecifier *Base) {
1975 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1976
John McCalld7bca762012-05-01 00:38:49 +00001977 if (!Base->isVirtual())
1978 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001979
Richard Smitha8105bc2012-01-06 16:39:00 +00001980 SubobjectDesignator &D = Obj.Designator;
1981 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001982 return false;
1983
Richard Smitha8105bc2012-01-06 16:39:00 +00001984 // Extract most-derived object and corresponding type.
1985 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1986 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1987 return false;
1988
1989 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001990 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001991 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1992 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001993 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001994 return true;
1995}
1996
Richard Smith84401042013-06-03 05:03:02 +00001997static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1998 QualType Type, LValue &Result) {
1999 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2000 PathE = E->path_end();
2001 PathI != PathE; ++PathI) {
2002 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2003 *PathI))
2004 return false;
2005 Type = (*PathI)->getType();
2006 }
2007 return true;
2008}
2009
Richard Smithd62306a2011-11-10 06:34:14 +00002010/// Update LVal to refer to the given field, which must be a member of the type
2011/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002012static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002013 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002014 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002015 if (!RL) {
2016 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002017 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002018 }
Richard Smithd62306a2011-11-10 06:34:14 +00002019
2020 unsigned I = FD->getFieldIndex();
2021 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002022 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002023 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002024}
2025
Richard Smith1b78b3d2012-01-25 22:15:11 +00002026/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002027static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002028 LValue &LVal,
2029 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002030 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002031 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002032 return false;
2033 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002034}
2035
Richard Smithd62306a2011-11-10 06:34:14 +00002036/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002037static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2038 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002039 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2040 // extension.
2041 if (Type->isVoidType() || Type->isFunctionType()) {
2042 Size = CharUnits::One();
2043 return true;
2044 }
2045
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002046 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002047 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002048 return false;
2049 }
2050
Richard Smithd62306a2011-11-10 06:34:14 +00002051 if (!Type->isConstantSizeType()) {
2052 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002053 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002054 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002055 return false;
2056 }
2057
2058 Size = Info.Ctx.getTypeSizeInChars(Type);
2059 return true;
2060}
2061
2062/// Update a pointer value to model pointer arithmetic.
2063/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002064/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002065/// \param LVal - The pointer value to be updated.
2066/// \param EltTy - The pointee type represented by LVal.
2067/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002068static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2069 LValue &LVal, QualType EltTy,
2070 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002071 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002073 return false;
2074
2075 // Compute the new offset in the appropriate width.
2076 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002077 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002078 return true;
2079}
2080
Richard Smith66c96992012-02-18 22:04:06 +00002081/// Update an lvalue to refer to a component of a complex number.
2082/// \param Info - Information about the ongoing evaluation.
2083/// \param LVal - The lvalue to be updated.
2084/// \param EltTy - The complex number's component type.
2085/// \param Imag - False for the real component, true for the imaginary.
2086static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2087 LValue &LVal, QualType EltTy,
2088 bool Imag) {
2089 if (Imag) {
2090 CharUnits SizeOfComponent;
2091 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2092 return false;
2093 LVal.Offset += SizeOfComponent;
2094 }
2095 LVal.addComplex(Info, E, EltTy, Imag);
2096 return true;
2097}
2098
Richard Smith27908702011-10-24 17:54:18 +00002099/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002100///
2101/// \param Info Information about the ongoing evaluation.
2102/// \param E An expression to be used when printing diagnostics.
2103/// \param VD The variable whose initializer should be obtained.
2104/// \param Frame The frame in which the variable was created. Must be null
2105/// if this variable is not local to the evaluation.
2106/// \param Result Filled in with a pointer to the value of the variable.
2107static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2108 const VarDecl *VD, CallStackFrame *Frame,
2109 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002110 // If this is a parameter to an active constexpr function call, perform
2111 // argument substitution.
2112 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002113 // Assume arguments of a potential constant expression are unknown
2114 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002115 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002117 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002118 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002119 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002120 }
Richard Smith3229b742013-05-05 21:17:10 +00002121 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002122 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002123 }
Richard Smith27908702011-10-24 17:54:18 +00002124
Richard Smithd9f663b2013-04-22 15:31:51 +00002125 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002126 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002127 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002128 if (!Result) {
2129 // Assume variables referenced within a lambda's call operator that were
2130 // not declared within the call operator are captures and during checking
2131 // of a potential constant expression, assume they are unknown constant
2132 // expressions.
2133 assert(isLambdaCallOperator(Frame->Callee) &&
2134 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2135 "missing value for local variable");
2136 if (Info.checkingPotentialConstantExpression())
2137 return false;
2138 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002139 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002140 diag::note_unimplemented_constexpr_lambda_feature_ast)
2141 << "captures not currently allowed";
2142 return false;
2143 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002144 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002145 }
2146
Richard Smithd0b4dd62011-12-19 06:19:21 +00002147 // Dig out the initializer, and use the declaration which it's attached to.
2148 const Expr *Init = VD->getAnyInitializer(VD);
2149 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002150 // If we're checking a potential constant expression, the variable could be
2151 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002152 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002154 return false;
2155 }
2156
Richard Smithd62306a2011-11-10 06:34:14 +00002157 // If we're currently evaluating the initializer of this declaration, use that
2158 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002159 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002160 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002161 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002162 }
2163
Richard Smithcecf1842011-11-01 21:06:14 +00002164 // Never evaluate the initializer of a weak variable. We can't be sure that
2165 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002167 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002168 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002169 }
Richard Smithcecf1842011-11-01 21:06:14 +00002170
Richard Smithd0b4dd62011-12-19 06:19:21 +00002171 // Check that we can fold the initializer. In C++, we will have already done
2172 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002173 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002174 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002175 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002176 Notes.size() + 1) << VD;
2177 Info.Note(VD->getLocation(), diag::note_declared_at);
2178 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002179 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002180 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002181 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002182 Notes.size() + 1) << VD;
2183 Info.Note(VD->getLocation(), diag::note_declared_at);
2184 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002185 }
Richard Smith27908702011-10-24 17:54:18 +00002186
Richard Smith3229b742013-05-05 21:17:10 +00002187 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002188 return true;
Richard Smith27908702011-10-24 17:54:18 +00002189}
2190
Richard Smith11562c52011-10-28 17:51:58 +00002191static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002192 Qualifiers Quals = T.getQualifiers();
2193 return Quals.hasConst() && !Quals.hasVolatile();
2194}
2195
Richard Smithe97cbd72011-11-11 04:05:33 +00002196/// Get the base index of the given base class within an APValue representing
2197/// the given derived class.
2198static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2199 const CXXRecordDecl *Base) {
2200 Base = Base->getCanonicalDecl();
2201 unsigned Index = 0;
2202 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2203 E = Derived->bases_end(); I != E; ++I, ++Index) {
2204 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2205 return Index;
2206 }
2207
2208 llvm_unreachable("base class missing from derived class's bases list");
2209}
2210
Richard Smith3da88fa2013-04-26 14:36:30 +00002211/// Extract the value of a character from a string literal.
2212static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2213 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002214 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2215 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2216 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002217 const StringLiteral *S = cast<StringLiteral>(Lit);
2218 const ConstantArrayType *CAT =
2219 Info.Ctx.getAsConstantArrayType(S->getType());
2220 assert(CAT && "string literal isn't an array");
2221 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002222 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002223
2224 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002225 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002226 if (Index < S->getLength())
2227 Value = S->getCodeUnit(Index);
2228 return Value;
2229}
2230
Richard Smith3da88fa2013-04-26 14:36:30 +00002231// Expand a string literal into an array of characters.
2232static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2233 APValue &Result) {
2234 const StringLiteral *S = cast<StringLiteral>(Lit);
2235 const ConstantArrayType *CAT =
2236 Info.Ctx.getAsConstantArrayType(S->getType());
2237 assert(CAT && "string literal isn't an array");
2238 QualType CharType = CAT->getElementType();
2239 assert(CharType->isIntegerType() && "unexpected character type");
2240
2241 unsigned Elts = CAT->getSize().getZExtValue();
2242 Result = APValue(APValue::UninitArray(),
2243 std::min(S->getLength(), Elts), Elts);
2244 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2245 CharType->isUnsignedIntegerType());
2246 if (Result.hasArrayFiller())
2247 Result.getArrayFiller() = APValue(Value);
2248 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2249 Value = S->getCodeUnit(I);
2250 Result.getArrayInitializedElt(I) = APValue(Value);
2251 }
2252}
2253
2254// Expand an array so that it has more than Index filled elements.
2255static void expandArray(APValue &Array, unsigned Index) {
2256 unsigned Size = Array.getArraySize();
2257 assert(Index < Size);
2258
2259 // Always at least double the number of elements for which we store a value.
2260 unsigned OldElts = Array.getArrayInitializedElts();
2261 unsigned NewElts = std::max(Index+1, OldElts * 2);
2262 NewElts = std::min(Size, std::max(NewElts, 8u));
2263
2264 // Copy the data across.
2265 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2266 for (unsigned I = 0; I != OldElts; ++I)
2267 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2268 for (unsigned I = OldElts; I != NewElts; ++I)
2269 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2270 if (NewValue.hasArrayFiller())
2271 NewValue.getArrayFiller() = Array.getArrayFiller();
2272 Array.swap(NewValue);
2273}
2274
Richard Smithb01fe402014-09-16 01:24:02 +00002275/// Determine whether a type would actually be read by an lvalue-to-rvalue
2276/// conversion. If it's of class type, we may assume that the copy operation
2277/// is trivial. Note that this is never true for a union type with fields
2278/// (because the copy always "reads" the active member) and always true for
2279/// a non-class type.
2280static bool isReadByLvalueToRvalueConversion(QualType T) {
2281 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2282 if (!RD || (RD->isUnion() && !RD->field_empty()))
2283 return true;
2284 if (RD->isEmpty())
2285 return false;
2286
2287 for (auto *Field : RD->fields())
2288 if (isReadByLvalueToRvalueConversion(Field->getType()))
2289 return true;
2290
2291 for (auto &BaseSpec : RD->bases())
2292 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2293 return true;
2294
2295 return false;
2296}
2297
2298/// Diagnose an attempt to read from any unreadable field within the specified
2299/// type, which might be a class type.
2300static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2301 QualType T) {
2302 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2303 if (!RD)
2304 return false;
2305
2306 if (!RD->hasMutableFields())
2307 return false;
2308
2309 for (auto *Field : RD->fields()) {
2310 // If we're actually going to read this field in some way, then it can't
2311 // be mutable. If we're in a union, then assigning to a mutable field
2312 // (even an empty one) can change the active member, so that's not OK.
2313 // FIXME: Add core issue number for the union case.
2314 if (Field->isMutable() &&
2315 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002316 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002317 Info.Note(Field->getLocation(), diag::note_declared_at);
2318 return true;
2319 }
2320
2321 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2322 return true;
2323 }
2324
2325 for (auto &BaseSpec : RD->bases())
2326 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2327 return true;
2328
2329 // All mutable fields were empty, and thus not actually read.
2330 return false;
2331}
2332
Richard Smith861b5b52013-05-07 23:34:45 +00002333/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002334enum AccessKinds {
2335 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002336 AK_Assign,
2337 AK_Increment,
2338 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002339};
2340
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002341namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002342/// A handle to a complete object (an object that is not a subobject of
2343/// another object).
2344struct CompleteObject {
2345 /// The value of the complete object.
2346 APValue *Value;
2347 /// The type of the complete object.
2348 QualType Type;
2349
Craig Topper36250ad2014-05-12 05:36:57 +00002350 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002351 CompleteObject(APValue *Value, QualType Type)
2352 : Value(Value), Type(Type) {
2353 assert(Value && "missing value for complete object");
2354 }
2355
Aaron Ballman67347662015-02-15 22:00:28 +00002356 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002357};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002358} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002359
Richard Smith3da88fa2013-04-26 14:36:30 +00002360/// Find the designated sub-object of an rvalue.
2361template<typename SubobjectHandler>
2362typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002363findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002364 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002365 if (Sub.Invalid)
2366 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002367 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002368 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002369 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002370 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002371 << handler.AccessKind;
2372 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002373 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002374 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002375 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002376
Richard Smith3229b742013-05-05 21:17:10 +00002377 APValue *O = Obj.Value;
2378 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002379 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002380
Richard Smithd62306a2011-11-10 06:34:14 +00002381 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002382 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2383 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002384 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002385 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002386 return handler.failed();
2387 }
2388
Richard Smith49ca8aa2013-08-06 07:09:20 +00002389 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002390 // If we are reading an object of class type, there may still be more
2391 // things we need to check: if there are any mutable subobjects, we
2392 // cannot perform this read. (This only happens when performing a trivial
2393 // copy or assignment.)
2394 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2395 diagnoseUnreadableFields(Info, E, ObjType))
2396 return handler.failed();
2397
Richard Smith49ca8aa2013-08-06 07:09:20 +00002398 if (!handler.found(*O, ObjType))
2399 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002400
Richard Smith49ca8aa2013-08-06 07:09:20 +00002401 // If we modified a bit-field, truncate it to the right width.
2402 if (handler.AccessKind != AK_Read &&
2403 LastField && LastField->isBitField() &&
2404 !truncateBitfieldValue(Info, E, *O, LastField))
2405 return false;
2406
2407 return true;
2408 }
2409
Craig Topper36250ad2014-05-12 05:36:57 +00002410 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002411 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002412 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002413 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002414 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002415 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002416 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002417 // Note, it should not be possible to form a pointer with a valid
2418 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002419 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002420 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002421 << handler.AccessKind;
2422 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002423 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002424 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002425 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002426
2427 ObjType = CAT->getElementType();
2428
Richard Smith14a94132012-02-17 03:35:37 +00002429 // An array object is represented as either an Array APValue or as an
2430 // LValue which refers to a string literal.
2431 if (O->isLValue()) {
2432 assert(I == N - 1 && "extracting subobject of character?");
2433 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002434 if (handler.AccessKind != AK_Read)
2435 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2436 *O);
2437 else
2438 return handler.foundString(*O, ObjType, Index);
2439 }
2440
2441 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002442 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002443 else if (handler.AccessKind != AK_Read) {
2444 expandArray(*O, Index);
2445 O = &O->getArrayInitializedElt(Index);
2446 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002447 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002448 } else if (ObjType->isAnyComplexType()) {
2449 // Next subobject is a complex number.
2450 uint64_t Index = Sub.Entries[I].ArrayIndex;
2451 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002453 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002454 << handler.AccessKind;
2455 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002456 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002457 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002458 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002459
2460 bool WasConstQualified = ObjType.isConstQualified();
2461 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2462 if (WasConstQualified)
2463 ObjType.addConst();
2464
Richard Smith66c96992012-02-18 22:04:06 +00002465 assert(I == N - 1 && "extracting subobject of scalar?");
2466 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002467 return handler.found(Index ? O->getComplexIntImag()
2468 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002469 } else {
2470 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002471 return handler.found(Index ? O->getComplexFloatImag()
2472 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002473 }
Richard Smithd62306a2011-11-10 06:34:14 +00002474 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002475 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002476 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002477 << Field;
2478 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002480 }
2481
Richard Smithd62306a2011-11-10 06:34:14 +00002482 // Next subobject is a class, struct or union field.
2483 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2484 if (RD->isUnion()) {
2485 const FieldDecl *UnionField = O->getUnionField();
2486 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002487 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002488 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 << handler.AccessKind << Field << !UnionField << UnionField;
2490 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002491 }
Richard Smithd62306a2011-11-10 06:34:14 +00002492 O = &O->getUnionValue();
2493 } else
2494 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002495
2496 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002497 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002498 if (WasConstQualified && !Field->isMutable())
2499 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002500
2501 if (ObjType.isVolatileQualified()) {
2502 if (Info.getLangOpts().CPlusPlus) {
2503 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002504 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002505 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002506 Info.Note(Field->getLocation(), diag::note_declared_at);
2507 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002508 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002509 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002510 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002511 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002512
2513 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002514 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002515 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002516 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2517 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2518 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002519
2520 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002521 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002522 if (WasConstQualified)
2523 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002524 }
2525 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002526}
2527
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002528namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002529struct ExtractSubobjectHandler {
2530 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002531 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002532
2533 static const AccessKinds AccessKind = AK_Read;
2534
2535 typedef bool result_type;
2536 bool failed() { return false; }
2537 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002538 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002539 return true;
2540 }
2541 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002542 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002543 return true;
2544 }
2545 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002546 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002547 return true;
2548 }
2549 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002550 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002551 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2552 return true;
2553 }
2554};
Richard Smith3229b742013-05-05 21:17:10 +00002555} // end anonymous namespace
2556
Richard Smith3da88fa2013-04-26 14:36:30 +00002557const AccessKinds ExtractSubobjectHandler::AccessKind;
2558
2559/// Extract the designated sub-object of an rvalue.
2560static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002561 const CompleteObject &Obj,
2562 const SubobjectDesignator &Sub,
2563 APValue &Result) {
2564 ExtractSubobjectHandler Handler = { Info, Result };
2565 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002566}
2567
Richard Smith3229b742013-05-05 21:17:10 +00002568namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002569struct ModifySubobjectHandler {
2570 EvalInfo &Info;
2571 APValue &NewVal;
2572 const Expr *E;
2573
2574 typedef bool result_type;
2575 static const AccessKinds AccessKind = AK_Assign;
2576
2577 bool checkConst(QualType QT) {
2578 // Assigning to a const object has undefined behavior.
2579 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002581 return false;
2582 }
2583 return true;
2584 }
2585
2586 bool failed() { return false; }
2587 bool found(APValue &Subobj, QualType SubobjType) {
2588 if (!checkConst(SubobjType))
2589 return false;
2590 // We've been given ownership of NewVal, so just swap it in.
2591 Subobj.swap(NewVal);
2592 return true;
2593 }
2594 bool found(APSInt &Value, QualType SubobjType) {
2595 if (!checkConst(SubobjType))
2596 return false;
2597 if (!NewVal.isInt()) {
2598 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002599 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002600 return false;
2601 }
2602 Value = NewVal.getInt();
2603 return true;
2604 }
2605 bool found(APFloat &Value, QualType SubobjType) {
2606 if (!checkConst(SubobjType))
2607 return false;
2608 Value = NewVal.getFloat();
2609 return true;
2610 }
2611 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2612 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2613 }
2614};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002615} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002616
Richard Smith3229b742013-05-05 21:17:10 +00002617const AccessKinds ModifySubobjectHandler::AccessKind;
2618
Richard Smith3da88fa2013-04-26 14:36:30 +00002619/// Update the designated sub-object of an rvalue to the given value.
2620static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002621 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002622 const SubobjectDesignator &Sub,
2623 APValue &NewVal) {
2624 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002625 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002626}
2627
Richard Smith84f6dcf2012-02-02 01:16:57 +00002628/// Find the position where two subobject designators diverge, or equivalently
2629/// the length of the common initial subsequence.
2630static unsigned FindDesignatorMismatch(QualType ObjType,
2631 const SubobjectDesignator &A,
2632 const SubobjectDesignator &B,
2633 bool &WasArrayIndex) {
2634 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2635 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002636 if (!ObjType.isNull() &&
2637 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002638 // Next subobject is an array element.
2639 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2640 WasArrayIndex = true;
2641 return I;
2642 }
Richard Smith66c96992012-02-18 22:04:06 +00002643 if (ObjType->isAnyComplexType())
2644 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2645 else
2646 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002647 } else {
2648 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2649 WasArrayIndex = false;
2650 return I;
2651 }
2652 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2653 // Next subobject is a field.
2654 ObjType = FD->getType();
2655 else
2656 // Next subobject is a base class.
2657 ObjType = QualType();
2658 }
2659 }
2660 WasArrayIndex = false;
2661 return I;
2662}
2663
2664/// Determine whether the given subobject designators refer to elements of the
2665/// same array object.
2666static bool AreElementsOfSameArray(QualType ObjType,
2667 const SubobjectDesignator &A,
2668 const SubobjectDesignator &B) {
2669 if (A.Entries.size() != B.Entries.size())
2670 return false;
2671
George Burgess IVa51c4072015-10-16 01:49:01 +00002672 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002673 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2674 // A is a subobject of the array element.
2675 return false;
2676
2677 // If A (and B) designates an array element, the last entry will be the array
2678 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2679 // of length 1' case, and the entire path must match.
2680 bool WasArrayIndex;
2681 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2682 return CommonLength >= A.Entries.size() - IsArray;
2683}
2684
Richard Smith3229b742013-05-05 21:17:10 +00002685/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002686static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2687 AccessKinds AK, const LValue &LVal,
2688 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002689 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002691 return CompleteObject();
2692 }
2693
Craig Topper36250ad2014-05-12 05:36:57 +00002694 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002695 if (LVal.CallIndex) {
2696 Frame = Info.getCallFrame(LVal.CallIndex);
2697 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002698 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002699 << AK << LVal.Base.is<const ValueDecl*>();
2700 NoteLValueLocation(Info, LVal.Base);
2701 return CompleteObject();
2702 }
Richard Smith3229b742013-05-05 21:17:10 +00002703 }
2704
2705 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2706 // is not a constant expression (even if the object is non-volatile). We also
2707 // apply this rule to C++98, in order to conform to the expected 'volatile'
2708 // semantics.
2709 if (LValType.isVolatileQualified()) {
2710 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002711 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002712 << AK << LValType;
2713 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002714 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002715 return CompleteObject();
2716 }
2717
2718 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002719 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002720 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002721
2722 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2723 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2724 // In C++11, constexpr, non-volatile variables initialized with constant
2725 // expressions are constant expressions too. Inside constexpr functions,
2726 // parameters are constant expressions even if they're non-const.
2727 // In C++1y, objects local to a constant expression (those with a Frame) are
2728 // both readable and writable inside constant expressions.
2729 // In C, such things can also be folded, although they are not ICEs.
2730 const VarDecl *VD = dyn_cast<VarDecl>(D);
2731 if (VD) {
2732 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2733 VD = VDef;
2734 }
2735 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002736 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002737 return CompleteObject();
2738 }
2739
2740 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002741 if (BaseType.isVolatileQualified()) {
2742 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002743 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002744 << AK << 1 << VD;
2745 Info.Note(VD->getLocation(), diag::note_declared_at);
2746 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002747 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002748 }
2749 return CompleteObject();
2750 }
2751
2752 // Unless we're looking at a local variable or argument in a constexpr call,
2753 // the variable we're reading must be const.
2754 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002755 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002756 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2757 // OK, we can read and modify an object if we're in the process of
2758 // evaluating its initializer, because its lifetime began in this
2759 // evaluation.
2760 } else if (AK != AK_Read) {
2761 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002762 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002763 return CompleteObject();
2764 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002765 // OK, we can read this variable.
2766 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002767 // In OpenCL if a variable is in constant address space it is a const value.
2768 if (!(BaseType.isConstQualified() ||
2769 (Info.getLangOpts().OpenCL &&
2770 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002771 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002772 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002773 Info.Note(VD->getLocation(), diag::note_declared_at);
2774 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002775 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002776 }
2777 return CompleteObject();
2778 }
2779 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2780 // We support folding of const floating-point types, in order to make
2781 // static const data members of such types (supported as an extension)
2782 // more useful.
2783 if (Info.getLangOpts().CPlusPlus11) {
2784 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2785 Info.Note(VD->getLocation(), diag::note_declared_at);
2786 } else {
2787 Info.CCEDiag(E);
2788 }
2789 } else {
2790 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002791 if (Info.checkingPotentialConstantExpression() &&
2792 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2793 // The definition of this variable could be constexpr. We can't
2794 // access it right now, but may be able to in future.
2795 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002796 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002797 Info.Note(VD->getLocation(), diag::note_declared_at);
2798 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002800 }
2801 return CompleteObject();
2802 }
2803 }
2804
2805 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2806 return CompleteObject();
2807 } else {
2808 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2809
2810 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002811 if (const MaterializeTemporaryExpr *MTE =
2812 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2813 assert(MTE->getStorageDuration() == SD_Static &&
2814 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002815
Richard Smithe6c01442013-06-05 00:46:14 +00002816 // Per C++1y [expr.const]p2:
2817 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2818 // - a [...] glvalue of integral or enumeration type that refers to
2819 // a non-volatile const object [...]
2820 // [...]
2821 // - a [...] glvalue of literal type that refers to a non-volatile
2822 // object whose lifetime began within the evaluation of e.
2823 //
2824 // C++11 misses the 'began within the evaluation of e' check and
2825 // instead allows all temporaries, including things like:
2826 // int &&r = 1;
2827 // int x = ++r;
2828 // constexpr int k = r;
2829 // Therefore we use the C++1y rules in C++11 too.
2830 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2831 const ValueDecl *ED = MTE->getExtendingDecl();
2832 if (!(BaseType.isConstQualified() &&
2833 BaseType->isIntegralOrEnumerationType()) &&
2834 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002835 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002836 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2837 return CompleteObject();
2838 }
2839
2840 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2841 assert(BaseVal && "got reference to unevaluated temporary");
2842 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002843 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002844 return CompleteObject();
2845 }
2846 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002847 BaseVal = Frame->getTemporary(Base);
2848 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002849 }
Richard Smith3229b742013-05-05 21:17:10 +00002850
2851 // Volatile temporary objects cannot be accessed in constant expressions.
2852 if (BaseType.isVolatileQualified()) {
2853 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002854 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002855 << AK << 0;
2856 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2857 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002858 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002859 }
2860 return CompleteObject();
2861 }
2862 }
2863
Richard Smith7525ff62013-05-09 07:14:00 +00002864 // During the construction of an object, it is not yet 'const'.
2865 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2866 // and this doesn't do quite the right thing for const subobjects of the
2867 // object under construction.
2868 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2869 BaseType = Info.Ctx.getCanonicalType(BaseType);
2870 BaseType.removeLocalConst();
2871 }
2872
Richard Smith6d4c6582013-11-05 22:18:15 +00002873 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002874 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002875 //
2876 // FIXME: Not all local state is mutable. Allow local constant subobjects
2877 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002878 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2879 Info.EvalStatus.HasSideEffects) ||
2880 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002881 return CompleteObject();
2882
2883 return CompleteObject(BaseVal, BaseType);
2884}
2885
Richard Smith243ef902013-05-05 23:31:59 +00002886/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2887/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2888/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002889///
2890/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002891/// \param Conv - The expression for which we are performing the conversion.
2892/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002893/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2894/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002895/// \param LVal - The glvalue on which we are attempting to perform this action.
2896/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002897static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002898 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002899 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002900 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002901 return false;
2902
Richard Smith3229b742013-05-05 21:17:10 +00002903 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002904 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002905 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002906 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2907 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2908 // initializer until now for such expressions. Such an expression can't be
2909 // an ICE in C, so this only matters for fold.
2910 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2911 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002912 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002913 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002914 }
Richard Smith3229b742013-05-05 21:17:10 +00002915 APValue Lit;
2916 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2917 return false;
2918 CompleteObject LitObj(&Lit, Base->getType());
2919 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002920 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002921 // We represent a string literal array as an lvalue pointing at the
2922 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002923 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002924 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2925 CompleteObject StrObj(&Str, Base->getType());
2926 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002927 }
Richard Smith11562c52011-10-28 17:51:58 +00002928 }
2929
Richard Smith3229b742013-05-05 21:17:10 +00002930 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2931 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002932}
2933
2934/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002935static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002936 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002938 return false;
2939
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002940 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002941 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002942 return false;
2943 }
2944
Richard Smith3229b742013-05-05 21:17:10 +00002945 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2946 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002947}
2948
Richard Smith243ef902013-05-05 23:31:59 +00002949static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2950 return T->isSignedIntegerType() &&
2951 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2952}
2953
2954namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002955struct CompoundAssignSubobjectHandler {
2956 EvalInfo &Info;
2957 const Expr *E;
2958 QualType PromotedLHSType;
2959 BinaryOperatorKind Opcode;
2960 const APValue &RHS;
2961
2962 static const AccessKinds AccessKind = AK_Assign;
2963
2964 typedef bool result_type;
2965
2966 bool checkConst(QualType QT) {
2967 // Assigning to a const object has undefined behavior.
2968 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002969 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00002970 return false;
2971 }
2972 return true;
2973 }
2974
2975 bool failed() { return false; }
2976 bool found(APValue &Subobj, QualType SubobjType) {
2977 switch (Subobj.getKind()) {
2978 case APValue::Int:
2979 return found(Subobj.getInt(), SubobjType);
2980 case APValue::Float:
2981 return found(Subobj.getFloat(), SubobjType);
2982 case APValue::ComplexInt:
2983 case APValue::ComplexFloat:
2984 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00002985 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002986 return false;
2987 case APValue::LValue:
2988 return foundPointer(Subobj, SubobjType);
2989 default:
2990 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00002991 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002992 return false;
2993 }
2994 }
2995 bool found(APSInt &Value, QualType SubobjType) {
2996 if (!checkConst(SubobjType))
2997 return false;
2998
2999 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3000 // We don't support compound assignment on integer-cast-to-pointer
3001 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003002 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003003 return false;
3004 }
3005
3006 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3007 SubobjType, Value);
3008 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3009 return false;
3010 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3011 return true;
3012 }
3013 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003014 return checkConst(SubobjType) &&
3015 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3016 Value) &&
3017 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3018 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003019 }
3020 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3021 if (!checkConst(SubobjType))
3022 return false;
3023
3024 QualType PointeeType;
3025 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3026 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003027
3028 if (PointeeType.isNull() || !RHS.isInt() ||
3029 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003030 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003031 return false;
3032 }
3033
Richard Smith861b5b52013-05-07 23:34:45 +00003034 int64_t Offset = getExtValue(RHS.getInt());
3035 if (Opcode == BO_Sub)
3036 Offset = -Offset;
3037
3038 LValue LVal;
3039 LVal.setFrom(Info.Ctx, Subobj);
3040 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3041 return false;
3042 LVal.moveInto(Subobj);
3043 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003044 }
3045 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3046 llvm_unreachable("shouldn't encounter string elements here");
3047 }
3048};
3049} // end anonymous namespace
3050
3051const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3052
3053/// Perform a compound assignment of LVal <op>= RVal.
3054static bool handleCompoundAssignment(
3055 EvalInfo &Info, const Expr *E,
3056 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3057 BinaryOperatorKind Opcode, const APValue &RVal) {
3058 if (LVal.Designator.Invalid)
3059 return false;
3060
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003061 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003062 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003063 return false;
3064 }
3065
3066 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3067 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3068 RVal };
3069 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3070}
3071
3072namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003073struct IncDecSubobjectHandler {
3074 EvalInfo &Info;
3075 const Expr *E;
3076 AccessKinds AccessKind;
3077 APValue *Old;
3078
3079 typedef bool result_type;
3080
3081 bool checkConst(QualType QT) {
3082 // Assigning to a const object has undefined behavior.
3083 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003084 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003085 return false;
3086 }
3087 return true;
3088 }
3089
3090 bool failed() { return false; }
3091 bool found(APValue &Subobj, QualType SubobjType) {
3092 // Stash the old value. Also clear Old, so we don't clobber it later
3093 // if we're post-incrementing a complex.
3094 if (Old) {
3095 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003096 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003097 }
3098
3099 switch (Subobj.getKind()) {
3100 case APValue::Int:
3101 return found(Subobj.getInt(), SubobjType);
3102 case APValue::Float:
3103 return found(Subobj.getFloat(), SubobjType);
3104 case APValue::ComplexInt:
3105 return found(Subobj.getComplexIntReal(),
3106 SubobjType->castAs<ComplexType>()->getElementType()
3107 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3108 case APValue::ComplexFloat:
3109 return found(Subobj.getComplexFloatReal(),
3110 SubobjType->castAs<ComplexType>()->getElementType()
3111 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3112 case APValue::LValue:
3113 return foundPointer(Subobj, SubobjType);
3114 default:
3115 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003116 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003117 return false;
3118 }
3119 }
3120 bool found(APSInt &Value, QualType SubobjType) {
3121 if (!checkConst(SubobjType))
3122 return false;
3123
3124 if (!SubobjType->isIntegerType()) {
3125 // We don't support increment / decrement on integer-cast-to-pointer
3126 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003127 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003128 return false;
3129 }
3130
3131 if (Old) *Old = APValue(Value);
3132
3133 // bool arithmetic promotes to int, and the conversion back to bool
3134 // doesn't reduce mod 2^n, so special-case it.
3135 if (SubobjType->isBooleanType()) {
3136 if (AccessKind == AK_Increment)
3137 Value = 1;
3138 else
3139 Value = !Value;
3140 return true;
3141 }
3142
3143 bool WasNegative = Value.isNegative();
3144 if (AccessKind == AK_Increment) {
3145 ++Value;
3146
3147 if (!WasNegative && Value.isNegative() &&
3148 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3149 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003150 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003151 }
3152 } else {
3153 --Value;
3154
3155 if (WasNegative && !Value.isNegative() &&
3156 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3157 unsigned BitWidth = Value.getBitWidth();
3158 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3159 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003160 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003161 }
3162 }
3163 return true;
3164 }
3165 bool found(APFloat &Value, QualType SubobjType) {
3166 if (!checkConst(SubobjType))
3167 return false;
3168
3169 if (Old) *Old = APValue(Value);
3170
3171 APFloat One(Value.getSemantics(), 1);
3172 if (AccessKind == AK_Increment)
3173 Value.add(One, APFloat::rmNearestTiesToEven);
3174 else
3175 Value.subtract(One, APFloat::rmNearestTiesToEven);
3176 return true;
3177 }
3178 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3179 if (!checkConst(SubobjType))
3180 return false;
3181
3182 QualType PointeeType;
3183 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3184 PointeeType = PT->getPointeeType();
3185 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003186 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003187 return false;
3188 }
3189
3190 LValue LVal;
3191 LVal.setFrom(Info.Ctx, Subobj);
3192 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3193 AccessKind == AK_Increment ? 1 : -1))
3194 return false;
3195 LVal.moveInto(Subobj);
3196 return true;
3197 }
3198 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3199 llvm_unreachable("shouldn't encounter string elements here");
3200 }
3201};
3202} // end anonymous namespace
3203
3204/// Perform an increment or decrement on LVal.
3205static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3206 QualType LValType, bool IsIncrement, APValue *Old) {
3207 if (LVal.Designator.Invalid)
3208 return false;
3209
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003210 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003211 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003212 return false;
3213 }
3214
3215 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3216 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3217 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3218 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3219}
3220
Richard Smithe97cbd72011-11-11 04:05:33 +00003221/// Build an lvalue for the object argument of a member function call.
3222static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3223 LValue &This) {
3224 if (Object->getType()->isPointerType())
3225 return EvaluatePointer(Object, This, Info);
3226
3227 if (Object->isGLValue())
3228 return EvaluateLValue(Object, This, Info);
3229
Richard Smithd9f663b2013-04-22 15:31:51 +00003230 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003231 return EvaluateTemporary(Object, This, Info);
3232
Faisal Valie690b7a2016-07-02 22:34:24 +00003233 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003234 return false;
3235}
3236
3237/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3238/// lvalue referring to the result.
3239///
3240/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003241/// \param LV - An lvalue referring to the base of the member pointer.
3242/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003243/// \param IncludeMember - Specifies whether the member itself is included in
3244/// the resulting LValue subobject designator. This is not possible when
3245/// creating a bound member function.
3246/// \return The field or method declaration to which the member pointer refers,
3247/// or 0 if evaluation fails.
3248static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003249 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003250 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003251 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003252 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003253 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003254 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003255 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003256
3257 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3258 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003259 if (!MemPtr.getDecl()) {
3260 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003261 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003262 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003263 }
Richard Smith253c2a32012-01-27 01:14:48 +00003264
Richard Smith027bf112011-11-17 22:56:20 +00003265 if (MemPtr.isDerivedMember()) {
3266 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003267 // The end of the derived-to-base path for the base object must match the
3268 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003269 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003270 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003271 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003272 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003273 }
Richard Smith027bf112011-11-17 22:56:20 +00003274 unsigned PathLengthToMember =
3275 LV.Designator.Entries.size() - MemPtr.Path.size();
3276 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3277 const CXXRecordDecl *LVDecl = getAsBaseClass(
3278 LV.Designator.Entries[PathLengthToMember + I]);
3279 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003280 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003281 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003282 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003283 }
Richard Smith027bf112011-11-17 22:56:20 +00003284 }
3285
3286 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003287 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003288 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003289 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003290 } else if (!MemPtr.Path.empty()) {
3291 // Extend the LValue path with the member pointer's path.
3292 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3293 MemPtr.Path.size() + IncludeMember);
3294
3295 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003296 if (const PointerType *PT = LVType->getAs<PointerType>())
3297 LVType = PT->getPointeeType();
3298 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3299 assert(RD && "member pointer access on non-class-type expression");
3300 // The first class in the path is that of the lvalue.
3301 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3302 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003303 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003304 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003305 RD = Base;
3306 }
3307 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003308 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3309 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003310 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003311 }
3312
3313 // Add the member. Note that we cannot build bound member functions here.
3314 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003315 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003316 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003317 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003318 } else if (const IndirectFieldDecl *IFD =
3319 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003320 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003321 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003322 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003323 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003324 }
Richard Smith027bf112011-11-17 22:56:20 +00003325 }
3326
3327 return MemPtr.getDecl();
3328}
3329
Richard Smith84401042013-06-03 05:03:02 +00003330static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3331 const BinaryOperator *BO,
3332 LValue &LV,
3333 bool IncludeMember = true) {
3334 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3335
3336 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003337 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003338 MemberPtr MemPtr;
3339 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3340 }
Craig Topper36250ad2014-05-12 05:36:57 +00003341 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003342 }
3343
3344 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3345 BO->getRHS(), IncludeMember);
3346}
3347
Richard Smith027bf112011-11-17 22:56:20 +00003348/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3349/// the provided lvalue, which currently refers to the base object.
3350static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3351 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003352 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003353 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003354 return false;
3355
Richard Smitha8105bc2012-01-06 16:39:00 +00003356 QualType TargetQT = E->getType();
3357 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3358 TargetQT = PT->getPointeeType();
3359
3360 // Check this cast lands within the final derived-to-base subobject path.
3361 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003362 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003363 << D.MostDerivedType << TargetQT;
3364 return false;
3365 }
3366
Richard Smith027bf112011-11-17 22:56:20 +00003367 // Check the type of the final cast. We don't need to check the path,
3368 // since a cast can only be formed if the path is unique.
3369 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003370 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3371 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003372 if (NewEntriesSize == D.MostDerivedPathLength)
3373 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3374 else
Richard Smith027bf112011-11-17 22:56:20 +00003375 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003376 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003377 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003378 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003379 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003380 }
Richard Smith027bf112011-11-17 22:56:20 +00003381
3382 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003383 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003384}
3385
Mike Stump876387b2009-10-27 22:09:17 +00003386namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003387enum EvalStmtResult {
3388 /// Evaluation failed.
3389 ESR_Failed,
3390 /// Hit a 'return' statement.
3391 ESR_Returned,
3392 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003393 ESR_Succeeded,
3394 /// Hit a 'continue' statement.
3395 ESR_Continue,
3396 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003397 ESR_Break,
3398 /// Still scanning for 'case' or 'default' statement.
3399 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003400};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003401}
Richard Smith254a73d2011-10-28 22:34:42 +00003402
Richard Smith97fcf4b2016-08-14 23:15:52 +00003403static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3404 // We don't need to evaluate the initializer for a static local.
3405 if (!VD->hasLocalStorage())
3406 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003407
Richard Smith97fcf4b2016-08-14 23:15:52 +00003408 LValue Result;
3409 Result.set(VD, Info.CurrentCall->Index);
3410 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003411
Richard Smith97fcf4b2016-08-14 23:15:52 +00003412 const Expr *InitE = VD->getInit();
3413 if (!InitE) {
3414 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3415 << false << VD->getType();
3416 Val = APValue();
3417 return false;
3418 }
Richard Smith51f03172013-06-20 03:00:05 +00003419
Richard Smith97fcf4b2016-08-14 23:15:52 +00003420 if (InitE->isValueDependent())
3421 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003422
Richard Smith97fcf4b2016-08-14 23:15:52 +00003423 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3424 // Wipe out any partially-computed value, to allow tracking that this
3425 // evaluation failed.
3426 Val = APValue();
3427 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003428 }
3429
3430 return true;
3431}
3432
Richard Smith97fcf4b2016-08-14 23:15:52 +00003433static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3434 bool OK = true;
3435
3436 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3437 OK &= EvaluateVarDecl(Info, VD);
3438
3439 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3440 for (auto *BD : DD->bindings())
3441 if (auto *VD = BD->getHoldingVar())
3442 OK &= EvaluateDecl(Info, VD);
3443
3444 return OK;
3445}
3446
3447
Richard Smith4e18ca52013-05-06 05:56:11 +00003448/// Evaluate a condition (either a variable declaration or an expression).
3449static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3450 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003451 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003452 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3453 return false;
3454 return EvaluateAsBooleanCondition(Cond, Result, Info);
3455}
3456
Richard Smith89210072016-04-04 23:29:43 +00003457namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003458/// \brief A location where the result (returned value) of evaluating a
3459/// statement should be stored.
3460struct StmtResult {
3461 /// The APValue that should be filled in with the returned value.
3462 APValue &Value;
3463 /// The location containing the result, if any (used to support RVO).
3464 const LValue *Slot;
3465};
Richard Smith89210072016-04-04 23:29:43 +00003466}
Richard Smith52a980a2015-08-28 02:43:42 +00003467
3468static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003469 const Stmt *S,
3470 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003471
3472/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003473static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003474 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003475 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003476 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003477 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003478 case ESR_Break:
3479 return ESR_Succeeded;
3480 case ESR_Succeeded:
3481 case ESR_Continue:
3482 return ESR_Continue;
3483 case ESR_Failed:
3484 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003485 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003486 return ESR;
3487 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003488 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003489}
3490
Richard Smith496ddcf2013-05-12 17:32:42 +00003491/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003492static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003493 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003494 BlockScopeRAII Scope(Info);
3495
Richard Smith496ddcf2013-05-12 17:32:42 +00003496 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003497 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003498 {
3499 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003500 if (const Stmt *Init = SS->getInit()) {
3501 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3502 if (ESR != ESR_Succeeded)
3503 return ESR;
3504 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003505 if (SS->getConditionVariable() &&
3506 !EvaluateDecl(Info, SS->getConditionVariable()))
3507 return ESR_Failed;
3508 if (!EvaluateInteger(SS->getCond(), Value, Info))
3509 return ESR_Failed;
3510 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003511
3512 // Find the switch case corresponding to the value of the condition.
3513 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003514 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003515 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3516 SC = SC->getNextSwitchCase()) {
3517 if (isa<DefaultStmt>(SC)) {
3518 Found = SC;
3519 continue;
3520 }
3521
3522 const CaseStmt *CS = cast<CaseStmt>(SC);
3523 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3524 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3525 : LHS;
3526 if (LHS <= Value && Value <= RHS) {
3527 Found = SC;
3528 break;
3529 }
3530 }
3531
3532 if (!Found)
3533 return ESR_Succeeded;
3534
3535 // Search the switch body for the switch case and evaluate it from there.
3536 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3537 case ESR_Break:
3538 return ESR_Succeeded;
3539 case ESR_Succeeded:
3540 case ESR_Continue:
3541 case ESR_Failed:
3542 case ESR_Returned:
3543 return ESR;
3544 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003545 // This can only happen if the switch case is nested within a statement
3546 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003547 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003548 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003549 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003550 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003551}
3552
Richard Smith254a73d2011-10-28 22:34:42 +00003553// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003554static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003555 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003556 if (!Info.nextStep(S))
3557 return ESR_Failed;
3558
Richard Smith496ddcf2013-05-12 17:32:42 +00003559 // If we're hunting down a 'case' or 'default' label, recurse through
3560 // substatements until we hit the label.
3561 if (Case) {
3562 // FIXME: We don't start the lifetime of objects whose initialization we
3563 // jump over. However, such objects must be of class type with a trivial
3564 // default constructor that initialize all subobjects, so must be empty,
3565 // so this almost never matters.
3566 switch (S->getStmtClass()) {
3567 case Stmt::CompoundStmtClass:
3568 // FIXME: Precompute which substatement of a compound statement we
3569 // would jump to, and go straight there rather than performing a
3570 // linear scan each time.
3571 case Stmt::LabelStmtClass:
3572 case Stmt::AttributedStmtClass:
3573 case Stmt::DoStmtClass:
3574 break;
3575
3576 case Stmt::CaseStmtClass:
3577 case Stmt::DefaultStmtClass:
3578 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003579 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003580 break;
3581
3582 case Stmt::IfStmtClass: {
3583 // FIXME: Precompute which side of an 'if' we would jump to, and go
3584 // straight there rather than scanning both sides.
3585 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003586
3587 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3588 // preceded by our switch label.
3589 BlockScopeRAII Scope(Info);
3590
Richard Smith496ddcf2013-05-12 17:32:42 +00003591 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3592 if (ESR != ESR_CaseNotFound || !IS->getElse())
3593 return ESR;
3594 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3595 }
3596
3597 case Stmt::WhileStmtClass: {
3598 EvalStmtResult ESR =
3599 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3600 if (ESR != ESR_Continue)
3601 return ESR;
3602 break;
3603 }
3604
3605 case Stmt::ForStmtClass: {
3606 const ForStmt *FS = cast<ForStmt>(S);
3607 EvalStmtResult ESR =
3608 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3609 if (ESR != ESR_Continue)
3610 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003611 if (FS->getInc()) {
3612 FullExpressionRAII IncScope(Info);
3613 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3614 return ESR_Failed;
3615 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003616 break;
3617 }
3618
3619 case Stmt::DeclStmtClass:
3620 // FIXME: If the variable has initialization that can't be jumped over,
3621 // bail out of any immediately-surrounding compound-statement too.
3622 default:
3623 return ESR_CaseNotFound;
3624 }
3625 }
3626
Richard Smith254a73d2011-10-28 22:34:42 +00003627 switch (S->getStmtClass()) {
3628 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003629 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003630 // Don't bother evaluating beyond an expression-statement which couldn't
3631 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003632 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003633 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003634 return ESR_Failed;
3635 return ESR_Succeeded;
3636 }
3637
Faisal Valie690b7a2016-07-02 22:34:24 +00003638 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003639 return ESR_Failed;
3640
3641 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003642 return ESR_Succeeded;
3643
Richard Smithd9f663b2013-04-22 15:31:51 +00003644 case Stmt::DeclStmtClass: {
3645 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003646 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003647 // Each declaration initialization is its own full-expression.
3648 // FIXME: This isn't quite right; if we're performing aggregate
3649 // initialization, each braced subexpression is its own full-expression.
3650 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003651 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003652 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003653 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003654 return ESR_Succeeded;
3655 }
3656
Richard Smith357362d2011-12-13 06:39:58 +00003657 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003658 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003659 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003660 if (RetExpr &&
3661 !(Result.Slot
3662 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3663 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003664 return ESR_Failed;
3665 return ESR_Returned;
3666 }
Richard Smith254a73d2011-10-28 22:34:42 +00003667
3668 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003669 BlockScopeRAII Scope(Info);
3670
Richard Smith254a73d2011-10-28 22:34:42 +00003671 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003672 for (const auto *BI : CS->body()) {
3673 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003674 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003675 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003676 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003677 return ESR;
3678 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003679 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003680 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003681
3682 case Stmt::IfStmtClass: {
3683 const IfStmt *IS = cast<IfStmt>(S);
3684
3685 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003687 if (const Stmt *Init = IS->getInit()) {
3688 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3689 if (ESR != ESR_Succeeded)
3690 return ESR;
3691 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003692 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003693 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003694 return ESR_Failed;
3695
3696 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3697 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3698 if (ESR != ESR_Succeeded)
3699 return ESR;
3700 }
3701 return ESR_Succeeded;
3702 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003703
3704 case Stmt::WhileStmtClass: {
3705 const WhileStmt *WS = cast<WhileStmt>(S);
3706 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003707 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003708 bool Continue;
3709 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3710 Continue))
3711 return ESR_Failed;
3712 if (!Continue)
3713 break;
3714
3715 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3716 if (ESR != ESR_Continue)
3717 return ESR;
3718 }
3719 return ESR_Succeeded;
3720 }
3721
3722 case Stmt::DoStmtClass: {
3723 const DoStmt *DS = cast<DoStmt>(S);
3724 bool Continue;
3725 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003726 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003727 if (ESR != ESR_Continue)
3728 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003729 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003730
Richard Smith08d6a2c2013-07-24 07:11:57 +00003731 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003732 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3733 return ESR_Failed;
3734 } while (Continue);
3735 return ESR_Succeeded;
3736 }
3737
3738 case Stmt::ForStmtClass: {
3739 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003740 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003741 if (FS->getInit()) {
3742 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3743 if (ESR != ESR_Succeeded)
3744 return ESR;
3745 }
3746 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003747 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003748 bool Continue = true;
3749 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3750 FS->getCond(), Continue))
3751 return ESR_Failed;
3752 if (!Continue)
3753 break;
3754
3755 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3756 if (ESR != ESR_Continue)
3757 return ESR;
3758
Richard Smith08d6a2c2013-07-24 07:11:57 +00003759 if (FS->getInc()) {
3760 FullExpressionRAII IncScope(Info);
3761 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3762 return ESR_Failed;
3763 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003764 }
3765 return ESR_Succeeded;
3766 }
3767
Richard Smith896e0d72013-05-06 06:51:17 +00003768 case Stmt::CXXForRangeStmtClass: {
3769 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003770 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003771
3772 // Initialize the __range variable.
3773 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3774 if (ESR != ESR_Succeeded)
3775 return ESR;
3776
3777 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003778 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3779 if (ESR != ESR_Succeeded)
3780 return ESR;
3781 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003782 if (ESR != ESR_Succeeded)
3783 return ESR;
3784
3785 while (true) {
3786 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003787 {
3788 bool Continue = true;
3789 FullExpressionRAII CondExpr(Info);
3790 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3791 return ESR_Failed;
3792 if (!Continue)
3793 break;
3794 }
Richard Smith896e0d72013-05-06 06:51:17 +00003795
3796 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003797 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003798 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3799 if (ESR != ESR_Succeeded)
3800 return ESR;
3801
3802 // Loop body.
3803 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3804 if (ESR != ESR_Continue)
3805 return ESR;
3806
3807 // Increment: ++__begin
3808 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3809 return ESR_Failed;
3810 }
3811
3812 return ESR_Succeeded;
3813 }
3814
Richard Smith496ddcf2013-05-12 17:32:42 +00003815 case Stmt::SwitchStmtClass:
3816 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3817
Richard Smith4e18ca52013-05-06 05:56:11 +00003818 case Stmt::ContinueStmtClass:
3819 return ESR_Continue;
3820
3821 case Stmt::BreakStmtClass:
3822 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003823
3824 case Stmt::LabelStmtClass:
3825 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3826
3827 case Stmt::AttributedStmtClass:
3828 // As a general principle, C++11 attributes can be ignored without
3829 // any semantic impact.
3830 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3831 Case);
3832
3833 case Stmt::CaseStmtClass:
3834 case Stmt::DefaultStmtClass:
3835 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003836 }
3837}
3838
Richard Smithcc36f692011-12-22 02:22:31 +00003839/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3840/// default constructor. If so, we'll fold it whether or not it's marked as
3841/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3842/// so we need special handling.
3843static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003844 const CXXConstructorDecl *CD,
3845 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003846 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3847 return false;
3848
Richard Smith66e05fe2012-01-18 05:21:49 +00003849 // Value-initialization does not call a trivial default constructor, so such a
3850 // call is a core constant expression whether or not the constructor is
3851 // constexpr.
3852 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003853 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003854 // FIXME: If DiagDecl is an implicitly-declared special member function,
3855 // we should be much more explicit about why it's not constexpr.
3856 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3857 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3858 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003859 } else {
3860 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3861 }
3862 }
3863 return true;
3864}
3865
Richard Smith357362d2011-12-13 06:39:58 +00003866/// CheckConstexprFunction - Check that a function can be called in a constant
3867/// expression.
3868static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3869 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003870 const FunctionDecl *Definition,
3871 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003872 // Potential constant expressions can contain calls to declared, but not yet
3873 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003874 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003875 Declaration->isConstexpr())
3876 return false;
3877
Richard Smith0838f3a2013-05-14 05:18:44 +00003878 // Bail out with no diagnostic if the function declaration itself is invalid.
3879 // We will have produced a relevant diagnostic while parsing it.
3880 if (Declaration->isInvalidDecl())
3881 return false;
3882
Richard Smith357362d2011-12-13 06:39:58 +00003883 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003884 if (Definition && Definition->isConstexpr() &&
3885 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003886 return true;
3887
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003888 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003889 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003890
Richard Smith5179eb72016-06-28 19:03:57 +00003891 // If this function is not constexpr because it is an inherited
3892 // non-constexpr constructor, diagnose that directly.
3893 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3894 if (CD && CD->isInheritingConstructor()) {
3895 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3896 if (!Inherited->isConstexpr())
3897 DiagDecl = CD = Inherited;
3898 }
3899
3900 // FIXME: If DiagDecl is an implicitly-declared special member function
3901 // or an inheriting constructor, we should be much more explicit about why
3902 // it's not constexpr.
3903 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003904 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003905 << CD->getInheritedConstructor().getConstructor()->getParent();
3906 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003907 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003908 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003909 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3910 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003911 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003912 }
3913 return false;
3914}
3915
Richard Smithbe6dd812014-11-19 21:27:17 +00003916/// Determine if a class has any fields that might need to be copied by a
3917/// trivial copy or move operation.
3918static bool hasFields(const CXXRecordDecl *RD) {
3919 if (!RD || RD->isEmpty())
3920 return false;
3921 for (auto *FD : RD->fields()) {
3922 if (FD->isUnnamedBitfield())
3923 continue;
3924 return true;
3925 }
3926 for (auto &Base : RD->bases())
3927 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3928 return true;
3929 return false;
3930}
3931
Richard Smithd62306a2011-11-10 06:34:14 +00003932namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003933typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003934}
3935
3936/// EvaluateArgs - Evaluate the arguments to a function call.
3937static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3938 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003939 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003940 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003941 I != E; ++I) {
3942 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3943 // If we're checking for a potential constant expression, evaluate all
3944 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003945 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003946 return false;
3947 Success = false;
3948 }
3949 }
3950 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003951}
3952
Richard Smith254a73d2011-10-28 22:34:42 +00003953/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003954static bool HandleFunctionCall(SourceLocation CallLoc,
3955 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003956 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003957 EvalInfo &Info, APValue &Result,
3958 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003959 ArgVector ArgValues(Args.size());
3960 if (!EvaluateArgs(Args, ArgValues, Info))
3961 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003962
Richard Smith253c2a32012-01-27 01:14:48 +00003963 if (!Info.CheckCallLimit(CallLoc))
3964 return false;
3965
3966 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003967
3968 // For a trivial copy or move assignment, perform an APValue copy. This is
3969 // essential for unions, where the operations performed by the assignment
3970 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003971 //
3972 // Skip this for non-union classes with no fields; in that case, the defaulted
3973 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003974 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003975 if (MD && MD->isDefaulted() &&
3976 (MD->getParent()->isUnion() ||
3977 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003978 assert(This &&
3979 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3980 LValue RHS;
3981 RHS.setFrom(Info.Ctx, ArgValues[0]);
3982 APValue RHSValue;
3983 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3984 RHS, RHSValue))
3985 return false;
3986 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3987 RHSValue))
3988 return false;
3989 This->moveInto(Result);
3990 return true;
3991 }
3992
Richard Smith52a980a2015-08-28 02:43:42 +00003993 StmtResult Ret = {Result, ResultSlot};
3994 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003995 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003996 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003997 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00003998 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003999 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004000 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004001}
4002
Richard Smithd62306a2011-11-10 06:34:14 +00004003/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004004static bool HandleConstructorCall(const Expr *E, const LValue &This,
4005 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004006 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004007 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004008 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004009 if (!Info.CheckCallLimit(CallLoc))
4010 return false;
4011
Richard Smith3607ffe2012-02-13 03:54:03 +00004012 const CXXRecordDecl *RD = Definition->getParent();
4013 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004014 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004015 return false;
4016 }
4017
Richard Smith5179eb72016-06-28 19:03:57 +00004018 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004019
Richard Smith52a980a2015-08-28 02:43:42 +00004020 // FIXME: Creating an APValue just to hold a nonexistent return value is
4021 // wasteful.
4022 APValue RetVal;
4023 StmtResult Ret = {RetVal, nullptr};
4024
Richard Smith5179eb72016-06-28 19:03:57 +00004025 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004026 if (Definition->isDelegatingConstructor()) {
4027 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004028 {
4029 FullExpressionRAII InitScope(Info);
4030 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4031 return false;
4032 }
Richard Smith52a980a2015-08-28 02:43:42 +00004033 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004034 }
4035
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004036 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004037 // essential for unions (or classes with anonymous union members), where the
4038 // operations performed by the constructor cannot be represented by
4039 // ctor-initializers.
4040 //
4041 // Skip this for empty non-union classes; we should not perform an
4042 // lvalue-to-rvalue conversion on them because their copy constructor does not
4043 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004044 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004045 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004046 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004047 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004048 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004049 return handleLValueToRValueConversion(
4050 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4051 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004052 }
4053
4054 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004055 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004056 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004057 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004058
John McCalld7bca762012-05-01 00:38:49 +00004059 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004060 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4061
Richard Smith08d6a2c2013-07-24 07:11:57 +00004062 // A scope for temporaries lifetime-extended by reference members.
4063 BlockScopeRAII LifetimeExtendedScope(Info);
4064
Richard Smith253c2a32012-01-27 01:14:48 +00004065 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004066 unsigned BasesSeen = 0;
4067#ifndef NDEBUG
4068 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4069#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004070 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004071 LValue Subobject = This;
4072 APValue *Value = &Result;
4073
4074 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004075 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004076 if (I->isBaseInitializer()) {
4077 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004078#ifndef NDEBUG
4079 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004080 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004081 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4082 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4083 "base class initializers not in expected order");
4084 ++BaseIt;
4085#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004086 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004087 BaseType->getAsCXXRecordDecl(), &Layout))
4088 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004089 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004090 } else if ((FD = I->getMember())) {
4091 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004092 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004093 if (RD->isUnion()) {
4094 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004095 Value = &Result.getUnionValue();
4096 } else {
4097 Value = &Result.getStructField(FD->getFieldIndex());
4098 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004099 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004100 // Walk the indirect field decl's chain to find the object to initialize,
4101 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004102 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004103 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004104 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4105 // Switch the union field if it differs. This happens if we had
4106 // preceding zero-initialization, and we're now initializing a union
4107 // subobject other than the first.
4108 // FIXME: In this case, the values of the other subobjects are
4109 // specified, since zero-initialization sets all padding bits to zero.
4110 if (Value->isUninit() ||
4111 (Value->isUnion() && Value->getUnionField() != FD)) {
4112 if (CD->isUnion())
4113 *Value = APValue(FD);
4114 else
4115 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004116 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004117 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004118 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004119 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004120 if (CD->isUnion())
4121 Value = &Value->getUnionValue();
4122 else
4123 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004124 }
Richard Smithd62306a2011-11-10 06:34:14 +00004125 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004126 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004127 }
Richard Smith253c2a32012-01-27 01:14:48 +00004128
Richard Smith08d6a2c2013-07-24 07:11:57 +00004129 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004130 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4131 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004132 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004133 // If we're checking for a potential constant expression, evaluate all
4134 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004135 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004136 return false;
4137 Success = false;
4138 }
Richard Smithd62306a2011-11-10 06:34:14 +00004139 }
4140
Richard Smithd9f663b2013-04-22 15:31:51 +00004141 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004142 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004143}
4144
Richard Smith5179eb72016-06-28 19:03:57 +00004145static bool HandleConstructorCall(const Expr *E, const LValue &This,
4146 ArrayRef<const Expr*> Args,
4147 const CXXConstructorDecl *Definition,
4148 EvalInfo &Info, APValue &Result) {
4149 ArgVector ArgValues(Args.size());
4150 if (!EvaluateArgs(Args, ArgValues, Info))
4151 return false;
4152
4153 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4154 Info, Result);
4155}
4156
Eli Friedman9a156e52008-11-12 09:44:48 +00004157//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004158// Generic Evaluation
4159//===----------------------------------------------------------------------===//
4160namespace {
4161
Aaron Ballman68af21c2014-01-03 19:26:43 +00004162template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004163class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004164 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004165private:
Richard Smith52a980a2015-08-28 02:43:42 +00004166 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004167 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004168 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004169 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004170 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004171 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004172 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004173
Richard Smith17100ba2012-02-16 02:46:34 +00004174 // Check whether a conditional operator with a non-constant condition is a
4175 // potential constant expression. If neither arm is a potential constant
4176 // expression, then the conditional operator is not either.
4177 template<typename ConditionalOperator>
4178 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004179 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004180
4181 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004182 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004183 {
Richard Smith17100ba2012-02-16 02:46:34 +00004184 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004185 StmtVisitorTy::Visit(E->getFalseExpr());
4186 if (Diag.empty())
4187 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004188 }
Richard Smith17100ba2012-02-16 02:46:34 +00004189
George Burgess IV8c892b52016-05-25 22:31:54 +00004190 {
4191 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004192 Diag.clear();
4193 StmtVisitorTy::Visit(E->getTrueExpr());
4194 if (Diag.empty())
4195 return;
4196 }
4197
4198 Error(E, diag::note_constexpr_conditional_never_const);
4199 }
4200
4201
4202 template<typename ConditionalOperator>
4203 bool HandleConditionalOperator(const ConditionalOperator *E) {
4204 bool BoolResult;
4205 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004206 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004207 CheckPotentialConstantConditional(E);
4208 return false;
4209 }
4210
4211 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4212 return StmtVisitorTy::Visit(EvalExpr);
4213 }
4214
Peter Collingbournee9200682011-05-13 03:29:01 +00004215protected:
4216 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004217 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004218 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4219
Richard Smith92b1ce02011-12-12 09:28:41 +00004220 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004221 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004222 }
4223
Aaron Ballman68af21c2014-01-03 19:26:43 +00004224 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004225
4226public:
4227 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4228
4229 EvalInfo &getEvalInfo() { return Info; }
4230
Richard Smithf57d8cb2011-12-09 22:58:01 +00004231 /// Report an evaluation error. This should only be called when an error is
4232 /// first discovered. When propagating an error, just return false.
4233 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004234 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004235 return false;
4236 }
4237 bool Error(const Expr *E) {
4238 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4239 }
4240
Aaron Ballman68af21c2014-01-03 19:26:43 +00004241 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004242 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004243 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004244 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004245 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004246 }
4247
Aaron Ballman68af21c2014-01-03 19:26:43 +00004248 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004249 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004251 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004252 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004253 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004254 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004255 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004256 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004257 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004258 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004259 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004260 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004261 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004262 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004263 // The initializer may not have been parsed yet, or might be erroneous.
4264 if (!E->getExpr())
4265 return Error(E);
4266 return StmtVisitorTy::Visit(E->getExpr());
4267 }
Richard Smith5894a912011-12-19 22:12:41 +00004268 // We cannot create any objects for which cleanups are required, so there is
4269 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004270 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004271 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004272
Aaron Ballman68af21c2014-01-03 19:26:43 +00004273 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004274 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4275 return static_cast<Derived*>(this)->VisitCastExpr(E);
4276 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004277 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004278 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4279 return static_cast<Derived*>(this)->VisitCastExpr(E);
4280 }
4281
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004283 switch (E->getOpcode()) {
4284 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004285 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004286
4287 case BO_Comma:
4288 VisitIgnoredValue(E->getLHS());
4289 return StmtVisitorTy::Visit(E->getRHS());
4290
4291 case BO_PtrMemD:
4292 case BO_PtrMemI: {
4293 LValue Obj;
4294 if (!HandleMemberPointerAccess(Info, E, Obj))
4295 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004296 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004297 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004298 return false;
4299 return DerivedSuccess(Result, E);
4300 }
4301 }
4302 }
4303
Aaron Ballman68af21c2014-01-03 19:26:43 +00004304 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004305 // Evaluate and cache the common expression. We treat it as a temporary,
4306 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004307 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004308 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004309 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004310
Richard Smith17100ba2012-02-16 02:46:34 +00004311 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004312 }
4313
Aaron Ballman68af21c2014-01-03 19:26:43 +00004314 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004315 bool IsBcpCall = false;
4316 // If the condition (ignoring parens) is a __builtin_constant_p call,
4317 // the result is a constant expression if it can be folded without
4318 // side-effects. This is an important GNU extension. See GCC PR38377
4319 // for discussion.
4320 if (const CallExpr *CallCE =
4321 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004322 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004323 IsBcpCall = true;
4324
4325 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4326 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004327 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004328 return false;
4329
Richard Smith6d4c6582013-11-05 22:18:15 +00004330 FoldConstant Fold(Info, IsBcpCall);
4331 if (!HandleConditionalOperator(E)) {
4332 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004333 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004334 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004335
4336 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004337 }
4338
Aaron Ballman68af21c2014-01-03 19:26:43 +00004339 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004340 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4341 return DerivedSuccess(*Value, E);
4342
4343 const Expr *Source = E->getSourceExpr();
4344 if (!Source)
4345 return Error(E);
4346 if (Source == E) { // sanity checking.
4347 assert(0 && "OpaqueValueExpr recursively refers to itself");
4348 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004349 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004350 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004351 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004352
Aaron Ballman68af21c2014-01-03 19:26:43 +00004353 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004354 APValue Result;
4355 if (!handleCallExpr(E, Result, nullptr))
4356 return false;
4357 return DerivedSuccess(Result, E);
4358 }
4359
4360 bool handleCallExpr(const CallExpr *E, APValue &Result,
4361 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004362 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004363 QualType CalleeType = Callee->getType();
4364
Craig Topper36250ad2014-05-12 05:36:57 +00004365 const FunctionDecl *FD = nullptr;
4366 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004367 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004368 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004369
Richard Smithe97cbd72011-11-11 04:05:33 +00004370 // Extract function decl and 'this' pointer from the callee.
4371 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004372 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004373 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4374 // Explicit bound member calls, such as x.f() or p->g();
4375 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004376 return false;
4377 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004378 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004379 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004380 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4381 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004382 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4383 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004384 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004385 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004386 return Error(Callee);
4387
4388 FD = dyn_cast<FunctionDecl>(Member);
4389 if (!FD)
4390 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004391 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004392 LValue Call;
4393 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004394 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004395
Richard Smitha8105bc2012-01-06 16:39:00 +00004396 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004397 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004398 FD = dyn_cast_or_null<FunctionDecl>(
4399 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004400 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004401 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004402
4403 // Overloaded operator calls to member functions are represented as normal
4404 // calls with '*this' as the first argument.
4405 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4406 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004407 // FIXME: When selecting an implicit conversion for an overloaded
4408 // operator delete, we sometimes try to evaluate calls to conversion
4409 // operators without a 'this' parameter!
4410 if (Args.empty())
4411 return Error(E);
4412
Richard Smithe97cbd72011-11-11 04:05:33 +00004413 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4414 return false;
4415 This = &ThisVal;
4416 Args = Args.slice(1);
4417 }
4418
4419 // Don't call function pointers which have been cast to some other type.
4420 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004421 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004422 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004423 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004424
Richard Smith47b34932012-02-01 02:39:43 +00004425 if (This && !This->checkSubobject(Info, E, CSK_This))
4426 return false;
4427
Richard Smith3607ffe2012-02-13 03:54:03 +00004428 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4429 // calls to such functions in constant expressions.
4430 if (This && !HasQualifier &&
4431 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4432 return Error(E, diag::note_constexpr_virtual_call);
4433
Craig Topper36250ad2014-05-12 05:36:57 +00004434 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004435 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004436
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004437 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004438 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4439 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004440 return false;
4441
Richard Smith52a980a2015-08-28 02:43:42 +00004442 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004443 }
4444
Aaron Ballman68af21c2014-01-03 19:26:43 +00004445 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004446 return StmtVisitorTy::Visit(E->getInitializer());
4447 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004448 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004449 if (E->getNumInits() == 0)
4450 return DerivedZeroInitialization(E);
4451 if (E->getNumInits() == 1)
4452 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004453 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004454 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004455 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004456 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004457 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004458 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004459 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004460 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004461 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004462 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004463 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004464
Richard Smithd62306a2011-11-10 06:34:14 +00004465 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004466 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004467 assert(!E->isArrow() && "missing call to bound member function?");
4468
Richard Smith2e312c82012-03-03 22:46:17 +00004469 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004470 if (!Evaluate(Val, Info, E->getBase()))
4471 return false;
4472
4473 QualType BaseTy = E->getBase()->getType();
4474
4475 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004476 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004477 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004478 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004479 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4480
Richard Smith3229b742013-05-05 21:17:10 +00004481 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004482 SubobjectDesignator Designator(BaseTy);
4483 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004484
Richard Smith3229b742013-05-05 21:17:10 +00004485 APValue Result;
4486 return extractSubobject(Info, E, Obj, Designator, Result) &&
4487 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004488 }
4489
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004491 switch (E->getCastKind()) {
4492 default:
4493 break;
4494
Richard Smitha23ab512013-05-23 00:30:41 +00004495 case CK_AtomicToNonAtomic: {
4496 APValue AtomicVal;
4497 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4498 return false;
4499 return DerivedSuccess(AtomicVal, E);
4500 }
4501
Richard Smith11562c52011-10-28 17:51:58 +00004502 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004503 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004504 return StmtVisitorTy::Visit(E->getSubExpr());
4505
4506 case CK_LValueToRValue: {
4507 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004508 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4509 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004510 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004511 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004512 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004513 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004514 return false;
4515 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004516 }
4517 }
4518
Richard Smithf57d8cb2011-12-09 22:58:01 +00004519 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004520 }
4521
Aaron Ballman68af21c2014-01-03 19:26:43 +00004522 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004523 return VisitUnaryPostIncDec(UO);
4524 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004525 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004526 return VisitUnaryPostIncDec(UO);
4527 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004528 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004529 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004530 return Error(UO);
4531
4532 LValue LVal;
4533 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4534 return false;
4535 APValue RVal;
4536 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4537 UO->isIncrementOp(), &RVal))
4538 return false;
4539 return DerivedSuccess(RVal, UO);
4540 }
4541
Aaron Ballman68af21c2014-01-03 19:26:43 +00004542 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004543 // We will have checked the full-expressions inside the statement expression
4544 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004545 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004546 return Error(E);
4547
Richard Smith08d6a2c2013-07-24 07:11:57 +00004548 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004549 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004550 if (CS->body_empty())
4551 return true;
4552
Richard Smith51f03172013-06-20 03:00:05 +00004553 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4554 BE = CS->body_end();
4555 /**/; ++BI) {
4556 if (BI + 1 == BE) {
4557 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4558 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004559 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004560 diag::note_constexpr_stmt_expr_unsupported);
4561 return false;
4562 }
4563 return this->Visit(FinalExpr);
4564 }
4565
4566 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004567 StmtResult Result = { ReturnValue, nullptr };
4568 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004569 if (ESR != ESR_Succeeded) {
4570 // FIXME: If the statement-expression terminated due to 'return',
4571 // 'break', or 'continue', it would be nice to propagate that to
4572 // the outer statement evaluation rather than bailing out.
4573 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004574 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004575 diag::note_constexpr_stmt_expr_unsupported);
4576 return false;
4577 }
4578 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004579
4580 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004581 }
4582
Richard Smith4a678122011-10-24 18:44:57 +00004583 /// Visit a value which is evaluated, but whose value is ignored.
4584 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004585 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004586 }
David Majnemere9807b22016-02-26 04:23:19 +00004587
4588 /// Potentially visit a MemberExpr's base expression.
4589 void VisitIgnoredBaseExpression(const Expr *E) {
4590 // While MSVC doesn't evaluate the base expression, it does diagnose the
4591 // presence of side-effecting behavior.
4592 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4593 return;
4594 VisitIgnoredValue(E);
4595 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004596};
4597
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004598}
Peter Collingbournee9200682011-05-13 03:29:01 +00004599
4600//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004601// Common base class for lvalue and temporary evaluation.
4602//===----------------------------------------------------------------------===//
4603namespace {
4604template<class Derived>
4605class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004606 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004607protected:
4608 LValue &Result;
4609 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004610 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004611
4612 bool Success(APValue::LValueBase B) {
4613 Result.set(B);
4614 return true;
4615 }
4616
4617public:
4618 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4619 ExprEvaluatorBaseTy(Info), Result(Result) {}
4620
Richard Smith2e312c82012-03-03 22:46:17 +00004621 bool Success(const APValue &V, const Expr *E) {
4622 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004623 return true;
4624 }
Richard Smith027bf112011-11-17 22:56:20 +00004625
Richard Smith027bf112011-11-17 22:56:20 +00004626 bool VisitMemberExpr(const MemberExpr *E) {
4627 // Handle non-static data members.
4628 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004629 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004630 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004631 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004632 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004633 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004634 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004635 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004636 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004637 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004638 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004639 BaseTy = E->getBase()->getType();
4640 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004641 if (!EvalOK) {
4642 if (!this->Info.allowInvalidBaseExpr())
4643 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004644 Result.setInvalid(E);
4645 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004646 }
Richard Smith027bf112011-11-17 22:56:20 +00004647
Richard Smith1b78b3d2012-01-25 22:15:11 +00004648 const ValueDecl *MD = E->getMemberDecl();
4649 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4650 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4651 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4652 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004653 if (!HandleLValueMember(this->Info, E, Result, FD))
4654 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004655 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004656 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4657 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004658 } else
4659 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004660
Richard Smith1b78b3d2012-01-25 22:15:11 +00004661 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004662 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004663 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004664 RefValue))
4665 return false;
4666 return Success(RefValue, E);
4667 }
4668 return true;
4669 }
4670
4671 bool VisitBinaryOperator(const BinaryOperator *E) {
4672 switch (E->getOpcode()) {
4673 default:
4674 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4675
4676 case BO_PtrMemD:
4677 case BO_PtrMemI:
4678 return HandleMemberPointerAccess(this->Info, E, Result);
4679 }
4680 }
4681
4682 bool VisitCastExpr(const CastExpr *E) {
4683 switch (E->getCastKind()) {
4684 default:
4685 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4686
4687 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004688 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004689 if (!this->Visit(E->getSubExpr()))
4690 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004691
4692 // Now figure out the necessary offset to add to the base LV to get from
4693 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004694 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4695 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004696 }
4697 }
4698};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004699}
Richard Smith027bf112011-11-17 22:56:20 +00004700
4701//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004702// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004703//
4704// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4705// function designators (in C), decl references to void objects (in C), and
4706// temporaries (if building with -Wno-address-of-temporary).
4707//
4708// LValue evaluation produces values comprising a base expression of one of the
4709// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004710// - Declarations
4711// * VarDecl
4712// * FunctionDecl
4713// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004714// * CompoundLiteralExpr in C
4715// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004716// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004717// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004718// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004719// * ObjCEncodeExpr
4720// * AddrLabelExpr
4721// * BlockExpr
4722// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004723// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004724// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004725// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004726// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4727// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004728// * A MaterializeTemporaryExpr that has static storage duration, with no
4729// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004730// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004731//===----------------------------------------------------------------------===//
4732namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004733class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004734 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004735public:
Richard Smith027bf112011-11-17 22:56:20 +00004736 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4737 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004738
Richard Smith11562c52011-10-28 17:51:58 +00004739 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004740 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004741
Peter Collingbournee9200682011-05-13 03:29:01 +00004742 bool VisitDeclRefExpr(const DeclRefExpr *E);
4743 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004744 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004745 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4746 bool VisitMemberExpr(const MemberExpr *E);
4747 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4748 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004749 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004750 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004751 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4752 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004753 bool VisitUnaryReal(const UnaryOperator *E);
4754 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004755 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4756 return VisitUnaryPreIncDec(UO);
4757 }
4758 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4759 return VisitUnaryPreIncDec(UO);
4760 }
Richard Smith3229b742013-05-05 21:17:10 +00004761 bool VisitBinAssign(const BinaryOperator *BO);
4762 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004763
Peter Collingbournee9200682011-05-13 03:29:01 +00004764 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004765 switch (E->getCastKind()) {
4766 default:
Richard Smith027bf112011-11-17 22:56:20 +00004767 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004768
Eli Friedmance3e02a2011-10-11 00:13:24 +00004769 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004770 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004771 if (!Visit(E->getSubExpr()))
4772 return false;
4773 Result.Designator.setInvalid();
4774 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004775
Richard Smith027bf112011-11-17 22:56:20 +00004776 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004777 if (!Visit(E->getSubExpr()))
4778 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004779 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004780 }
4781 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004782};
4783} // end anonymous namespace
4784
Richard Smith11562c52011-10-28 17:51:58 +00004785/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004786/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004787/// * function designators in C, and
4788/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004789/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004790static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4791 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004792 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004793 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004794}
4795
Peter Collingbournee9200682011-05-13 03:29:01 +00004796bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004797 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004798 return Success(FD);
4799 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004800 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004801 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004802 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004803 return Error(E);
4804}
Richard Smith733237d2011-10-24 23:14:33 +00004805
Faisal Vali0528a312016-11-13 06:09:16 +00004806
Richard Smith11562c52011-10-28 17:51:58 +00004807bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004808 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004809 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4810 // Only if a local variable was declared in the function currently being
4811 // evaluated, do we expect to be able to find its value in the current
4812 // frame. (Otherwise it was likely declared in an enclosing context and
4813 // could either have a valid evaluatable value (for e.g. a constexpr
4814 // variable) or be ill-formed (and trigger an appropriate evaluation
4815 // diagnostic)).
4816 if (Info.CurrentCall->Callee &&
4817 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4818 Frame = Info.CurrentCall;
4819 }
4820 }
Richard Smith3229b742013-05-05 21:17:10 +00004821
Richard Smithfec09922011-11-01 16:57:24 +00004822 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004823 if (Frame) {
4824 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004825 return true;
4826 }
Richard Smithce40ad62011-11-12 22:28:03 +00004827 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004828 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004829
Richard Smith3229b742013-05-05 21:17:10 +00004830 APValue *V;
4831 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004832 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004833 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004834 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004835 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004836 return false;
4837 }
Richard Smith3229b742013-05-05 21:17:10 +00004838 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004839}
4840
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004841bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4842 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004843 // Walk through the expression to find the materialized temporary itself.
4844 SmallVector<const Expr *, 2> CommaLHSs;
4845 SmallVector<SubobjectAdjustment, 2> Adjustments;
4846 const Expr *Inner = E->GetTemporaryExpr()->
4847 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004848
Richard Smith84401042013-06-03 05:03:02 +00004849 // If we passed any comma operators, evaluate their LHSs.
4850 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4851 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4852 return false;
4853
Richard Smithe6c01442013-06-05 00:46:14 +00004854 // A materialized temporary with static storage duration can appear within the
4855 // result of a constant expression evaluation, so we need to preserve its
4856 // value for use outside this evaluation.
4857 APValue *Value;
4858 if (E->getStorageDuration() == SD_Static) {
4859 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004860 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004861 Result.set(E);
4862 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004863 Value = &Info.CurrentCall->
4864 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004865 Result.set(E, Info.CurrentCall->Index);
4866 }
4867
Richard Smithea4ad5d2013-06-06 08:19:16 +00004868 QualType Type = Inner->getType();
4869
Richard Smith84401042013-06-03 05:03:02 +00004870 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004871 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4872 (E->getStorageDuration() == SD_Static &&
4873 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4874 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004875 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004876 }
Richard Smith84401042013-06-03 05:03:02 +00004877
4878 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004879 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4880 --I;
4881 switch (Adjustments[I].Kind) {
4882 case SubobjectAdjustment::DerivedToBaseAdjustment:
4883 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4884 Type, Result))
4885 return false;
4886 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4887 break;
4888
4889 case SubobjectAdjustment::FieldAdjustment:
4890 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4891 return false;
4892 Type = Adjustments[I].Field->getType();
4893 break;
4894
4895 case SubobjectAdjustment::MemberPointerAdjustment:
4896 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4897 Adjustments[I].Ptr.RHS))
4898 return false;
4899 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4900 break;
4901 }
4902 }
4903
4904 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004905}
4906
Peter Collingbournee9200682011-05-13 03:29:01 +00004907bool
4908LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004909 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4910 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4911 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004912 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004913}
4914
Richard Smith6e525142011-12-27 12:18:28 +00004915bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004916 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004917 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004918
Faisal Valie690b7a2016-07-02 22:34:24 +00004919 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004920 << E->getExprOperand()->getType()
4921 << E->getExprOperand()->getSourceRange();
4922 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004923}
4924
Francois Pichet0066db92012-04-16 04:08:35 +00004925bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4926 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004927}
Francois Pichet0066db92012-04-16 04:08:35 +00004928
Peter Collingbournee9200682011-05-13 03:29:01 +00004929bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004930 // Handle static data members.
4931 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004932 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004933 return VisitVarDecl(E, VD);
4934 }
4935
Richard Smith254a73d2011-10-28 22:34:42 +00004936 // Handle static member functions.
4937 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4938 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004939 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004940 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004941 }
4942 }
4943
Richard Smithd62306a2011-11-10 06:34:14 +00004944 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004945 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004946}
4947
Peter Collingbournee9200682011-05-13 03:29:01 +00004948bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004949 // FIXME: Deal with vectors as array subscript bases.
4950 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004951 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004952
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004953 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004954 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004955
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004956 APSInt Index;
4957 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004958 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004959
Richard Smith861b5b52013-05-07 23:34:45 +00004960 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4961 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004962}
Eli Friedman9a156e52008-11-12 09:44:48 +00004963
Peter Collingbournee9200682011-05-13 03:29:01 +00004964bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004965 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004966}
4967
Richard Smith66c96992012-02-18 22:04:06 +00004968bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4969 if (!Visit(E->getSubExpr()))
4970 return false;
4971 // __real is a no-op on scalar lvalues.
4972 if (E->getSubExpr()->getType()->isAnyComplexType())
4973 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4974 return true;
4975}
4976
4977bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4978 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4979 "lvalue __imag__ on scalar?");
4980 if (!Visit(E->getSubExpr()))
4981 return false;
4982 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4983 return true;
4984}
4985
Richard Smith243ef902013-05-05 23:31:59 +00004986bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004987 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004988 return Error(UO);
4989
4990 if (!this->Visit(UO->getSubExpr()))
4991 return false;
4992
Richard Smith243ef902013-05-05 23:31:59 +00004993 return handleIncDec(
4994 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004995 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004996}
4997
4998bool LValueExprEvaluator::VisitCompoundAssignOperator(
4999 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005000 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005001 return Error(CAO);
5002
Richard Smith3229b742013-05-05 21:17:10 +00005003 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005004
5005 // The overall lvalue result is the result of evaluating the LHS.
5006 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005007 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005008 Evaluate(RHS, this->Info, CAO->getRHS());
5009 return false;
5010 }
5011
Richard Smith3229b742013-05-05 21:17:10 +00005012 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5013 return false;
5014
Richard Smith43e77732013-05-07 04:50:00 +00005015 return handleCompoundAssignment(
5016 this->Info, CAO,
5017 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5018 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005019}
5020
5021bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005022 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005023 return Error(E);
5024
Richard Smith3229b742013-05-05 21:17:10 +00005025 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005026
5027 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005028 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005029 Evaluate(NewVal, this->Info, E->getRHS());
5030 return false;
5031 }
5032
Richard Smith3229b742013-05-05 21:17:10 +00005033 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5034 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005035
5036 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005037 NewVal);
5038}
5039
Eli Friedman9a156e52008-11-12 09:44:48 +00005040//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005041// Pointer Evaluation
5042//===----------------------------------------------------------------------===//
5043
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005044namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005045class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005046 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005047 LValue &Result;
5048
Peter Collingbournee9200682011-05-13 03:29:01 +00005049 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005050 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005051 return true;
5052 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005053public:
Mike Stump11289f42009-09-09 15:08:12 +00005054
John McCall45d55e42010-05-07 21:00:08 +00005055 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005056 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005057
Richard Smith2e312c82012-03-03 22:46:17 +00005058 bool Success(const APValue &V, const Expr *E) {
5059 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005060 return true;
5061 }
Richard Smithfddd3842011-12-30 21:15:51 +00005062 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005063 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00005064 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005065
John McCall45d55e42010-05-07 21:00:08 +00005066 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005067 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005068 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005069 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005070 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005071 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005072 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005073 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005074 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005075 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005076 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005077 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005078 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005079 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005080 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005081 }
Richard Smithd62306a2011-11-10 06:34:14 +00005082 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005083 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005084 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005085 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005086 if (!Info.CurrentCall->This) {
5087 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005088 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005089 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005090 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005091 return false;
5092 }
Richard Smithd62306a2011-11-10 06:34:14 +00005093 Result = *Info.CurrentCall->This;
5094 return true;
5095 }
John McCallc07a0c72011-02-17 10:25:35 +00005096
Eli Friedman449fe542009-03-23 04:56:01 +00005097 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005098};
Chris Lattner05706e882008-07-11 18:11:29 +00005099} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005100
John McCall45d55e42010-05-07 21:00:08 +00005101static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005102 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005103 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005104}
5105
John McCall45d55e42010-05-07 21:00:08 +00005106bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005107 if (E->getOpcode() != BO_Add &&
5108 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005109 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005110
Chris Lattner05706e882008-07-11 18:11:29 +00005111 const Expr *PExp = E->getLHS();
5112 const Expr *IExp = E->getRHS();
5113 if (IExp->getType()->isPointerType())
5114 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005115
Richard Smith253c2a32012-01-27 01:14:48 +00005116 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005117 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005118 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005119
John McCall45d55e42010-05-07 21:00:08 +00005120 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005121 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005122 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005123
5124 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005125 if (E->getOpcode() == BO_Sub)
5126 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005127
Ted Kremenek28831752012-08-23 20:46:57 +00005128 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005129 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5130 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005131}
Eli Friedman9a156e52008-11-12 09:44:48 +00005132
John McCall45d55e42010-05-07 21:00:08 +00005133bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5134 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005135}
Mike Stump11289f42009-09-09 15:08:12 +00005136
Peter Collingbournee9200682011-05-13 03:29:01 +00005137bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5138 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005139
Eli Friedman847a2bc2009-12-27 05:43:15 +00005140 switch (E->getCastKind()) {
5141 default:
5142 break;
5143
John McCalle3027922010-08-25 11:45:40 +00005144 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005145 case CK_CPointerToObjCPointerCast:
5146 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005147 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005148 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005149 if (!Visit(SubExpr))
5150 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005151 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5152 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5153 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005154 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005155 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005156 if (SubExpr->getType()->isVoidPointerType())
5157 CCEDiag(E, diag::note_constexpr_invalid_cast)
5158 << 3 << SubExpr->getType();
5159 else
5160 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5161 }
Richard Smith96e0c102011-11-04 02:25:55 +00005162 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005163
Anders Carlsson18275092010-10-31 20:41:46 +00005164 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005165 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005166 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005167 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005168 if (!Result.Base && Result.Offset.isZero())
5169 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005170
Richard Smithd62306a2011-11-10 06:34:14 +00005171 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005172 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005173 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5174 castAs<PointerType>()->getPointeeType(),
5175 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005176
Richard Smith027bf112011-11-17 22:56:20 +00005177 case CK_BaseToDerived:
5178 if (!Visit(E->getSubExpr()))
5179 return false;
5180 if (!Result.Base && Result.Offset.isZero())
5181 return true;
5182 return HandleBaseToDerivedCast(Info, E, Result);
5183
Richard Smith0b0a0b62011-10-29 20:57:55 +00005184 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005185 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005186 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005187
John McCalle3027922010-08-25 11:45:40 +00005188 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005189 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5190
Richard Smith2e312c82012-03-03 22:46:17 +00005191 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005192 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005193 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005194
John McCall45d55e42010-05-07 21:00:08 +00005195 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005196 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5197 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005198 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005199 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005200 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005201 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005202 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005203 return true;
5204 } else {
5205 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005206 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005207 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005208 }
5209 }
John McCalle3027922010-08-25 11:45:40 +00005210 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005211 if (SubExpr->isGLValue()) {
5212 if (!EvaluateLValue(SubExpr, Result, Info))
5213 return false;
5214 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005215 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005216 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005217 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005218 return false;
5219 }
Richard Smith96e0c102011-11-04 02:25:55 +00005220 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005221 if (const ConstantArrayType *CAT
5222 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5223 Result.addArray(Info, E, CAT);
5224 else
5225 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005226 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005227
John McCalle3027922010-08-25 11:45:40 +00005228 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005229 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005230 }
5231
Richard Smith11562c52011-10-28 17:51:58 +00005232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005233}
Chris Lattner05706e882008-07-11 18:11:29 +00005234
Hal Finkel0dd05d42014-10-03 17:18:37 +00005235static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5236 // C++ [expr.alignof]p3:
5237 // When alignof is applied to a reference type, the result is the
5238 // alignment of the referenced type.
5239 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5240 T = Ref->getPointeeType();
5241
5242 // __alignof is defined to return the preferred alignment.
5243 return Info.Ctx.toCharUnitsFromBits(
5244 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5245}
5246
5247static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5248 E = E->IgnoreParens();
5249
5250 // The kinds of expressions that we have special-case logic here for
5251 // should be kept up to date with the special checks for those
5252 // expressions in Sema.
5253
5254 // alignof decl is always accepted, even if it doesn't make sense: we default
5255 // to 1 in those cases.
5256 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5257 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5258 /*RefAsPointee*/true);
5259
5260 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5261 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5262 /*RefAsPointee*/true);
5263
5264 return GetAlignOfType(Info, E->getType());
5265}
5266
Peter Collingbournee9200682011-05-13 03:29:01 +00005267bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005268 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005269 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005270
Richard Smith6328cbd2016-11-16 00:57:23 +00005271 if (unsigned BuiltinOp = E->getBuiltinCallee())
5272 return VisitBuiltinCallExpr(E, BuiltinOp);
5273
5274 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5275}
5276
5277bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5278 unsigned BuiltinOp) {
5279 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005280 case Builtin::BI__builtin_addressof:
5281 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005282 case Builtin::BI__builtin_assume_aligned: {
5283 // We need to be very careful here because: if the pointer does not have the
5284 // asserted alignment, then the behavior is undefined, and undefined
5285 // behavior is non-constant.
5286 if (!EvaluatePointer(E->getArg(0), Result, Info))
5287 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005288
Hal Finkel0dd05d42014-10-03 17:18:37 +00005289 LValue OffsetResult(Result);
5290 APSInt Alignment;
5291 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5292 return false;
5293 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5294
5295 if (E->getNumArgs() > 2) {
5296 APSInt Offset;
5297 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5298 return false;
5299
5300 int64_t AdditionalOffset = -getExtValue(Offset);
5301 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5302 }
5303
5304 // If there is a base object, then it must have the correct alignment.
5305 if (OffsetResult.Base) {
5306 CharUnits BaseAlignment;
5307 if (const ValueDecl *VD =
5308 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5309 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5310 } else {
5311 BaseAlignment =
5312 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5313 }
5314
5315 if (BaseAlignment < Align) {
5316 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005317 // FIXME: Quantities here cast to integers because the plural modifier
5318 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005319 CCEDiag(E->getArg(0),
5320 diag::note_constexpr_baa_insufficient_alignment) << 0
5321 << (int) BaseAlignment.getQuantity()
5322 << (unsigned) getExtValue(Alignment);
5323 return false;
5324 }
5325 }
5326
5327 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005328 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005329 Result.Designator.setInvalid();
5330 APSInt Offset(64, false);
5331 Offset = OffsetResult.Offset.getQuantity();
5332
5333 if (OffsetResult.Base)
5334 CCEDiag(E->getArg(0),
5335 diag::note_constexpr_baa_insufficient_alignment) << 1
5336 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5337 else
5338 CCEDiag(E->getArg(0),
5339 diag::note_constexpr_baa_value_insufficient_alignment)
5340 << Offset << (unsigned) getExtValue(Alignment);
5341
5342 return false;
5343 }
5344
5345 return true;
5346 }
Richard Smithe9507952016-11-12 01:39:56 +00005347
5348 case Builtin::BIstrchr:
5349 case Builtin::BImemchr:
5350 if (Info.getLangOpts().CPlusPlus11)
5351 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5352 << /*isConstexpr*/0 << /*isConstructor*/0
5353 << (BuiltinOp == Builtin::BIstrchr ? "'strchr'" : "'memchr'");
5354 else
5355 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5356 // Fall through.
5357 case Builtin::BI__builtin_strchr:
5358 case Builtin::BI__builtin_memchr: {
5359 if (!Visit(E->getArg(0)))
5360 return false;
5361 APSInt Desired;
5362 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5363 return false;
5364 uint64_t MaxLength = uint64_t(-1);
5365 if (BuiltinOp != Builtin::BIstrchr &&
5366 BuiltinOp != Builtin::BI__builtin_strchr) {
5367 APSInt N;
5368 if (!EvaluateInteger(E->getArg(2), N, Info))
5369 return false;
5370 MaxLength = N.getExtValue();
5371 }
5372
5373 QualType CharTy = Info.Ctx.CharTy;
5374 bool IsStrchr = (BuiltinOp != Builtin::BImemchr &&
5375 BuiltinOp != Builtin::BI__builtin_memchr);
5376
5377 // strchr compares directly to the passed integer, and therefore
5378 // always fails if given an int that is not a char.
5379 if (IsStrchr &&
5380 !APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5381 E->getArg(1)->getType(),
5382 Desired),
5383 Desired))
5384 return ZeroInitialization(E);
5385
5386 // memchr compares by converting both sides to unsigned char. That's also
5387 // correct for strchr if we get this far.
5388 uint64_t DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5389
5390 for (; MaxLength; --MaxLength) {
5391 APValue Char;
5392 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5393 !Char.isInt())
5394 return false;
5395 if (Char.getInt().getZExtValue() == DesiredVal)
5396 return true;
5397 if (IsStrchr && !Char.getInt())
5398 break;
5399 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5400 return false;
5401 }
5402 // Not found: return nullptr.
5403 return ZeroInitialization(E);
5404 }
5405
Richard Smith6cbd65d2013-07-11 02:27:57 +00005406 default:
5407 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5408 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005409}
Chris Lattner05706e882008-07-11 18:11:29 +00005410
5411//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005412// Member Pointer Evaluation
5413//===----------------------------------------------------------------------===//
5414
5415namespace {
5416class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005417 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005418 MemberPtr &Result;
5419
5420 bool Success(const ValueDecl *D) {
5421 Result = MemberPtr(D);
5422 return true;
5423 }
5424public:
5425
5426 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5427 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5428
Richard Smith2e312c82012-03-03 22:46:17 +00005429 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005430 Result.setFrom(V);
5431 return true;
5432 }
Richard Smithfddd3842011-12-30 21:15:51 +00005433 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005434 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005435 }
5436
5437 bool VisitCastExpr(const CastExpr *E);
5438 bool VisitUnaryAddrOf(const UnaryOperator *E);
5439};
5440} // end anonymous namespace
5441
5442static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5443 EvalInfo &Info) {
5444 assert(E->isRValue() && E->getType()->isMemberPointerType());
5445 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5446}
5447
5448bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5449 switch (E->getCastKind()) {
5450 default:
5451 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5452
5453 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005454 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005455 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005456
5457 case CK_BaseToDerivedMemberPointer: {
5458 if (!Visit(E->getSubExpr()))
5459 return false;
5460 if (E->path_empty())
5461 return true;
5462 // Base-to-derived member pointer casts store the path in derived-to-base
5463 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5464 // the wrong end of the derived->base arc, so stagger the path by one class.
5465 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5466 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5467 PathI != PathE; ++PathI) {
5468 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5469 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5470 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005471 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005472 }
5473 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5474 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005475 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005476 return true;
5477 }
5478
5479 case CK_DerivedToBaseMemberPointer:
5480 if (!Visit(E->getSubExpr()))
5481 return false;
5482 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5483 PathE = E->path_end(); PathI != PathE; ++PathI) {
5484 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5485 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5486 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005487 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005488 }
5489 return true;
5490 }
5491}
5492
5493bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5494 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5495 // member can be formed.
5496 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5497}
5498
5499//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005500// Record Evaluation
5501//===----------------------------------------------------------------------===//
5502
5503namespace {
5504 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005505 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005506 const LValue &This;
5507 APValue &Result;
5508 public:
5509
5510 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5511 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5512
Richard Smith2e312c82012-03-03 22:46:17 +00005513 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005514 Result = V;
5515 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005516 }
Richard Smithb8348f52016-05-12 22:16:28 +00005517 bool ZeroInitialization(const Expr *E) {
5518 return ZeroInitialization(E, E->getType());
5519 }
5520 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005521
Richard Smith52a980a2015-08-28 02:43:42 +00005522 bool VisitCallExpr(const CallExpr *E) {
5523 return handleCallExpr(E, Result, &This);
5524 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005525 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005526 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005527 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5528 return VisitCXXConstructExpr(E, E->getType());
5529 }
Richard Smith5179eb72016-06-28 19:03:57 +00005530 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005531 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005532 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005533 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005534}
Richard Smithd62306a2011-11-10 06:34:14 +00005535
Richard Smithfddd3842011-12-30 21:15:51 +00005536/// Perform zero-initialization on an object of non-union class type.
5537/// C++11 [dcl.init]p5:
5538/// To zero-initialize an object or reference of type T means:
5539/// [...]
5540/// -- if T is a (possibly cv-qualified) non-union class type,
5541/// each non-static data member and each base-class subobject is
5542/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005543static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5544 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005545 const LValue &This, APValue &Result) {
5546 assert(!RD->isUnion() && "Expected non-union class type");
5547 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5548 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005549 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005550
John McCalld7bca762012-05-01 00:38:49 +00005551 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005552 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5553
5554 if (CD) {
5555 unsigned Index = 0;
5556 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005557 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005558 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5559 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005560 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5561 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005562 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005563 Result.getStructBase(Index)))
5564 return false;
5565 }
5566 }
5567
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005568 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005569 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005570 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005571 continue;
5572
5573 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005574 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005575 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005576
David Blaikie2d7c57e2012-04-30 02:36:29 +00005577 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005578 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005579 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005580 return false;
5581 }
5582
5583 return true;
5584}
5585
Richard Smithb8348f52016-05-12 22:16:28 +00005586bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5587 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005588 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005589 if (RD->isUnion()) {
5590 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5591 // object's first non-static named data member is zero-initialized
5592 RecordDecl::field_iterator I = RD->field_begin();
5593 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005594 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005595 return true;
5596 }
5597
5598 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005599 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005600 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005601 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005602 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005603 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005604 }
5605
Richard Smith5d108602012-02-17 00:44:16 +00005606 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005607 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005608 return false;
5609 }
5610
Richard Smitha8105bc2012-01-06 16:39:00 +00005611 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005612}
5613
Richard Smithe97cbd72011-11-11 04:05:33 +00005614bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5615 switch (E->getCastKind()) {
5616 default:
5617 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5618
5619 case CK_ConstructorConversion:
5620 return Visit(E->getSubExpr());
5621
5622 case CK_DerivedToBase:
5623 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005624 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005625 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005626 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005627 if (!DerivedObject.isStruct())
5628 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005629
5630 // Derived-to-base rvalue conversion: just slice off the derived part.
5631 APValue *Value = &DerivedObject;
5632 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5633 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5634 PathE = E->path_end(); PathI != PathE; ++PathI) {
5635 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5636 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5637 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5638 RD = Base;
5639 }
5640 Result = *Value;
5641 return true;
5642 }
5643 }
5644}
5645
Richard Smithd62306a2011-11-10 06:34:14 +00005646bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5647 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005648 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005649 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5650
5651 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005652 const FieldDecl *Field = E->getInitializedFieldInUnion();
5653 Result = APValue(Field);
5654 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005655 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005656
5657 // If the initializer list for a union does not contain any elements, the
5658 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005659 // FIXME: The element should be initialized from an initializer list.
5660 // Is this difference ever observable for initializer lists which
5661 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005662 ImplicitValueInitExpr VIE(Field->getType());
5663 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5664
Richard Smithd62306a2011-11-10 06:34:14 +00005665 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005666 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5667 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005668
5669 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5670 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5671 isa<CXXDefaultInitExpr>(InitExpr));
5672
Richard Smithb228a862012-02-15 02:18:13 +00005673 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005674 }
5675
Richard Smith872307e2016-03-08 22:17:41 +00005676 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005677 if (Result.isUninit())
5678 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5679 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005680 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005681 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005682
5683 // Initialize base classes.
5684 if (CXXRD) {
5685 for (const auto &Base : CXXRD->bases()) {
5686 assert(ElementNo < E->getNumInits() && "missing init for base class");
5687 const Expr *Init = E->getInit(ElementNo);
5688
5689 LValue Subobject = This;
5690 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5691 return false;
5692
5693 APValue &FieldVal = Result.getStructBase(ElementNo);
5694 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005695 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005696 return false;
5697 Success = false;
5698 }
5699 ++ElementNo;
5700 }
5701 }
5702
5703 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005704 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005705 // Anonymous bit-fields are not considered members of the class for
5706 // purposes of aggregate initialization.
5707 if (Field->isUnnamedBitfield())
5708 continue;
5709
5710 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005711
Richard Smith253c2a32012-01-27 01:14:48 +00005712 bool HaveInit = ElementNo < E->getNumInits();
5713
5714 // FIXME: Diagnostics here should point to the end of the initializer
5715 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005716 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005717 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005718 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005719
5720 // Perform an implicit value-initialization for members beyond the end of
5721 // the initializer list.
5722 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005723 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005724
Richard Smith852c9db2013-04-20 22:23:05 +00005725 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5726 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5727 isa<CXXDefaultInitExpr>(Init));
5728
Richard Smith49ca8aa2013-08-06 07:09:20 +00005729 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5730 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5731 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005732 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005733 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005734 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005735 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005736 }
5737 }
5738
Richard Smith253c2a32012-01-27 01:14:48 +00005739 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005740}
5741
Richard Smithb8348f52016-05-12 22:16:28 +00005742bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5743 QualType T) {
5744 // Note that E's type is not necessarily the type of our class here; we might
5745 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005746 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005747 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5748
Richard Smithfddd3842011-12-30 21:15:51 +00005749 bool ZeroInit = E->requiresZeroInitialization();
5750 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005751 // If we've already performed zero-initialization, we're already done.
5752 if (!Result.isUninit())
5753 return true;
5754
Richard Smithda3f4fd2014-03-05 23:32:50 +00005755 // We can get here in two different ways:
5756 // 1) We're performing value-initialization, and should zero-initialize
5757 // the object, or
5758 // 2) We're performing default-initialization of an object with a trivial
5759 // constexpr default constructor, in which case we should start the
5760 // lifetimes of all the base subobjects (there can be no data member
5761 // subobjects in this case) per [basic.life]p1.
5762 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005763 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005764 }
5765
Craig Topper36250ad2014-05-12 05:36:57 +00005766 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005767 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005768
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005769 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005770 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005771
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005772 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005773 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005774 if (const MaterializeTemporaryExpr *ME
5775 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5776 return Visit(ME->GetTemporaryExpr());
5777
Richard Smithb8348f52016-05-12 22:16:28 +00005778 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005779 return false;
5780
Craig Topper5fc8fc22014-08-27 06:28:36 +00005781 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005782 return HandleConstructorCall(E, This, Args,
5783 cast<CXXConstructorDecl>(Definition), Info,
5784 Result);
5785}
5786
5787bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5788 const CXXInheritedCtorInitExpr *E) {
5789 if (!Info.CurrentCall) {
5790 assert(Info.checkingPotentialConstantExpression());
5791 return false;
5792 }
5793
5794 const CXXConstructorDecl *FD = E->getConstructor();
5795 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5796 return false;
5797
5798 const FunctionDecl *Definition = nullptr;
5799 auto Body = FD->getBody(Definition);
5800
5801 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5802 return false;
5803
5804 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005805 cast<CXXConstructorDecl>(Definition), Info,
5806 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005807}
5808
Richard Smithcc1b96d2013-06-12 22:31:48 +00005809bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5810 const CXXStdInitializerListExpr *E) {
5811 const ConstantArrayType *ArrayType =
5812 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5813
5814 LValue Array;
5815 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5816 return false;
5817
5818 // Get a pointer to the first element of the array.
5819 Array.addArray(Info, E, ArrayType);
5820
5821 // FIXME: Perform the checks on the field types in SemaInit.
5822 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5823 RecordDecl::field_iterator Field = Record->field_begin();
5824 if (Field == Record->field_end())
5825 return Error(E);
5826
5827 // Start pointer.
5828 if (!Field->getType()->isPointerType() ||
5829 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5830 ArrayType->getElementType()))
5831 return Error(E);
5832
5833 // FIXME: What if the initializer_list type has base classes, etc?
5834 Result = APValue(APValue::UninitStruct(), 0, 2);
5835 Array.moveInto(Result.getStructField(0));
5836
5837 if (++Field == Record->field_end())
5838 return Error(E);
5839
5840 if (Field->getType()->isPointerType() &&
5841 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5842 ArrayType->getElementType())) {
5843 // End pointer.
5844 if (!HandleLValueArrayAdjustment(Info, E, Array,
5845 ArrayType->getElementType(),
5846 ArrayType->getSize().getZExtValue()))
5847 return false;
5848 Array.moveInto(Result.getStructField(1));
5849 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5850 // Length.
5851 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5852 else
5853 return Error(E);
5854
5855 if (++Field != Record->field_end())
5856 return Error(E);
5857
5858 return true;
5859}
5860
Richard Smithd62306a2011-11-10 06:34:14 +00005861static bool EvaluateRecord(const Expr *E, const LValue &This,
5862 APValue &Result, EvalInfo &Info) {
5863 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005864 "can't evaluate expression as a record rvalue");
5865 return RecordExprEvaluator(Info, This, Result).Visit(E);
5866}
5867
5868//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005869// Temporary Evaluation
5870//
5871// Temporaries are represented in the AST as rvalues, but generally behave like
5872// lvalues. The full-object of which the temporary is a subobject is implicitly
5873// materialized so that a reference can bind to it.
5874//===----------------------------------------------------------------------===//
5875namespace {
5876class TemporaryExprEvaluator
5877 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5878public:
5879 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5880 LValueExprEvaluatorBaseTy(Info, Result) {}
5881
5882 /// Visit an expression which constructs the value of this temporary.
5883 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005884 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005885 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5886 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005887 }
5888
5889 bool VisitCastExpr(const CastExpr *E) {
5890 switch (E->getCastKind()) {
5891 default:
5892 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5893
5894 case CK_ConstructorConversion:
5895 return VisitConstructExpr(E->getSubExpr());
5896 }
5897 }
5898 bool VisitInitListExpr(const InitListExpr *E) {
5899 return VisitConstructExpr(E);
5900 }
5901 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5902 return VisitConstructExpr(E);
5903 }
5904 bool VisitCallExpr(const CallExpr *E) {
5905 return VisitConstructExpr(E);
5906 }
Richard Smith513955c2014-12-17 19:24:30 +00005907 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5908 return VisitConstructExpr(E);
5909 }
Richard Smith027bf112011-11-17 22:56:20 +00005910};
5911} // end anonymous namespace
5912
5913/// Evaluate an expression of record type as a temporary.
5914static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005915 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005916 return TemporaryExprEvaluator(Info, Result).Visit(E);
5917}
5918
5919//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005920// Vector Evaluation
5921//===----------------------------------------------------------------------===//
5922
5923namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005924 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005925 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005926 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005927 public:
Mike Stump11289f42009-09-09 15:08:12 +00005928
Richard Smith2d406342011-10-22 21:10:00 +00005929 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5930 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005931
Craig Topper9798b932015-09-29 04:30:05 +00005932 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005933 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5934 // FIXME: remove this APValue copy.
5935 Result = APValue(V.data(), V.size());
5936 return true;
5937 }
Richard Smith2e312c82012-03-03 22:46:17 +00005938 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005939 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005940 Result = V;
5941 return true;
5942 }
Richard Smithfddd3842011-12-30 21:15:51 +00005943 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005944
Richard Smith2d406342011-10-22 21:10:00 +00005945 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005946 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005947 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005948 bool VisitInitListExpr(const InitListExpr *E);
5949 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005950 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005951 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005952 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005953 };
5954} // end anonymous namespace
5955
5956static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005957 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005958 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005959}
5960
George Burgess IV533ff002015-12-11 00:23:35 +00005961bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005962 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005963 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005964
Richard Smith161f09a2011-12-06 22:44:34 +00005965 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005966 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005967
Eli Friedmanc757de22011-03-25 00:43:55 +00005968 switch (E->getCastKind()) {
5969 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005970 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005971 if (SETy->isIntegerType()) {
5972 APSInt IntResult;
5973 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005974 return false;
5975 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005976 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005977 APFloat FloatResult(0.0);
5978 if (!EvaluateFloat(SE, FloatResult, Info))
5979 return false;
5980 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005981 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005982 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005983 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005984
5985 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005986 SmallVector<APValue, 4> Elts(NElts, Val);
5987 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005988 }
Eli Friedman803acb32011-12-22 03:51:45 +00005989 case CK_BitCast: {
5990 // Evaluate the operand into an APInt we can extract from.
5991 llvm::APInt SValInt;
5992 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5993 return false;
5994 // Extract the elements
5995 QualType EltTy = VTy->getElementType();
5996 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5997 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5998 SmallVector<APValue, 4> Elts;
5999 if (EltTy->isRealFloatingType()) {
6000 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006001 unsigned FloatEltSize = EltSize;
6002 if (&Sem == &APFloat::x87DoubleExtended)
6003 FloatEltSize = 80;
6004 for (unsigned i = 0; i < NElts; i++) {
6005 llvm::APInt Elt;
6006 if (BigEndian)
6007 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6008 else
6009 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006010 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006011 }
6012 } else if (EltTy->isIntegerType()) {
6013 for (unsigned i = 0; i < NElts; i++) {
6014 llvm::APInt Elt;
6015 if (BigEndian)
6016 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6017 else
6018 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6019 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6020 }
6021 } else {
6022 return Error(E);
6023 }
6024 return Success(Elts, E);
6025 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006026 default:
Richard Smith11562c52011-10-28 17:51:58 +00006027 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006028 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006029}
6030
Richard Smith2d406342011-10-22 21:10:00 +00006031bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006032VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006033 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006034 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006035 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006036
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006037 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006038 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006039
Eli Friedmanb9c71292012-01-03 23:24:20 +00006040 // The number of initializers can be less than the number of
6041 // vector elements. For OpenCL, this can be due to nested vector
6042 // initialization. For GCC compatibility, missing trailing elements
6043 // should be initialized with zeroes.
6044 unsigned CountInits = 0, CountElts = 0;
6045 while (CountElts < NumElements) {
6046 // Handle nested vector initialization.
6047 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006048 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006049 APValue v;
6050 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6051 return Error(E);
6052 unsigned vlen = v.getVectorLength();
6053 for (unsigned j = 0; j < vlen; j++)
6054 Elements.push_back(v.getVectorElt(j));
6055 CountElts += vlen;
6056 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006057 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006058 if (CountInits < NumInits) {
6059 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006060 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006061 } else // trailing integer zero.
6062 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6063 Elements.push_back(APValue(sInt));
6064 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006065 } else {
6066 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006067 if (CountInits < NumInits) {
6068 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006069 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006070 } else // trailing float zero.
6071 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6072 Elements.push_back(APValue(f));
6073 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006074 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006075 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006076 }
Richard Smith2d406342011-10-22 21:10:00 +00006077 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006078}
6079
Richard Smith2d406342011-10-22 21:10:00 +00006080bool
Richard Smithfddd3842011-12-30 21:15:51 +00006081VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006082 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006083 QualType EltTy = VT->getElementType();
6084 APValue ZeroElement;
6085 if (EltTy->isIntegerType())
6086 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6087 else
6088 ZeroElement =
6089 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6090
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006091 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006092 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006093}
6094
Richard Smith2d406342011-10-22 21:10:00 +00006095bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006096 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006097 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006098}
6099
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006100//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006101// Array Evaluation
6102//===----------------------------------------------------------------------===//
6103
6104namespace {
6105 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006106 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006107 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006108 APValue &Result;
6109 public:
6110
Richard Smithd62306a2011-11-10 06:34:14 +00006111 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6112 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006113
6114 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006115 assert((V.isArray() || V.isLValue()) &&
6116 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006117 Result = V;
6118 return true;
6119 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006120
Richard Smithfddd3842011-12-30 21:15:51 +00006121 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006122 const ConstantArrayType *CAT =
6123 Info.Ctx.getAsConstantArrayType(E->getType());
6124 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006125 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006126
6127 Result = APValue(APValue::UninitArray(), 0,
6128 CAT->getSize().getZExtValue());
6129 if (!Result.hasArrayFiller()) return true;
6130
Richard Smithfddd3842011-12-30 21:15:51 +00006131 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006132 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006133 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006134 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006135 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006136 }
6137
Richard Smith52a980a2015-08-28 02:43:42 +00006138 bool VisitCallExpr(const CallExpr *E) {
6139 return handleCallExpr(E, Result, &This);
6140 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006141 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006142 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006143 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6144 const LValue &Subobject,
6145 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006146 };
6147} // end anonymous namespace
6148
Richard Smithd62306a2011-11-10 06:34:14 +00006149static bool EvaluateArray(const Expr *E, const LValue &This,
6150 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006151 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006152 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006153}
6154
6155bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6156 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6157 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006158 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006159
Richard Smithca2cfbf2011-12-22 01:07:19 +00006160 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6161 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006162 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006163 LValue LV;
6164 if (!EvaluateLValue(E->getInit(0), LV, Info))
6165 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006166 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006167 LV.moveInto(Val);
6168 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006169 }
6170
Richard Smith253c2a32012-01-27 01:14:48 +00006171 bool Success = true;
6172
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006173 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6174 "zero-initialized array shouldn't have any initialized elts");
6175 APValue Filler;
6176 if (Result.isArray() && Result.hasArrayFiller())
6177 Filler = Result.getArrayFiller();
6178
Richard Smith9543c5e2013-04-22 14:44:29 +00006179 unsigned NumEltsToInit = E->getNumInits();
6180 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006181 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006182
6183 // If the initializer might depend on the array index, run it for each
6184 // array element. For now, just whitelist non-class value-initialization.
6185 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6186 NumEltsToInit = NumElts;
6187
6188 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006189
6190 // If the array was previously zero-initialized, preserve the
6191 // zero-initialized values.
6192 if (!Filler.isUninit()) {
6193 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6194 Result.getArrayInitializedElt(I) = Filler;
6195 if (Result.hasArrayFiller())
6196 Result.getArrayFiller() = Filler;
6197 }
6198
Richard Smithd62306a2011-11-10 06:34:14 +00006199 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006200 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006201 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6202 const Expr *Init =
6203 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006204 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006205 Info, Subobject, Init) ||
6206 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006207 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006208 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006209 return false;
6210 Success = false;
6211 }
Richard Smithd62306a2011-11-10 06:34:14 +00006212 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006213
Richard Smith9543c5e2013-04-22 14:44:29 +00006214 if (!Result.hasArrayFiller())
6215 return Success;
6216
6217 // If we get here, we have a trivial filler, which we can just evaluate
6218 // once and splat over the rest of the array elements.
6219 assert(FillerExpr && "no array filler for incomplete init list");
6220 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6221 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006222}
6223
Richard Smith027bf112011-11-17 22:56:20 +00006224bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006225 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6226}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006227
Richard Smith9543c5e2013-04-22 14:44:29 +00006228bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6229 const LValue &Subobject,
6230 APValue *Value,
6231 QualType Type) {
6232 bool HadZeroInit = !Value->isUninit();
6233
6234 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6235 unsigned N = CAT->getSize().getZExtValue();
6236
6237 // Preserve the array filler if we had prior zero-initialization.
6238 APValue Filler =
6239 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6240 : APValue();
6241
6242 *Value = APValue(APValue::UninitArray(), N, N);
6243
6244 if (HadZeroInit)
6245 for (unsigned I = 0; I != N; ++I)
6246 Value->getArrayInitializedElt(I) = Filler;
6247
6248 // Initialize the elements.
6249 LValue ArrayElt = Subobject;
6250 ArrayElt.addArray(Info, E, CAT);
6251 for (unsigned I = 0; I != N; ++I)
6252 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6253 CAT->getElementType()) ||
6254 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6255 CAT->getElementType(), 1))
6256 return false;
6257
6258 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006259 }
Richard Smith027bf112011-11-17 22:56:20 +00006260
Richard Smith9543c5e2013-04-22 14:44:29 +00006261 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006262 return Error(E);
6263
Richard Smithb8348f52016-05-12 22:16:28 +00006264 return RecordExprEvaluator(Info, Subobject, *Value)
6265 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006266}
6267
Richard Smithf3e9e432011-11-07 09:22:26 +00006268//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006269// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006270//
6271// As a GNU extension, we support casting pointers to sufficiently-wide integer
6272// types and back in constant folding. Integer values are thus represented
6273// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006274//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006275
6276namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006277class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006278 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006279 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006280public:
Richard Smith2e312c82012-03-03 22:46:17 +00006281 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006282 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006283
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006284 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006285 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006286 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006287 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006288 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006289 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006290 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006291 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006292 return true;
6293 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006294 bool Success(const llvm::APSInt &SI, const Expr *E) {
6295 return Success(SI, E, Result);
6296 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006297
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006298 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006299 assert(E->getType()->isIntegralOrEnumerationType() &&
6300 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006301 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006302 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006303 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006304 Result.getInt().setIsUnsigned(
6305 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006306 return true;
6307 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006308 bool Success(const llvm::APInt &I, const Expr *E) {
6309 return Success(I, E, Result);
6310 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006311
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006312 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006313 assert(E->getType()->isIntegralOrEnumerationType() &&
6314 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006315 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006316 return true;
6317 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006318 bool Success(uint64_t Value, const Expr *E) {
6319 return Success(Value, E, Result);
6320 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006321
Ken Dyckdbc01912011-03-11 02:13:43 +00006322 bool Success(CharUnits Size, const Expr *E) {
6323 return Success(Size.getQuantity(), E);
6324 }
6325
Richard Smith2e312c82012-03-03 22:46:17 +00006326 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006327 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006328 Result = V;
6329 return true;
6330 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006331 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006332 }
Mike Stump11289f42009-09-09 15:08:12 +00006333
Richard Smithfddd3842011-12-30 21:15:51 +00006334 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006335
Peter Collingbournee9200682011-05-13 03:29:01 +00006336 //===--------------------------------------------------------------------===//
6337 // Visitor Methods
6338 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006339
Chris Lattner7174bf32008-07-12 00:38:25 +00006340 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006341 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006342 }
6343 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006344 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006345 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006346
6347 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6348 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006349 if (CheckReferencedDecl(E, E->getDecl()))
6350 return true;
6351
6352 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006353 }
6354 bool VisitMemberExpr(const MemberExpr *E) {
6355 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006356 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006357 return true;
6358 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006359
6360 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006361 }
6362
Peter Collingbournee9200682011-05-13 03:29:01 +00006363 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006364 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006365 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006366 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006367 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006368
Peter Collingbournee9200682011-05-13 03:29:01 +00006369 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006370 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006371
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006372 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006373 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006374 }
Mike Stump11289f42009-09-09 15:08:12 +00006375
Ted Kremeneke65b0862012-03-06 20:05:56 +00006376 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6377 return Success(E->getValue(), E);
6378 }
6379
Richard Smith4ce706a2011-10-11 21:43:33 +00006380 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006381 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006382 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006383 }
6384
Douglas Gregor29c42f22012-02-24 07:38:34 +00006385 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6386 return Success(E->getValue(), E);
6387 }
6388
John Wiegley6242b6a2011-04-28 00:16:57 +00006389 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6390 return Success(E->getValue(), E);
6391 }
6392
John Wiegleyf9f65842011-04-25 06:54:41 +00006393 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6394 return Success(E->getValue(), E);
6395 }
6396
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006397 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006398 bool VisitUnaryImag(const UnaryOperator *E);
6399
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006400 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006401 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006402
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006403private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006404 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006405 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006406};
Chris Lattner05706e882008-07-11 18:11:29 +00006407} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006408
Richard Smith11562c52011-10-28 17:51:58 +00006409/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6410/// produce either the integer value or a pointer.
6411///
6412/// GCC has a heinous extension which folds casts between pointer types and
6413/// pointer-sized integral types. We support this by allowing the evaluation of
6414/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6415/// Some simple arithmetic on such values is supported (they are treated much
6416/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006417static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006418 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006419 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006420 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006421}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006422
Richard Smithf57d8cb2011-12-09 22:58:01 +00006423static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006424 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006425 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006426 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006427 if (!Val.isInt()) {
6428 // FIXME: It would be better to produce the diagnostic for casting
6429 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006430 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006431 return false;
6432 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006433 Result = Val.getInt();
6434 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006435}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006436
Richard Smithf57d8cb2011-12-09 22:58:01 +00006437/// Check whether the given declaration can be directly converted to an integral
6438/// rvalue. If not, no diagnostic is produced; there are other things we can
6439/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006440bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006441 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006442 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006443 // Check for signedness/width mismatches between E type and ECD value.
6444 bool SameSign = (ECD->getInitVal().isSigned()
6445 == E->getType()->isSignedIntegerOrEnumerationType());
6446 bool SameWidth = (ECD->getInitVal().getBitWidth()
6447 == Info.Ctx.getIntWidth(E->getType()));
6448 if (SameSign && SameWidth)
6449 return Success(ECD->getInitVal(), E);
6450 else {
6451 // Get rid of mismatch (otherwise Success assertions will fail)
6452 // by computing a new value matching the type of E.
6453 llvm::APSInt Val = ECD->getInitVal();
6454 if (!SameSign)
6455 Val.setIsSigned(!ECD->getInitVal().isSigned());
6456 if (!SameWidth)
6457 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6458 return Success(Val, E);
6459 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006460 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006461 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006462}
6463
Chris Lattner86ee2862008-10-06 06:40:35 +00006464/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6465/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006466static int EvaluateBuiltinClassifyType(const CallExpr *E,
6467 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006468 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006469 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006470 enum gcc_type_class {
6471 no_type_class = -1,
6472 void_type_class, integer_type_class, char_type_class,
6473 enumeral_type_class, boolean_type_class,
6474 pointer_type_class, reference_type_class, offset_type_class,
6475 real_type_class, complex_type_class,
6476 function_type_class, method_type_class,
6477 record_type_class, union_type_class,
6478 array_type_class, string_type_class,
6479 lang_type_class
6480 };
Mike Stump11289f42009-09-09 15:08:12 +00006481
6482 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006483 // ideal, however it is what gcc does.
6484 if (E->getNumArgs() == 0)
6485 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006486
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006487 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6488 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6489
6490 switch (CanTy->getTypeClass()) {
6491#define TYPE(ID, BASE)
6492#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6493#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6494#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6495#include "clang/AST/TypeNodes.def"
6496 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6497
6498 case Type::Builtin:
6499 switch (BT->getKind()) {
6500#define BUILTIN_TYPE(ID, SINGLETON_ID)
6501#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6502#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6503#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6504#include "clang/AST/BuiltinTypes.def"
6505 case BuiltinType::Void:
6506 return void_type_class;
6507
6508 case BuiltinType::Bool:
6509 return boolean_type_class;
6510
6511 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6512 case BuiltinType::UChar:
6513 case BuiltinType::UShort:
6514 case BuiltinType::UInt:
6515 case BuiltinType::ULong:
6516 case BuiltinType::ULongLong:
6517 case BuiltinType::UInt128:
6518 return integer_type_class;
6519
6520 case BuiltinType::NullPtr:
6521 return pointer_type_class;
6522
6523 case BuiltinType::WChar_U:
6524 case BuiltinType::Char16:
6525 case BuiltinType::Char32:
6526 case BuiltinType::ObjCId:
6527 case BuiltinType::ObjCClass:
6528 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006529#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6530 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006531#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006532 case BuiltinType::OCLSampler:
6533 case BuiltinType::OCLEvent:
6534 case BuiltinType::OCLClkEvent:
6535 case BuiltinType::OCLQueue:
6536 case BuiltinType::OCLNDRange:
6537 case BuiltinType::OCLReserveID:
6538 case BuiltinType::Dependent:
6539 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6540 };
6541
6542 case Type::Enum:
6543 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6544 break;
6545
6546 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006547 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006548 break;
6549
6550 case Type::MemberPointer:
6551 if (CanTy->isMemberDataPointerType())
6552 return offset_type_class;
6553 else {
6554 // We expect member pointers to be either data or function pointers,
6555 // nothing else.
6556 assert(CanTy->isMemberFunctionPointerType());
6557 return method_type_class;
6558 }
6559
6560 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006561 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006562
6563 case Type::FunctionNoProto:
6564 case Type::FunctionProto:
6565 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6566
6567 case Type::Record:
6568 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6569 switch (RT->getDecl()->getTagKind()) {
6570 case TagTypeKind::TTK_Struct:
6571 case TagTypeKind::TTK_Class:
6572 case TagTypeKind::TTK_Interface:
6573 return record_type_class;
6574
6575 case TagTypeKind::TTK_Enum:
6576 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6577
6578 case TagTypeKind::TTK_Union:
6579 return union_type_class;
6580 }
6581 }
David Blaikie83d382b2011-09-23 05:06:16 +00006582 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006583
6584 case Type::ConstantArray:
6585 case Type::VariableArray:
6586 case Type::IncompleteArray:
6587 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6588
6589 case Type::BlockPointer:
6590 case Type::LValueReference:
6591 case Type::RValueReference:
6592 case Type::Vector:
6593 case Type::ExtVector:
6594 case Type::Auto:
6595 case Type::ObjCObject:
6596 case Type::ObjCInterface:
6597 case Type::ObjCObjectPointer:
6598 case Type::Pipe:
6599 case Type::Atomic:
6600 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6601 }
6602
6603 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006604}
6605
Richard Smith5fab0c92011-12-28 19:48:30 +00006606/// EvaluateBuiltinConstantPForLValue - Determine the result of
6607/// __builtin_constant_p when applied to the given lvalue.
6608///
6609/// An lvalue is only "constant" if it is a pointer or reference to the first
6610/// character of a string literal.
6611template<typename LValue>
6612static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006613 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006614 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6615}
6616
6617/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6618/// GCC as we can manage.
6619static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6620 QualType ArgType = Arg->getType();
6621
6622 // __builtin_constant_p always has one operand. The rules which gcc follows
6623 // are not precisely documented, but are as follows:
6624 //
6625 // - If the operand is of integral, floating, complex or enumeration type,
6626 // and can be folded to a known value of that type, it returns 1.
6627 // - If the operand and can be folded to a pointer to the first character
6628 // of a string literal (or such a pointer cast to an integral type), it
6629 // returns 1.
6630 //
6631 // Otherwise, it returns 0.
6632 //
6633 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6634 // its support for this does not currently work.
6635 if (ArgType->isIntegralOrEnumerationType()) {
6636 Expr::EvalResult Result;
6637 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6638 return false;
6639
6640 APValue &V = Result.Val;
6641 if (V.getKind() == APValue::Int)
6642 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006643 if (V.getKind() == APValue::LValue)
6644 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006645 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6646 return Arg->isEvaluatable(Ctx);
6647 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6648 LValue LV;
6649 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006650 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006651 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6652 : EvaluatePointer(Arg, LV, Info)) &&
6653 !Status.HasSideEffects)
6654 return EvaluateBuiltinConstantPForLValue(LV);
6655 }
6656
6657 // Anything else isn't considered to be sufficiently constant.
6658 return false;
6659}
6660
John McCall95007602010-05-10 23:27:23 +00006661/// Retrieves the "underlying object type" of the given expression,
6662/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006663static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006664 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6665 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006666 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006667 } else if (const Expr *E = B.get<const Expr*>()) {
6668 if (isa<CompoundLiteralExpr>(E))
6669 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006670 }
6671
6672 return QualType();
6673}
6674
George Burgess IV3a03fab2015-09-04 21:28:13 +00006675/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006676/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6677/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006678/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6679///
6680/// Always returns an RValue with a pointer representation.
6681static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6682 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6683
6684 auto *NoParens = E->IgnoreParens();
6685 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006686 if (Cast == nullptr)
6687 return NoParens;
6688
6689 // We only conservatively allow a few kinds of casts, because this code is
6690 // inherently a simple solution that seeks to support the common case.
6691 auto CastKind = Cast->getCastKind();
6692 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6693 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006694 return NoParens;
6695
6696 auto *SubExpr = Cast->getSubExpr();
6697 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6698 return NoParens;
6699 return ignorePointerCastsAndParens(SubExpr);
6700}
6701
George Burgess IVa51c4072015-10-16 01:49:01 +00006702/// Checks to see if the given LValue's Designator is at the end of the LValue's
6703/// record layout. e.g.
6704/// struct { struct { int a, b; } fst, snd; } obj;
6705/// obj.fst // no
6706/// obj.snd // yes
6707/// obj.fst.a // no
6708/// obj.fst.b // no
6709/// obj.snd.a // no
6710/// obj.snd.b // yes
6711///
6712/// Please note: this function is specialized for how __builtin_object_size
6713/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006714///
6715/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006716static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6717 assert(!LVal.Designator.Invalid);
6718
George Burgess IV4168d752016-06-27 19:40:41 +00006719 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6720 const RecordDecl *Parent = FD->getParent();
6721 Invalid = Parent->isInvalidDecl();
6722 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006723 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006724 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006725 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6726 };
6727
6728 auto &Base = LVal.getLValueBase();
6729 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6730 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006731 bool Invalid;
6732 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6733 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006734 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006735 for (auto *FD : IFD->chain()) {
6736 bool Invalid;
6737 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6738 return Invalid;
6739 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006740 }
6741 }
6742
6743 QualType BaseType = getType(Base);
6744 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6745 if (BaseType->isArrayType()) {
6746 // Because __builtin_object_size treats arrays as objects, we can ignore
6747 // the index iff this is the last array in the Designator.
6748 if (I + 1 == E)
6749 return true;
6750 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6751 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6752 if (Index + 1 != CAT->getSize())
6753 return false;
6754 BaseType = CAT->getElementType();
6755 } else if (BaseType->isAnyComplexType()) {
6756 auto *CT = BaseType->castAs<ComplexType>();
6757 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6758 if (Index != 1)
6759 return false;
6760 BaseType = CT->getElementType();
6761 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006762 bool Invalid;
6763 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6764 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006765 BaseType = FD->getType();
6766 } else {
6767 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6768 "Expecting cast to a base class");
6769 return false;
6770 }
6771 }
6772 return true;
6773}
6774
6775/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6776static bool refersToCompleteObject(const LValue &LVal) {
6777 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6778 return false;
6779
6780 if (!LVal.InvalidBase)
6781 return true;
6782
6783 auto *E = LVal.Base.dyn_cast<const Expr *>();
6784 (void)E;
6785 assert(E != nullptr && isa<MemberExpr>(E));
6786 return false;
6787}
6788
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006789/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6790/// true and stores the result in @p Size.
6791///
6792/// If @p WasError is non-null, this will report whether the failure to evaluate
6793/// is to be treated as an Error in IntExprEvaluator.
6794static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6795 EvalInfo &Info, uint64_t &Size,
6796 bool *WasError = nullptr) {
6797 if (WasError != nullptr)
6798 *WasError = false;
6799
6800 auto Error = [&](const Expr *E) {
6801 if (WasError != nullptr)
6802 *WasError = true;
6803 return false;
6804 };
6805
6806 auto Success = [&](uint64_t S, const Expr *E) {
6807 Size = S;
6808 return true;
6809 };
6810
George Burgess IVbdb5b262015-08-19 02:19:07 +00006811 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006812 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006813 {
6814 // The operand of __builtin_object_size is never evaluated for side-effects.
6815 // If there are any, but we can determine the pointed-to object anyway, then
6816 // ignore the side-effects.
6817 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006818 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006819
6820 if (E->isGLValue()) {
6821 // It's possible for us to be given GLValues if we're called via
6822 // Expr::tryEvaluateObjectSize.
6823 APValue RVal;
6824 if (!EvaluateAsRValue(Info, E, RVal))
6825 return false;
6826 Base.setFrom(Info.Ctx, RVal);
6827 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006828 return false;
6829 }
John McCall95007602010-05-10 23:27:23 +00006830
George Burgess IVbdb5b262015-08-19 02:19:07 +00006831 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006832 // If we point to before the start of the object, there are no accessible
6833 // bytes.
6834 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006835 return Success(0, E);
6836
George Burgess IV3a03fab2015-09-04 21:28:13 +00006837 // In the case where we're not dealing with a subobject, we discard the
6838 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006839 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006840
6841 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6842 // exist. If we can't verify the base, then we can't do that.
6843 //
6844 // As a special case, we produce a valid object size for an unknown object
6845 // with a known designator if Type & 1 is 1. For instance:
6846 //
6847 // extern struct X { char buff[32]; int a, b, c; } *p;
6848 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6849 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6850 //
6851 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006852 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006853 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006854
George Burgess IVa51c4072015-10-16 01:49:01 +00006855 // If we're not examining only the subobject, then we reset to a complete
6856 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006857 //
6858 // If Type is 1 and we've lost track of the subobject, just find the complete
6859 // object instead. (If Type is 3, that's not correct behavior and we should
6860 // return 0 instead.)
6861 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006862 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006863 QualType T = getObjectType(End.getLValueBase());
6864 if (T.isNull())
6865 End.Designator.setInvalid();
6866 else {
6867 End.Designator = SubobjectDesignator(T);
6868 End.Offset = CharUnits::Zero();
6869 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006870 }
John McCall95007602010-05-10 23:27:23 +00006871
George Burgess IVbdb5b262015-08-19 02:19:07 +00006872 // If it is not possible to determine which objects ptr points to at compile
6873 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6874 // and (size_t) 0 for type 2 or 3.
6875 if (End.Designator.Invalid)
6876 return false;
6877
6878 // According to the GCC documentation, we want the size of the subobject
6879 // denoted by the pointer. But that's not quite right -- what we actually
6880 // want is the size of the immediately-enclosing array, if there is one.
6881 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006882 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006883 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6884 // We got a pointer to an array. Step to its end.
6885 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006886 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006887 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006888 // We're already pointing at the end of the object.
6889 AmountToAdd = 0;
6890 }
6891
George Burgess IV3a03fab2015-09-04 21:28:13 +00006892 QualType PointeeType = End.Designator.MostDerivedType;
6893 assert(!PointeeType.isNull());
6894 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006895 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006896
George Burgess IVbdb5b262015-08-19 02:19:07 +00006897 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6898 AmountToAdd))
6899 return false;
John McCall95007602010-05-10 23:27:23 +00006900
George Burgess IVbdb5b262015-08-19 02:19:07 +00006901 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006902
6903 // The following is a moderately common idiom in C:
6904 //
6905 // struct Foo { int a; char c[1]; };
6906 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6907 // strcpy(&F->c[0], Bar);
6908 //
George Burgess IVf8f63242016-09-12 23:50:35 +00006909 // So, if we see that we're examining an array at the end of a struct with an
6910 // unknown base, we give up instead of breaking code that behaves this way.
6911 // Note that we only do this when Type=1, because Type=3 is a lower bound, so
6912 // answering conservatively is fine.
6913 //
6914 // We used to be a bit more aggressive here; we'd only be conservative if the
6915 // array at the end was flexible, or if it had 0 or 1 elements. This broke
6916 // some common standard library extensions (PR30346), but was otherwise
6917 // seemingly fine. It may be useful to reintroduce this behavior with some
6918 // sort of whitelist. OTOH, it seems that GCC is always conservative with the
6919 // last element in structs (if it's an array), so our current behavior is more
6920 // compatible than a whitelisting approach would be.
George Burgess IVa51c4072015-10-16 01:49:01 +00006921 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6922 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6923 End.Designator.MostDerivedIsArrayElement &&
George Burgess IVa51c4072015-10-16 01:49:01 +00006924 isDesignatorAtObjectEnd(Info.Ctx, End))
6925 return false;
6926
George Burgess IVbdb5b262015-08-19 02:19:07 +00006927 if (BaseOffset > EndOffset)
6928 return Success(0, E);
6929
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006930 return Success((EndOffset - BaseOffset).getQuantity(), E);
6931}
6932
6933bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6934 unsigned Type) {
6935 uint64_t Size;
6936 bool WasError;
6937 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6938 return Success(Size, E);
6939 if (WasError)
6940 return Error(E);
6941 return false;
John McCall95007602010-05-10 23:27:23 +00006942}
6943
Peter Collingbournee9200682011-05-13 03:29:01 +00006944bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00006945 if (unsigned BuiltinOp = E->getBuiltinCallee())
6946 return VisitBuiltinCallExpr(E, BuiltinOp);
6947
6948 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6949}
6950
6951bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6952 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00006953 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006954 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006955 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006956
6957 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006958 // The type was checked when we built the expression.
6959 unsigned Type =
6960 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6961 assert(Type <= 3 && "unexpected type");
6962
6963 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006964 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006965
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006966 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006967 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006968
Richard Smith01ade172012-05-23 04:13:20 +00006969 // Expression had no side effects, but we couldn't statically determine the
6970 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006971 switch (Info.EvalMode) {
6972 case EvalInfo::EM_ConstantExpression:
6973 case EvalInfo::EM_PotentialConstantExpression:
6974 case EvalInfo::EM_ConstantFold:
6975 case EvalInfo::EM_EvaluateForOverflow:
6976 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006977 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006978 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006979 return Error(E);
6980 case EvalInfo::EM_ConstantExpressionUnevaluated:
6981 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006982 // Reduce it to a constant now.
6983 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006984 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00006985
6986 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00006987 }
6988
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006989 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006990 case Builtin::BI__builtin_bswap32:
6991 case Builtin::BI__builtin_bswap64: {
6992 APSInt Val;
6993 if (!EvaluateInteger(E->getArg(0), Val, Info))
6994 return false;
6995
6996 return Success(Val.byteSwap(), E);
6997 }
6998
Richard Smith8889a3d2013-06-13 06:26:32 +00006999 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007000 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007001
7002 // FIXME: BI__builtin_clrsb
7003 // FIXME: BI__builtin_clrsbl
7004 // FIXME: BI__builtin_clrsbll
7005
Richard Smith80b3c8e2013-06-13 05:04:16 +00007006 case Builtin::BI__builtin_clz:
7007 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007008 case Builtin::BI__builtin_clzll:
7009 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007010 APSInt Val;
7011 if (!EvaluateInteger(E->getArg(0), Val, Info))
7012 return false;
7013 if (!Val)
7014 return Error(E);
7015
7016 return Success(Val.countLeadingZeros(), E);
7017 }
7018
Richard Smith8889a3d2013-06-13 06:26:32 +00007019 case Builtin::BI__builtin_constant_p:
7020 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7021
Richard Smith80b3c8e2013-06-13 05:04:16 +00007022 case Builtin::BI__builtin_ctz:
7023 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007024 case Builtin::BI__builtin_ctzll:
7025 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007026 APSInt Val;
7027 if (!EvaluateInteger(E->getArg(0), Val, Info))
7028 return false;
7029 if (!Val)
7030 return Error(E);
7031
7032 return Success(Val.countTrailingZeros(), E);
7033 }
7034
Richard Smith8889a3d2013-06-13 06:26:32 +00007035 case Builtin::BI__builtin_eh_return_data_regno: {
7036 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7037 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7038 return Success(Operand, E);
7039 }
7040
7041 case Builtin::BI__builtin_expect:
7042 return Visit(E->getArg(0));
7043
7044 case Builtin::BI__builtin_ffs:
7045 case Builtin::BI__builtin_ffsl:
7046 case Builtin::BI__builtin_ffsll: {
7047 APSInt Val;
7048 if (!EvaluateInteger(E->getArg(0), Val, Info))
7049 return false;
7050
7051 unsigned N = Val.countTrailingZeros();
7052 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7053 }
7054
7055 case Builtin::BI__builtin_fpclassify: {
7056 APFloat Val(0.0);
7057 if (!EvaluateFloat(E->getArg(5), Val, Info))
7058 return false;
7059 unsigned Arg;
7060 switch (Val.getCategory()) {
7061 case APFloat::fcNaN: Arg = 0; break;
7062 case APFloat::fcInfinity: Arg = 1; break;
7063 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7064 case APFloat::fcZero: Arg = 4; break;
7065 }
7066 return Visit(E->getArg(Arg));
7067 }
7068
7069 case Builtin::BI__builtin_isinf_sign: {
7070 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007071 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007072 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7073 }
7074
Richard Smithea3019d2013-10-15 19:07:14 +00007075 case Builtin::BI__builtin_isinf: {
7076 APFloat Val(0.0);
7077 return EvaluateFloat(E->getArg(0), Val, Info) &&
7078 Success(Val.isInfinity() ? 1 : 0, E);
7079 }
7080
7081 case Builtin::BI__builtin_isfinite: {
7082 APFloat Val(0.0);
7083 return EvaluateFloat(E->getArg(0), Val, Info) &&
7084 Success(Val.isFinite() ? 1 : 0, E);
7085 }
7086
7087 case Builtin::BI__builtin_isnan: {
7088 APFloat Val(0.0);
7089 return EvaluateFloat(E->getArg(0), Val, Info) &&
7090 Success(Val.isNaN() ? 1 : 0, E);
7091 }
7092
7093 case Builtin::BI__builtin_isnormal: {
7094 APFloat Val(0.0);
7095 return EvaluateFloat(E->getArg(0), Val, Info) &&
7096 Success(Val.isNormal() ? 1 : 0, E);
7097 }
7098
Richard Smith8889a3d2013-06-13 06:26:32 +00007099 case Builtin::BI__builtin_parity:
7100 case Builtin::BI__builtin_parityl:
7101 case Builtin::BI__builtin_parityll: {
7102 APSInt Val;
7103 if (!EvaluateInteger(E->getArg(0), Val, Info))
7104 return false;
7105
7106 return Success(Val.countPopulation() % 2, E);
7107 }
7108
Richard Smith80b3c8e2013-06-13 05:04:16 +00007109 case Builtin::BI__builtin_popcount:
7110 case Builtin::BI__builtin_popcountl:
7111 case Builtin::BI__builtin_popcountll: {
7112 APSInt Val;
7113 if (!EvaluateInteger(E->getArg(0), Val, Info))
7114 return false;
7115
7116 return Success(Val.countPopulation(), E);
7117 }
7118
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007119 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007120 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007121 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007122 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00007123 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
7124 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007125 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007126 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00007127 case Builtin::BI__builtin_strlen: {
7128 // As an extension, we support __builtin_strlen() as a constant expression,
7129 // and support folding strlen() to a constant.
7130 LValue String;
7131 if (!EvaluatePointer(E->getArg(0), String, Info))
7132 return false;
7133
7134 // Fast path: if it's a string literal, search the string value.
7135 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7136 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007137 // The string literal may have embedded null characters. Find the first
7138 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007139 StringRef Str = S->getBytes();
7140 int64_t Off = String.Offset.getQuantity();
7141 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7142 S->getCharByteWidth() == 1) {
7143 Str = Str.substr(Off);
7144
7145 StringRef::size_type Pos = Str.find(0);
7146 if (Pos != StringRef::npos)
7147 Str = Str.substr(0, Pos);
7148
7149 return Success(Str.size(), E);
7150 }
7151
7152 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007153 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007154
7155 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe9507952016-11-12 01:39:56 +00007156 QualType CharTy = Info.Ctx.CharTy;
Richard Smithe6c19f22013-11-15 02:10:04 +00007157 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7158 APValue Char;
7159 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7160 !Char.isInt())
7161 return false;
7162 if (!Char.getInt())
7163 return Success(Strlen, E);
7164 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7165 return false;
7166 }
7167 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007168
Richard Smithe151bab2016-11-11 23:43:35 +00007169 case Builtin::BIstrcmp:
7170 case Builtin::BIstrncmp:
7171 case Builtin::BImemcmp:
7172 // A call to strlen is not a constant expression.
7173 if (Info.getLangOpts().CPlusPlus11)
7174 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7175 << /*isConstexpr*/0 << /*isConstructor*/0
7176 << (BuiltinOp == Builtin::BIstrncmp ? "'strncmp'" :
7177 BuiltinOp == Builtin::BImemcmp ? "'memcmp'" :
7178 "'strcmp'");
7179 else
7180 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7181 // Fall through.
7182 case Builtin::BI__builtin_strcmp:
7183 case Builtin::BI__builtin_strncmp:
7184 case Builtin::BI__builtin_memcmp: {
7185 LValue String1, String2;
7186 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7187 !EvaluatePointer(E->getArg(1), String2, Info))
7188 return false;
7189 uint64_t MaxLength = uint64_t(-1);
7190 if (BuiltinOp != Builtin::BIstrcmp &&
7191 BuiltinOp != Builtin::BI__builtin_strcmp) {
7192 APSInt N;
7193 if (!EvaluateInteger(E->getArg(2), N, Info))
7194 return false;
7195 MaxLength = N.getExtValue();
7196 }
7197 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7198 BuiltinOp != Builtin::BI__builtin_memcmp);
Richard Smithe9507952016-11-12 01:39:56 +00007199 QualType CharTy = Info.Ctx.CharTy;
Richard Smithe151bab2016-11-11 23:43:35 +00007200 for (; MaxLength; --MaxLength) {
7201 APValue Char1, Char2;
7202 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7203 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7204 !Char1.isInt() || !Char2.isInt())
7205 return false;
7206 if (Char1.getInt() != Char2.getInt())
7207 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7208 if (StopAtNull && !Char1.getInt())
7209 return Success(0, E);
7210 assert(!(StopAtNull && !Char2.getInt()));
7211 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7212 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7213 return false;
7214 }
7215 // We hit the strncmp / memcmp limit.
7216 return Success(0, E);
7217 }
7218
Richard Smith01ba47d2012-04-13 00:45:38 +00007219 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007220 case Builtin::BI__atomic_is_lock_free:
7221 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007222 APSInt SizeVal;
7223 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7224 return false;
7225
7226 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7227 // of two less than the maximum inline atomic width, we know it is
7228 // lock-free. If the size isn't a power of two, or greater than the
7229 // maximum alignment where we promote atomics, we know it is not lock-free
7230 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7231 // the answer can only be determined at runtime; for example, 16-byte
7232 // atomics have lock-free implementations on some, but not all,
7233 // x86-64 processors.
7234
7235 // Check power-of-two.
7236 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007237 if (Size.isPowerOfTwo()) {
7238 // Check against inlining width.
7239 unsigned InlineWidthBits =
7240 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7241 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7242 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7243 Size == CharUnits::One() ||
7244 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7245 Expr::NPC_NeverValueDependent))
7246 // OK, we will inline appropriately-aligned operations of this size,
7247 // and _Atomic(T) is appropriately-aligned.
7248 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007249
Richard Smith01ba47d2012-04-13 00:45:38 +00007250 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7251 castAs<PointerType>()->getPointeeType();
7252 if (!PointeeType->isIncompleteType() &&
7253 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7254 // OK, we will inline operations on this object.
7255 return Success(1, E);
7256 }
7257 }
7258 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007259
Richard Smith01ba47d2012-04-13 00:45:38 +00007260 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7261 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007262 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007263 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007264}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007265
Richard Smith8b3497e2011-10-31 01:37:14 +00007266static bool HasSameBase(const LValue &A, const LValue &B) {
7267 if (!A.getLValueBase())
7268 return !B.getLValueBase();
7269 if (!B.getLValueBase())
7270 return false;
7271
Richard Smithce40ad62011-11-12 22:28:03 +00007272 if (A.getLValueBase().getOpaqueValue() !=
7273 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007274 const Decl *ADecl = GetLValueBaseDecl(A);
7275 if (!ADecl)
7276 return false;
7277 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007278 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007279 return false;
7280 }
7281
7282 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007283 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007284}
7285
Richard Smithd20f1e62014-10-21 23:01:04 +00007286/// \brief Determine whether this is a pointer past the end of the complete
7287/// object referred to by the lvalue.
7288static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7289 const LValue &LV) {
7290 // A null pointer can be viewed as being "past the end" but we don't
7291 // choose to look at it that way here.
7292 if (!LV.getLValueBase())
7293 return false;
7294
7295 // If the designator is valid and refers to a subobject, we're not pointing
7296 // past the end.
7297 if (!LV.getLValueDesignator().Invalid &&
7298 !LV.getLValueDesignator().isOnePastTheEnd())
7299 return false;
7300
David Majnemerc378ca52015-08-29 08:32:55 +00007301 // A pointer to an incomplete type might be past-the-end if the type's size is
7302 // zero. We cannot tell because the type is incomplete.
7303 QualType Ty = getType(LV.getLValueBase());
7304 if (Ty->isIncompleteType())
7305 return true;
7306
Richard Smithd20f1e62014-10-21 23:01:04 +00007307 // We're a past-the-end pointer if we point to the byte after the object,
7308 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007309 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007310 return LV.getLValueOffset() == Size;
7311}
7312
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007313namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007314
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007315/// \brief Data recursive integer evaluator of certain binary operators.
7316///
7317/// We use a data recursive algorithm for binary operators so that we are able
7318/// to handle extreme cases of chained binary operators without causing stack
7319/// overflow.
7320class DataRecursiveIntBinOpEvaluator {
7321 struct EvalResult {
7322 APValue Val;
7323 bool Failed;
7324
7325 EvalResult() : Failed(false) { }
7326
7327 void swap(EvalResult &RHS) {
7328 Val.swap(RHS.Val);
7329 Failed = RHS.Failed;
7330 RHS.Failed = false;
7331 }
7332 };
7333
7334 struct Job {
7335 const Expr *E;
7336 EvalResult LHSResult; // meaningful only for binary operator expression.
7337 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007338
David Blaikie73726062015-08-12 23:09:24 +00007339 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007340 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007341
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007342 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007343 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007344 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007345
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007346 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007347 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007348 };
7349
7350 SmallVector<Job, 16> Queue;
7351
7352 IntExprEvaluator &IntEval;
7353 EvalInfo &Info;
7354 APValue &FinalResult;
7355
7356public:
7357 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7358 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7359
7360 /// \brief True if \param E is a binary operator that we are going to handle
7361 /// data recursively.
7362 /// We handle binary operators that are comma, logical, or that have operands
7363 /// with integral or enumeration type.
7364 static bool shouldEnqueue(const BinaryOperator *E) {
7365 return E->getOpcode() == BO_Comma ||
7366 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007367 (E->isRValue() &&
7368 E->getType()->isIntegralOrEnumerationType() &&
7369 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007370 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007371 }
7372
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007373 bool Traverse(const BinaryOperator *E) {
7374 enqueue(E);
7375 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007376 while (!Queue.empty())
7377 process(PrevResult);
7378
7379 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007380
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007381 FinalResult.swap(PrevResult.Val);
7382 return true;
7383 }
7384
7385private:
7386 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7387 return IntEval.Success(Value, E, Result);
7388 }
7389 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7390 return IntEval.Success(Value, E, Result);
7391 }
7392 bool Error(const Expr *E) {
7393 return IntEval.Error(E);
7394 }
7395 bool Error(const Expr *E, diag::kind D) {
7396 return IntEval.Error(E, D);
7397 }
7398
7399 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7400 return Info.CCEDiag(E, D);
7401 }
7402
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007403 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7404 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007405 bool &SuppressRHSDiags);
7406
7407 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7408 const BinaryOperator *E, APValue &Result);
7409
7410 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7411 Result.Failed = !Evaluate(Result.Val, Info, E);
7412 if (Result.Failed)
7413 Result.Val = APValue();
7414 }
7415
Richard Trieuba4d0872012-03-21 23:30:30 +00007416 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007417
7418 void enqueue(const Expr *E) {
7419 E = E->IgnoreParens();
7420 Queue.resize(Queue.size()+1);
7421 Queue.back().E = E;
7422 Queue.back().Kind = Job::AnyExprKind;
7423 }
7424};
7425
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007426}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007427
7428bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007429 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007430 bool &SuppressRHSDiags) {
7431 if (E->getOpcode() == BO_Comma) {
7432 // Ignore LHS but note if we could not evaluate it.
7433 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007434 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007435 return true;
7436 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007437
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007438 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007439 bool LHSAsBool;
7440 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007441 // We were able to evaluate the LHS, see if we can get away with not
7442 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007443 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7444 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007445 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007446 }
7447 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007448 LHSResult.Failed = true;
7449
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007450 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007451 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007452 if (!Info.noteSideEffect())
7453 return false;
7454
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007455 // We can't evaluate the LHS; however, sometimes the result
7456 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7457 // Don't ignore RHS and suppress diagnostics from this arm.
7458 SuppressRHSDiags = true;
7459 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007460
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007461 return true;
7462 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007463
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007464 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7465 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007466
George Burgess IVa145e252016-05-25 22:38:36 +00007467 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007468 return false; // Ignore RHS;
7469
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007470 return true;
7471}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007472
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007473bool DataRecursiveIntBinOpEvaluator::
7474 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7475 const BinaryOperator *E, APValue &Result) {
7476 if (E->getOpcode() == BO_Comma) {
7477 if (RHSResult.Failed)
7478 return false;
7479 Result = RHSResult.Val;
7480 return true;
7481 }
7482
7483 if (E->isLogicalOp()) {
7484 bool lhsResult, rhsResult;
7485 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7486 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7487
7488 if (LHSIsOK) {
7489 if (RHSIsOK) {
7490 if (E->getOpcode() == BO_LOr)
7491 return Success(lhsResult || rhsResult, E, Result);
7492 else
7493 return Success(lhsResult && rhsResult, E, Result);
7494 }
7495 } else {
7496 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007497 // We can't evaluate the LHS; however, sometimes the result
7498 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7499 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007500 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007501 }
7502 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007503
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007504 return false;
7505 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007506
7507 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7508 E->getRHS()->getType()->isIntegralOrEnumerationType());
7509
7510 if (LHSResult.Failed || RHSResult.Failed)
7511 return false;
7512
7513 const APValue &LHSVal = LHSResult.Val;
7514 const APValue &RHSVal = RHSResult.Val;
7515
7516 // Handle cases like (unsigned long)&a + 4.
7517 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7518 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007519 CharUnits AdditionalOffset =
7520 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007521 if (E->getOpcode() == BO_Add)
7522 Result.getLValueOffset() += AdditionalOffset;
7523 else
7524 Result.getLValueOffset() -= AdditionalOffset;
7525 return true;
7526 }
7527
7528 // Handle cases like 4 + (unsigned long)&a
7529 if (E->getOpcode() == BO_Add &&
7530 RHSVal.isLValue() && LHSVal.isInt()) {
7531 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007532 Result.getLValueOffset() +=
7533 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007534 return true;
7535 }
7536
7537 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7538 // Handle (intptr_t)&&A - (intptr_t)&&B.
7539 if (!LHSVal.getLValueOffset().isZero() ||
7540 !RHSVal.getLValueOffset().isZero())
7541 return false;
7542 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7543 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7544 if (!LHSExpr || !RHSExpr)
7545 return false;
7546 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7547 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7548 if (!LHSAddrExpr || !RHSAddrExpr)
7549 return false;
7550 // Make sure both labels come from the same function.
7551 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7552 RHSAddrExpr->getLabel()->getDeclContext())
7553 return false;
7554 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7555 return true;
7556 }
Richard Smith43e77732013-05-07 04:50:00 +00007557
7558 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007559 if (!LHSVal.isInt() || !RHSVal.isInt())
7560 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007561
7562 // Set up the width and signedness manually, in case it can't be deduced
7563 // from the operation we're performing.
7564 // FIXME: Don't do this in the cases where we can deduce it.
7565 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7566 E->getType()->isUnsignedIntegerOrEnumerationType());
7567 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7568 RHSVal.getInt(), Value))
7569 return false;
7570 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007571}
7572
Richard Trieuba4d0872012-03-21 23:30:30 +00007573void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007574 Job &job = Queue.back();
7575
7576 switch (job.Kind) {
7577 case Job::AnyExprKind: {
7578 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7579 if (shouldEnqueue(Bop)) {
7580 job.Kind = Job::BinOpKind;
7581 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007582 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007583 }
7584 }
7585
7586 EvaluateExpr(job.E, Result);
7587 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007588 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007589 }
7590
7591 case Job::BinOpKind: {
7592 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007593 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007594 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007595 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007596 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007597 }
7598 if (SuppressRHSDiags)
7599 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007600 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007601 job.Kind = Job::BinOpVisitedLHSKind;
7602 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007603 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007604 }
7605
7606 case Job::BinOpVisitedLHSKind: {
7607 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7608 EvalResult RHS;
7609 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007610 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007611 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007612 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007613 }
7614 }
7615
7616 llvm_unreachable("Invalid Job::Kind!");
7617}
7618
George Burgess IV8c892b52016-05-25 22:31:54 +00007619namespace {
7620/// Used when we determine that we should fail, but can keep evaluating prior to
7621/// noting that we had a failure.
7622class DelayedNoteFailureRAII {
7623 EvalInfo &Info;
7624 bool NoteFailure;
7625
7626public:
7627 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7628 : Info(Info), NoteFailure(NoteFailure) {}
7629 ~DelayedNoteFailureRAII() {
7630 if (NoteFailure) {
7631 bool ContinueAfterFailure = Info.noteFailure();
7632 (void)ContinueAfterFailure;
7633 assert(ContinueAfterFailure &&
7634 "Shouldn't have kept evaluating on failure.");
7635 }
7636 }
7637};
7638}
7639
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007640bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007641 // We don't call noteFailure immediately because the assignment happens after
7642 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007643 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007644 return Error(E);
7645
George Burgess IV8c892b52016-05-25 22:31:54 +00007646 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007647 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7648 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007649
Anders Carlssonacc79812008-11-16 07:17:21 +00007650 QualType LHSTy = E->getLHS()->getType();
7651 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007652
Chandler Carruthb29a7432014-10-11 11:03:30 +00007653 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007654 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007655 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007656 if (E->isAssignmentOp()) {
7657 LValue LV;
7658 EvaluateLValue(E->getLHS(), LV, Info);
7659 LHSOK = false;
7660 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007661 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7662 if (LHSOK) {
7663 LHS.makeComplexFloat();
7664 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7665 }
7666 } else {
7667 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7668 }
George Burgess IVa145e252016-05-25 22:38:36 +00007669 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007670 return false;
7671
Chandler Carruthb29a7432014-10-11 11:03:30 +00007672 if (E->getRHS()->getType()->isRealFloatingType()) {
7673 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7674 return false;
7675 RHS.makeComplexFloat();
7676 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7677 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007678 return false;
7679
7680 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007681 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007682 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007683 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007684 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7685
John McCalle3027922010-08-25 11:45:40 +00007686 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007687 return Success((CR_r == APFloat::cmpEqual &&
7688 CR_i == APFloat::cmpEqual), E);
7689 else {
John McCalle3027922010-08-25 11:45:40 +00007690 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007691 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007692 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007693 CR_r == APFloat::cmpLessThan ||
7694 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007695 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007696 CR_i == APFloat::cmpLessThan ||
7697 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007698 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007699 } else {
John McCalle3027922010-08-25 11:45:40 +00007700 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007701 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7702 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7703 else {
John McCalle3027922010-08-25 11:45:40 +00007704 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007705 "Invalid compex comparison.");
7706 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7707 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7708 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007709 }
7710 }
Mike Stump11289f42009-09-09 15:08:12 +00007711
Anders Carlssonacc79812008-11-16 07:17:21 +00007712 if (LHSTy->isRealFloatingType() &&
7713 RHSTy->isRealFloatingType()) {
7714 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007715
Richard Smith253c2a32012-01-27 01:14:48 +00007716 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007717 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007718 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007719
Richard Smith253c2a32012-01-27 01:14:48 +00007720 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007721 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007722
Anders Carlssonacc79812008-11-16 07:17:21 +00007723 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007724
Anders Carlssonacc79812008-11-16 07:17:21 +00007725 switch (E->getOpcode()) {
7726 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007727 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007728 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007729 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007730 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007731 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007732 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007733 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007734 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007735 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007736 E);
John McCalle3027922010-08-25 11:45:40 +00007737 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007738 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007739 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007740 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007741 || CR == APFloat::cmpLessThan
7742 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007743 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007744 }
Mike Stump11289f42009-09-09 15:08:12 +00007745
Eli Friedmana38da572009-04-28 19:17:36 +00007746 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007747 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007748 LValue LHSValue, RHSValue;
7749
7750 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007751 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007752 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007753
Richard Smith253c2a32012-01-27 01:14:48 +00007754 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007755 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007756
Richard Smith8b3497e2011-10-31 01:37:14 +00007757 // Reject differing bases from the normal codepath; we special-case
7758 // comparisons to null.
7759 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007760 if (E->getOpcode() == BO_Sub) {
7761 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007762 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007763 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007764 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007765 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007766 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007767 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007768 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7769 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7770 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007771 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007772 // Make sure both labels come from the same function.
7773 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7774 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007775 return Error(E);
7776 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007777 }
Richard Smith83c68212011-10-31 05:11:32 +00007778 // Inequalities and subtractions between unrelated pointers have
7779 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007780 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007781 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007782 // A constant address may compare equal to the address of a symbol.
7783 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007784 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007785 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7786 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007787 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007788 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007789 // distinct addresses. In clang, the result of such a comparison is
7790 // unspecified, so it is not a constant expression. However, we do know
7791 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007792 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7793 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007794 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007795 // We can't tell whether weak symbols will end up pointing to the same
7796 // object.
7797 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007798 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007799 // We can't compare the address of the start of one object with the
7800 // past-the-end address of another object, per C++ DR1652.
7801 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7802 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7803 (RHSValue.Base && RHSValue.Offset.isZero() &&
7804 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7805 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007806 // We can't tell whether an object is at the same address as another
7807 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007808 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7809 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007810 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007811 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007812 // (Note that clang defaults to -fmerge-all-constants, which can
7813 // lead to inconsistent results for comparisons involving the address
7814 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007815 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007816 }
Eli Friedman64004332009-03-23 04:38:34 +00007817
Richard Smith1b470412012-02-01 08:10:20 +00007818 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7819 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7820
Richard Smith84f6dcf2012-02-02 01:16:57 +00007821 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7822 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7823
John McCalle3027922010-08-25 11:45:40 +00007824 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007825 // C++11 [expr.add]p6:
7826 // Unless both pointers point to elements of the same array object, or
7827 // one past the last element of the array object, the behavior is
7828 // undefined.
7829 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7830 !AreElementsOfSameArray(getType(LHSValue.Base),
7831 LHSDesignator, RHSDesignator))
7832 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7833
Chris Lattner882bdf22010-04-20 17:13:14 +00007834 QualType Type = E->getLHS()->getType();
7835 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007836
Richard Smithd62306a2011-11-10 06:34:14 +00007837 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007838 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007839 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007840
Richard Smith84c6b3d2013-09-10 21:34:14 +00007841 // As an extension, a type may have zero size (empty struct or union in
7842 // C, array of zero length). Pointer subtraction in such cases has
7843 // undefined behavior, so is not constant.
7844 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007845 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007846 << ElementType;
7847 return false;
7848 }
7849
Richard Smith1b470412012-02-01 08:10:20 +00007850 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7851 // and produce incorrect results when it overflows. Such behavior
7852 // appears to be non-conforming, but is common, so perhaps we should
7853 // assume the standard intended for such cases to be undefined behavior
7854 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007855
Richard Smith1b470412012-02-01 08:10:20 +00007856 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7857 // overflow in the final conversion to ptrdiff_t.
7858 APSInt LHS(
7859 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7860 APSInt RHS(
7861 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7862 APSInt ElemSize(
7863 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7864 APSInt TrueResult = (LHS - RHS) / ElemSize;
7865 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7866
Richard Smith0c6124b2015-12-03 01:36:22 +00007867 if (Result.extend(65) != TrueResult &&
7868 !HandleOverflow(Info, E, TrueResult, E->getType()))
7869 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007870 return Success(Result, E);
7871 }
Richard Smithde21b242012-01-31 06:41:30 +00007872
7873 // C++11 [expr.rel]p3:
7874 // Pointers to void (after pointer conversions) can be compared, with a
7875 // result defined as follows: If both pointers represent the same
7876 // address or are both the null pointer value, the result is true if the
7877 // operator is <= or >= and false otherwise; otherwise the result is
7878 // unspecified.
7879 // We interpret this as applying to pointers to *cv* void.
7880 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007881 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007882 CCEDiag(E, diag::note_constexpr_void_comparison);
7883
Richard Smith84f6dcf2012-02-02 01:16:57 +00007884 // C++11 [expr.rel]p2:
7885 // - If two pointers point to non-static data members of the same object,
7886 // or to subobjects or array elements fo such members, recursively, the
7887 // pointer to the later declared member compares greater provided the
7888 // two members have the same access control and provided their class is
7889 // not a union.
7890 // [...]
7891 // - Otherwise pointer comparisons are unspecified.
7892 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7893 E->isRelationalOp()) {
7894 bool WasArrayIndex;
7895 unsigned Mismatch =
7896 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7897 RHSDesignator, WasArrayIndex);
7898 // At the point where the designators diverge, the comparison has a
7899 // specified value if:
7900 // - we are comparing array indices
7901 // - we are comparing fields of a union, or fields with the same access
7902 // Otherwise, the result is unspecified and thus the comparison is not a
7903 // constant expression.
7904 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7905 Mismatch < RHSDesignator.Entries.size()) {
7906 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7907 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7908 if (!LF && !RF)
7909 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7910 else if (!LF)
7911 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7912 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7913 << RF->getParent() << RF;
7914 else if (!RF)
7915 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7916 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7917 << LF->getParent() << LF;
7918 else if (!LF->getParent()->isUnion() &&
7919 LF->getAccess() != RF->getAccess())
7920 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7921 << LF << LF->getAccess() << RF << RF->getAccess()
7922 << LF->getParent();
7923 }
7924 }
7925
Eli Friedman6c31cb42012-04-16 04:30:08 +00007926 // The comparison here must be unsigned, and performed with the same
7927 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007928 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7929 uint64_t CompareLHS = LHSOffset.getQuantity();
7930 uint64_t CompareRHS = RHSOffset.getQuantity();
7931 assert(PtrSize <= 64 && "Unexpected pointer width");
7932 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7933 CompareLHS &= Mask;
7934 CompareRHS &= Mask;
7935
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007936 // If there is a base and this is a relational operator, we can only
7937 // compare pointers within the object in question; otherwise, the result
7938 // depends on where the object is located in memory.
7939 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7940 QualType BaseTy = getType(LHSValue.Base);
7941 if (BaseTy->isIncompleteType())
7942 return Error(E);
7943 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7944 uint64_t OffsetLimit = Size.getQuantity();
7945 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7946 return Error(E);
7947 }
7948
Richard Smith8b3497e2011-10-31 01:37:14 +00007949 switch (E->getOpcode()) {
7950 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007951 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7952 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7953 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7954 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7955 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7956 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007957 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007958 }
7959 }
Richard Smith7bb00672012-02-01 01:42:44 +00007960
7961 if (LHSTy->isMemberPointerType()) {
7962 assert(E->isEqualityOp() && "unexpected member pointer operation");
7963 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7964
7965 MemberPtr LHSValue, RHSValue;
7966
7967 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007968 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007969 return false;
7970
7971 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7972 return false;
7973
7974 // C++11 [expr.eq]p2:
7975 // If both operands are null, they compare equal. Otherwise if only one is
7976 // null, they compare unequal.
7977 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7978 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7979 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7980 }
7981
7982 // Otherwise if either is a pointer to a virtual member function, the
7983 // result is unspecified.
7984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7985 if (MD->isVirtual())
7986 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7988 if (MD->isVirtual())
7989 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7990
7991 // Otherwise they compare equal if and only if they would refer to the
7992 // same member of the same most derived object or the same subobject if
7993 // they were dereferenced with a hypothetical object of the associated
7994 // class type.
7995 bool Equal = LHSValue == RHSValue;
7996 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7997 }
7998
Richard Smithab44d9b2012-02-14 22:35:28 +00007999 if (LHSTy->isNullPtrType()) {
8000 assert(E->isComparisonOp() && "unexpected nullptr operation");
8001 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8002 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8003 // are compared, the result is true of the operator is <=, >= or ==, and
8004 // false otherwise.
8005 BinaryOperator::Opcode Opcode = E->getOpcode();
8006 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8007 }
8008
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008009 assert((!LHSTy->isIntegralOrEnumerationType() ||
8010 !RHSTy->isIntegralOrEnumerationType()) &&
8011 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8012 // We can't continue from here for non-integral types.
8013 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008014}
8015
Peter Collingbournee190dee2011-03-11 19:24:49 +00008016/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8017/// a result as the expression's type.
8018bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8019 const UnaryExprOrTypeTraitExpr *E) {
8020 switch(E->getKind()) {
8021 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008022 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008023 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008024 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008025 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008026 }
Eli Friedman64004332009-03-23 04:38:34 +00008027
Peter Collingbournee190dee2011-03-11 19:24:49 +00008028 case UETT_VecStep: {
8029 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008030
Peter Collingbournee190dee2011-03-11 19:24:49 +00008031 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008032 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008033
Peter Collingbournee190dee2011-03-11 19:24:49 +00008034 // The vec_step built-in functions that take a 3-component
8035 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8036 if (n == 3)
8037 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008038
Peter Collingbournee190dee2011-03-11 19:24:49 +00008039 return Success(n, E);
8040 } else
8041 return Success(1, E);
8042 }
8043
8044 case UETT_SizeOf: {
8045 QualType SrcTy = E->getTypeOfArgument();
8046 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8047 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008048 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8049 SrcTy = Ref->getPointeeType();
8050
Richard Smithd62306a2011-11-10 06:34:14 +00008051 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008052 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008053 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008054 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008055 }
Alexey Bataev00396512015-07-02 03:40:19 +00008056 case UETT_OpenMPRequiredSimdAlign:
8057 assert(E->isArgumentType());
8058 return Success(
8059 Info.Ctx.toCharUnitsFromBits(
8060 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8061 .getQuantity(),
8062 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008063 }
8064
8065 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008066}
8067
Peter Collingbournee9200682011-05-13 03:29:01 +00008068bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008069 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008070 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008071 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008072 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008073 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008074 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008075 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008076 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008077 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008078 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008079 APSInt IdxResult;
8080 if (!EvaluateInteger(Idx, IdxResult, Info))
8081 return false;
8082 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8083 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008084 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008085 CurrentType = AT->getElementType();
8086 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8087 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008088 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008089 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008090
James Y Knight7281c352015-12-29 22:31:18 +00008091 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008092 FieldDecl *MemberDecl = ON.getField();
8093 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008094 if (!RT)
8095 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008096 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008097 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008098 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008099 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008100 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008101 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008102 CurrentType = MemberDecl->getType().getNonReferenceType();
8103 break;
8104 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008105
James Y Knight7281c352015-12-29 22:31:18 +00008106 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008107 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008108
James Y Knight7281c352015-12-29 22:31:18 +00008109 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008110 CXXBaseSpecifier *BaseSpec = ON.getBase();
8111 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008112 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008113
8114 // Find the layout of the class whose base we are looking into.
8115 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008116 if (!RT)
8117 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008118 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008119 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008120 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8121
8122 // Find the base class itself.
8123 CurrentType = BaseSpec->getType();
8124 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8125 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008126 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008127
8128 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008129 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008130 break;
8131 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008132 }
8133 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008134 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008135}
8136
Chris Lattnere13042c2008-07-11 19:10:17 +00008137bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008138 switch (E->getOpcode()) {
8139 default:
8140 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8141 // See C99 6.6p3.
8142 return Error(E);
8143 case UO_Extension:
8144 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8145 // If so, we could clear the diagnostic ID.
8146 return Visit(E->getSubExpr());
8147 case UO_Plus:
8148 // The result is just the value.
8149 return Visit(E->getSubExpr());
8150 case UO_Minus: {
8151 if (!Visit(E->getSubExpr()))
8152 return false;
8153 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008154 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008155 if (Value.isSigned() && Value.isMinSignedValue() &&
8156 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8157 E->getType()))
8158 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008159 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008160 }
8161 case UO_Not: {
8162 if (!Visit(E->getSubExpr()))
8163 return false;
8164 if (!Result.isInt()) return Error(E);
8165 return Success(~Result.getInt(), E);
8166 }
8167 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008168 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008169 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008170 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008171 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008172 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008173 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008174}
Mike Stump11289f42009-09-09 15:08:12 +00008175
Chris Lattner477c4be2008-07-12 01:15:53 +00008176/// HandleCast - This is used to evaluate implicit or explicit casts where the
8177/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008178bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8179 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008180 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008181 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008182
Eli Friedmanc757de22011-03-25 00:43:55 +00008183 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008184 case CK_BaseToDerived:
8185 case CK_DerivedToBase:
8186 case CK_UncheckedDerivedToBase:
8187 case CK_Dynamic:
8188 case CK_ToUnion:
8189 case CK_ArrayToPointerDecay:
8190 case CK_FunctionToPointerDecay:
8191 case CK_NullToPointer:
8192 case CK_NullToMemberPointer:
8193 case CK_BaseToDerivedMemberPointer:
8194 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008195 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008196 case CK_ConstructorConversion:
8197 case CK_IntegralToPointer:
8198 case CK_ToVoid:
8199 case CK_VectorSplat:
8200 case CK_IntegralToFloating:
8201 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008202 case CK_CPointerToObjCPointerCast:
8203 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008204 case CK_AnyPointerToBlockPointerCast:
8205 case CK_ObjCObjectLValueCast:
8206 case CK_FloatingRealToComplex:
8207 case CK_FloatingComplexToReal:
8208 case CK_FloatingComplexCast:
8209 case CK_FloatingComplexToIntegralComplex:
8210 case CK_IntegralRealToComplex:
8211 case CK_IntegralComplexCast:
8212 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008213 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008214 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008215 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008216 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008217 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008218 llvm_unreachable("invalid cast kind for integral value");
8219
Eli Friedman9faf2f92011-03-25 19:07:11 +00008220 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008221 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008222 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008223 case CK_ARCProduceObject:
8224 case CK_ARCConsumeObject:
8225 case CK_ARCReclaimReturnedObject:
8226 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008227 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008228 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008229
Richard Smith4ef685b2012-01-17 21:17:26 +00008230 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008231 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008232 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008233 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008234 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008235
8236 case CK_MemberPointerToBoolean:
8237 case CK_PointerToBoolean:
8238 case CK_IntegralToBoolean:
8239 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008240 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008241 case CK_FloatingComplexToBoolean:
8242 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008243 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008244 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008245 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008246 uint64_t IntResult = BoolResult;
8247 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8248 IntResult = (uint64_t)-1;
8249 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008250 }
8251
Eli Friedmanc757de22011-03-25 00:43:55 +00008252 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008253 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008254 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008255
Eli Friedman742421e2009-02-20 01:15:07 +00008256 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008257 // Allow casts of address-of-label differences if they are no-ops
8258 // or narrowing. (The narrowing case isn't actually guaranteed to
8259 // be constant-evaluatable except in some narrow cases which are hard
8260 // to detect here. We let it through on the assumption the user knows
8261 // what they are doing.)
8262 if (Result.isAddrLabelDiff())
8263 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008264 // Only allow casts of lvalues if they are lossless.
8265 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8266 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008267
Richard Smith911e1422012-01-30 22:27:01 +00008268 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8269 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008270 }
Mike Stump11289f42009-09-09 15:08:12 +00008271
Eli Friedmanc757de22011-03-25 00:43:55 +00008272 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008273 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8274
John McCall45d55e42010-05-07 21:00:08 +00008275 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008276 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008277 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008278
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008279 if (LV.getLValueBase()) {
8280 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008281 // FIXME: Allow a larger integer size than the pointer size, and allow
8282 // narrowing back down to pointer width in subsequent integral casts.
8283 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008284 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008285 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008286
Richard Smithcf74da72011-11-16 07:18:12 +00008287 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008288 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008289 return true;
8290 }
8291
Ken Dyck02990832010-01-15 12:37:54 +00008292 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8293 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008294 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008295 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008296
Eli Friedmanc757de22011-03-25 00:43:55 +00008297 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008298 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008299 if (!EvaluateComplex(SubExpr, C, Info))
8300 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008301 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008302 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008303
Eli Friedmanc757de22011-03-25 00:43:55 +00008304 case CK_FloatingToIntegral: {
8305 APFloat F(0.0);
8306 if (!EvaluateFloat(SubExpr, F, Info))
8307 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008308
Richard Smith357362d2011-12-13 06:39:58 +00008309 APSInt Value;
8310 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8311 return false;
8312 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008313 }
8314 }
Mike Stump11289f42009-09-09 15:08:12 +00008315
Eli Friedmanc757de22011-03-25 00:43:55 +00008316 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008317}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008318
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008319bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8320 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008321 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008322 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8323 return false;
8324 if (!LV.isComplexInt())
8325 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008326 return Success(LV.getComplexIntReal(), E);
8327 }
8328
8329 return Visit(E->getSubExpr());
8330}
8331
Eli Friedman4e7a2412009-02-27 04:45:43 +00008332bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008333 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008334 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008335 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8336 return false;
8337 if (!LV.isComplexInt())
8338 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008339 return Success(LV.getComplexIntImag(), E);
8340 }
8341
Richard Smith4a678122011-10-24 18:44:57 +00008342 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008343 return Success(0, E);
8344}
8345
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008346bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8347 return Success(E->getPackLength(), E);
8348}
8349
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008350bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8351 return Success(E->getValue(), E);
8352}
8353
Chris Lattner05706e882008-07-11 18:11:29 +00008354//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008355// Float Evaluation
8356//===----------------------------------------------------------------------===//
8357
8358namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008359class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008360 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008361 APFloat &Result;
8362public:
8363 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008364 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008365
Richard Smith2e312c82012-03-03 22:46:17 +00008366 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008367 Result = V.getFloat();
8368 return true;
8369 }
Eli Friedman24c01542008-08-22 00:06:13 +00008370
Richard Smithfddd3842011-12-30 21:15:51 +00008371 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008372 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8373 return true;
8374 }
8375
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008376 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008377
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008378 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008379 bool VisitBinaryOperator(const BinaryOperator *E);
8380 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008381 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008382
John McCallb1fb0d32010-05-07 22:08:54 +00008383 bool VisitUnaryReal(const UnaryOperator *E);
8384 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008385
Richard Smithfddd3842011-12-30 21:15:51 +00008386 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008387};
8388} // end anonymous namespace
8389
8390static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008391 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008392 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008393}
8394
Jay Foad39c79802011-01-12 09:06:06 +00008395static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008396 QualType ResultTy,
8397 const Expr *Arg,
8398 bool SNaN,
8399 llvm::APFloat &Result) {
8400 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8401 if (!S) return false;
8402
8403 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8404
8405 llvm::APInt fill;
8406
8407 // Treat empty strings as if they were zero.
8408 if (S->getString().empty())
8409 fill = llvm::APInt(32, 0);
8410 else if (S->getString().getAsInteger(0, fill))
8411 return false;
8412
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008413 if (Context.getTargetInfo().isNan2008()) {
8414 if (SNaN)
8415 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8416 else
8417 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8418 } else {
8419 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8420 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8421 // a different encoding to what became a standard in 2008, and for pre-
8422 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8423 // sNaN. This is now known as "legacy NaN" encoding.
8424 if (SNaN)
8425 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8426 else
8427 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8428 }
8429
John McCall16291492010-02-28 13:00:19 +00008430 return true;
8431}
8432
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008433bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008434 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008435 default:
8436 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8437
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008438 case Builtin::BI__builtin_huge_val:
8439 case Builtin::BI__builtin_huge_valf:
8440 case Builtin::BI__builtin_huge_vall:
8441 case Builtin::BI__builtin_inf:
8442 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008443 case Builtin::BI__builtin_infl: {
8444 const llvm::fltSemantics &Sem =
8445 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008446 Result = llvm::APFloat::getInf(Sem);
8447 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008448 }
Mike Stump11289f42009-09-09 15:08:12 +00008449
John McCall16291492010-02-28 13:00:19 +00008450 case Builtin::BI__builtin_nans:
8451 case Builtin::BI__builtin_nansf:
8452 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008453 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8454 true, Result))
8455 return Error(E);
8456 return true;
John McCall16291492010-02-28 13:00:19 +00008457
Chris Lattner0b7282e2008-10-06 06:31:58 +00008458 case Builtin::BI__builtin_nan:
8459 case Builtin::BI__builtin_nanf:
8460 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008461 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008462 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008463 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8464 false, Result))
8465 return Error(E);
8466 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008467
8468 case Builtin::BI__builtin_fabs:
8469 case Builtin::BI__builtin_fabsf:
8470 case Builtin::BI__builtin_fabsl:
8471 if (!EvaluateFloat(E->getArg(0), Result, Info))
8472 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008473
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008474 if (Result.isNegative())
8475 Result.changeSign();
8476 return true;
8477
Richard Smith8889a3d2013-06-13 06:26:32 +00008478 // FIXME: Builtin::BI__builtin_powi
8479 // FIXME: Builtin::BI__builtin_powif
8480 // FIXME: Builtin::BI__builtin_powil
8481
Mike Stump11289f42009-09-09 15:08:12 +00008482 case Builtin::BI__builtin_copysign:
8483 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008484 case Builtin::BI__builtin_copysignl: {
8485 APFloat RHS(0.);
8486 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8487 !EvaluateFloat(E->getArg(1), RHS, Info))
8488 return false;
8489 Result.copySign(RHS);
8490 return true;
8491 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008492 }
8493}
8494
John McCallb1fb0d32010-05-07 22:08:54 +00008495bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008496 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8497 ComplexValue CV;
8498 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8499 return false;
8500 Result = CV.FloatReal;
8501 return true;
8502 }
8503
8504 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008505}
8506
8507bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008508 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8509 ComplexValue CV;
8510 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8511 return false;
8512 Result = CV.FloatImag;
8513 return true;
8514 }
8515
Richard Smith4a678122011-10-24 18:44:57 +00008516 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008517 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8518 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008519 return true;
8520}
8521
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008522bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008523 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008524 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008525 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008526 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008527 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008528 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8529 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008530 Result.changeSign();
8531 return true;
8532 }
8533}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008534
Eli Friedman24c01542008-08-22 00:06:13 +00008535bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008536 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8537 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008538
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008539 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008540 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008541 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008542 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008543 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8544 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008545}
8546
8547bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8548 Result = E->getValue();
8549 return true;
8550}
8551
Peter Collingbournee9200682011-05-13 03:29:01 +00008552bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8553 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008554
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008555 switch (E->getCastKind()) {
8556 default:
Richard Smith11562c52011-10-28 17:51:58 +00008557 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008558
8559 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008560 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008561 return EvaluateInteger(SubExpr, IntResult, Info) &&
8562 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8563 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008564 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008565
8566 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008567 if (!Visit(SubExpr))
8568 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008569 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8570 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008571 }
John McCalld7646252010-11-14 08:17:51 +00008572
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008573 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008574 ComplexValue V;
8575 if (!EvaluateComplex(SubExpr, V, Info))
8576 return false;
8577 Result = V.getComplexFloatReal();
8578 return true;
8579 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008580 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008581}
8582
Eli Friedman24c01542008-08-22 00:06:13 +00008583//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008584// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008585//===----------------------------------------------------------------------===//
8586
8587namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008588class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008589 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008590 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008591
Anders Carlsson537969c2008-11-16 20:27:53 +00008592public:
John McCall93d91dc2010-05-07 17:22:02 +00008593 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008594 : ExprEvaluatorBaseTy(info), Result(Result) {}
8595
Richard Smith2e312c82012-03-03 22:46:17 +00008596 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008597 Result.setFrom(V);
8598 return true;
8599 }
Mike Stump11289f42009-09-09 15:08:12 +00008600
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008601 bool ZeroInitialization(const Expr *E);
8602
Anders Carlsson537969c2008-11-16 20:27:53 +00008603 //===--------------------------------------------------------------------===//
8604 // Visitor Methods
8605 //===--------------------------------------------------------------------===//
8606
Peter Collingbournee9200682011-05-13 03:29:01 +00008607 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008608 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008609 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008610 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008611 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008612};
8613} // end anonymous namespace
8614
John McCall93d91dc2010-05-07 17:22:02 +00008615static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8616 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008617 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008618 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008619}
8620
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008621bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008622 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008623 if (ElemTy->isRealFloatingType()) {
8624 Result.makeComplexFloat();
8625 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8626 Result.FloatReal = Zero;
8627 Result.FloatImag = Zero;
8628 } else {
8629 Result.makeComplexInt();
8630 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8631 Result.IntReal = Zero;
8632 Result.IntImag = Zero;
8633 }
8634 return true;
8635}
8636
Peter Collingbournee9200682011-05-13 03:29:01 +00008637bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8638 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008639
8640 if (SubExpr->getType()->isRealFloatingType()) {
8641 Result.makeComplexFloat();
8642 APFloat &Imag = Result.FloatImag;
8643 if (!EvaluateFloat(SubExpr, Imag, Info))
8644 return false;
8645
8646 Result.FloatReal = APFloat(Imag.getSemantics());
8647 return true;
8648 } else {
8649 assert(SubExpr->getType()->isIntegerType() &&
8650 "Unexpected imaginary literal.");
8651
8652 Result.makeComplexInt();
8653 APSInt &Imag = Result.IntImag;
8654 if (!EvaluateInteger(SubExpr, Imag, Info))
8655 return false;
8656
8657 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8658 return true;
8659 }
8660}
8661
Peter Collingbournee9200682011-05-13 03:29:01 +00008662bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008663
John McCallfcef3cf2010-12-14 17:51:41 +00008664 switch (E->getCastKind()) {
8665 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008666 case CK_BaseToDerived:
8667 case CK_DerivedToBase:
8668 case CK_UncheckedDerivedToBase:
8669 case CK_Dynamic:
8670 case CK_ToUnion:
8671 case CK_ArrayToPointerDecay:
8672 case CK_FunctionToPointerDecay:
8673 case CK_NullToPointer:
8674 case CK_NullToMemberPointer:
8675 case CK_BaseToDerivedMemberPointer:
8676 case CK_DerivedToBaseMemberPointer:
8677 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008678 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008679 case CK_ConstructorConversion:
8680 case CK_IntegralToPointer:
8681 case CK_PointerToIntegral:
8682 case CK_PointerToBoolean:
8683 case CK_ToVoid:
8684 case CK_VectorSplat:
8685 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008686 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008687 case CK_IntegralToBoolean:
8688 case CK_IntegralToFloating:
8689 case CK_FloatingToIntegral:
8690 case CK_FloatingToBoolean:
8691 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008692 case CK_CPointerToObjCPointerCast:
8693 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008694 case CK_AnyPointerToBlockPointerCast:
8695 case CK_ObjCObjectLValueCast:
8696 case CK_FloatingComplexToReal:
8697 case CK_FloatingComplexToBoolean:
8698 case CK_IntegralComplexToReal:
8699 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008700 case CK_ARCProduceObject:
8701 case CK_ARCConsumeObject:
8702 case CK_ARCReclaimReturnedObject:
8703 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008704 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008705 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008706 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008707 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008708 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008709 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00008710 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008711
John McCallfcef3cf2010-12-14 17:51:41 +00008712 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008713 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008714 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008715 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008716
8717 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008718 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008719 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008720 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008721
8722 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008723 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008724 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008725 return false;
8726
John McCallfcef3cf2010-12-14 17:51:41 +00008727 Result.makeComplexFloat();
8728 Result.FloatImag = APFloat(Real.getSemantics());
8729 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008730 }
8731
John McCallfcef3cf2010-12-14 17:51:41 +00008732 case CK_FloatingComplexCast: {
8733 if (!Visit(E->getSubExpr()))
8734 return false;
8735
8736 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8737 QualType From
8738 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8739
Richard Smith357362d2011-12-13 06:39:58 +00008740 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8741 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008742 }
8743
8744 case CK_FloatingComplexToIntegralComplex: {
8745 if (!Visit(E->getSubExpr()))
8746 return false;
8747
8748 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8749 QualType From
8750 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8751 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008752 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8753 To, Result.IntReal) &&
8754 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8755 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008756 }
8757
8758 case CK_IntegralRealToComplex: {
8759 APSInt &Real = Result.IntReal;
8760 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8761 return false;
8762
8763 Result.makeComplexInt();
8764 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8765 return true;
8766 }
8767
8768 case CK_IntegralComplexCast: {
8769 if (!Visit(E->getSubExpr()))
8770 return false;
8771
8772 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8773 QualType From
8774 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8775
Richard Smith911e1422012-01-30 22:27:01 +00008776 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8777 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008778 return true;
8779 }
8780
8781 case CK_IntegralComplexToFloatingComplex: {
8782 if (!Visit(E->getSubExpr()))
8783 return false;
8784
Ted Kremenek28831752012-08-23 20:46:57 +00008785 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008786 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008787 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008788 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008789 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8790 To, Result.FloatReal) &&
8791 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8792 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008793 }
8794 }
8795
8796 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008797}
8798
John McCall93d91dc2010-05-07 17:22:02 +00008799bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008800 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008801 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8802
Chandler Carrutha216cad2014-10-11 00:57:18 +00008803 // Track whether the LHS or RHS is real at the type system level. When this is
8804 // the case we can simplify our evaluation strategy.
8805 bool LHSReal = false, RHSReal = false;
8806
8807 bool LHSOK;
8808 if (E->getLHS()->getType()->isRealFloatingType()) {
8809 LHSReal = true;
8810 APFloat &Real = Result.FloatReal;
8811 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8812 if (LHSOK) {
8813 Result.makeComplexFloat();
8814 Result.FloatImag = APFloat(Real.getSemantics());
8815 }
8816 } else {
8817 LHSOK = Visit(E->getLHS());
8818 }
George Burgess IVa145e252016-05-25 22:38:36 +00008819 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008820 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008821
John McCall93d91dc2010-05-07 17:22:02 +00008822 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008823 if (E->getRHS()->getType()->isRealFloatingType()) {
8824 RHSReal = true;
8825 APFloat &Real = RHS.FloatReal;
8826 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8827 return false;
8828 RHS.makeComplexFloat();
8829 RHS.FloatImag = APFloat(Real.getSemantics());
8830 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008831 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008832
Chandler Carrutha216cad2014-10-11 00:57:18 +00008833 assert(!(LHSReal && RHSReal) &&
8834 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008835 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008836 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008837 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008838 if (Result.isComplexFloat()) {
8839 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8840 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008841 if (LHSReal)
8842 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8843 else if (!RHSReal)
8844 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8845 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008846 } else {
8847 Result.getComplexIntReal() += RHS.getComplexIntReal();
8848 Result.getComplexIntImag() += RHS.getComplexIntImag();
8849 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008850 break;
John McCalle3027922010-08-25 11:45:40 +00008851 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008852 if (Result.isComplexFloat()) {
8853 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8854 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008855 if (LHSReal) {
8856 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8857 Result.getComplexFloatImag().changeSign();
8858 } else if (!RHSReal) {
8859 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8860 APFloat::rmNearestTiesToEven);
8861 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008862 } else {
8863 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8864 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8865 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008866 break;
John McCalle3027922010-08-25 11:45:40 +00008867 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008868 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008869 // This is an implementation of complex multiplication according to the
8870 // constraints laid out in C11 Annex G. The implemantion uses the
8871 // following naming scheme:
8872 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008873 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008874 APFloat &A = LHS.getComplexFloatReal();
8875 APFloat &B = LHS.getComplexFloatImag();
8876 APFloat &C = RHS.getComplexFloatReal();
8877 APFloat &D = RHS.getComplexFloatImag();
8878 APFloat &ResR = Result.getComplexFloatReal();
8879 APFloat &ResI = Result.getComplexFloatImag();
8880 if (LHSReal) {
8881 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8882 ResR = A * C;
8883 ResI = A * D;
8884 } else if (RHSReal) {
8885 ResR = C * A;
8886 ResI = C * B;
8887 } else {
8888 // In the fully general case, we need to handle NaNs and infinities
8889 // robustly.
8890 APFloat AC = A * C;
8891 APFloat BD = B * D;
8892 APFloat AD = A * D;
8893 APFloat BC = B * C;
8894 ResR = AC - BD;
8895 ResI = AD + BC;
8896 if (ResR.isNaN() && ResI.isNaN()) {
8897 bool Recalc = false;
8898 if (A.isInfinity() || B.isInfinity()) {
8899 A = APFloat::copySign(
8900 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8901 B = APFloat::copySign(
8902 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8903 if (C.isNaN())
8904 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8905 if (D.isNaN())
8906 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8907 Recalc = true;
8908 }
8909 if (C.isInfinity() || D.isInfinity()) {
8910 C = APFloat::copySign(
8911 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8912 D = APFloat::copySign(
8913 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8914 if (A.isNaN())
8915 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8916 if (B.isNaN())
8917 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8918 Recalc = true;
8919 }
8920 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8921 AD.isInfinity() || BC.isInfinity())) {
8922 if (A.isNaN())
8923 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8924 if (B.isNaN())
8925 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8926 if (C.isNaN())
8927 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8928 if (D.isNaN())
8929 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8930 Recalc = true;
8931 }
8932 if (Recalc) {
8933 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8934 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8935 }
8936 }
8937 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008938 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008939 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008940 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008941 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8942 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008943 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008944 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8945 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8946 }
8947 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008948 case BO_Div:
8949 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008950 // This is an implementation of complex division according to the
8951 // constraints laid out in C11 Annex G. The implemantion uses the
8952 // following naming scheme:
8953 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008954 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008955 APFloat &A = LHS.getComplexFloatReal();
8956 APFloat &B = LHS.getComplexFloatImag();
8957 APFloat &C = RHS.getComplexFloatReal();
8958 APFloat &D = RHS.getComplexFloatImag();
8959 APFloat &ResR = Result.getComplexFloatReal();
8960 APFloat &ResI = Result.getComplexFloatImag();
8961 if (RHSReal) {
8962 ResR = A / C;
8963 ResI = B / C;
8964 } else {
8965 if (LHSReal) {
8966 // No real optimizations we can do here, stub out with zero.
8967 B = APFloat::getZero(A.getSemantics());
8968 }
8969 int DenomLogB = 0;
8970 APFloat MaxCD = maxnum(abs(C), abs(D));
8971 if (MaxCD.isFinite()) {
8972 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008973 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8974 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008975 }
8976 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008977 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8978 APFloat::rmNearestTiesToEven);
8979 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8980 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008981 if (ResR.isNaN() && ResI.isNaN()) {
8982 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8983 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8984 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8985 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8986 D.isFinite()) {
8987 A = APFloat::copySign(
8988 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8989 B = APFloat::copySign(
8990 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8991 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8992 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8993 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8994 C = APFloat::copySign(
8995 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8996 D = APFloat::copySign(
8997 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8998 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8999 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9000 }
9001 }
9002 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009003 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009004 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9005 return Error(E, diag::note_expr_divide_by_zero);
9006
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009007 ComplexValue LHS = Result;
9008 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9009 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9010 Result.getComplexIntReal() =
9011 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9012 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9013 Result.getComplexIntImag() =
9014 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9015 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9016 }
9017 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009018 }
9019
John McCall93d91dc2010-05-07 17:22:02 +00009020 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009021}
9022
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009023bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9024 // Get the operand value into 'Result'.
9025 if (!Visit(E->getSubExpr()))
9026 return false;
9027
9028 switch (E->getOpcode()) {
9029 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009030 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009031 case UO_Extension:
9032 return true;
9033 case UO_Plus:
9034 // The result is always just the subexpr.
9035 return true;
9036 case UO_Minus:
9037 if (Result.isComplexFloat()) {
9038 Result.getComplexFloatReal().changeSign();
9039 Result.getComplexFloatImag().changeSign();
9040 }
9041 else {
9042 Result.getComplexIntReal() = -Result.getComplexIntReal();
9043 Result.getComplexIntImag() = -Result.getComplexIntImag();
9044 }
9045 return true;
9046 case UO_Not:
9047 if (Result.isComplexFloat())
9048 Result.getComplexFloatImag().changeSign();
9049 else
9050 Result.getComplexIntImag() = -Result.getComplexIntImag();
9051 return true;
9052 }
9053}
9054
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009055bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9056 if (E->getNumInits() == 2) {
9057 if (E->getType()->isComplexType()) {
9058 Result.makeComplexFloat();
9059 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9060 return false;
9061 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9062 return false;
9063 } else {
9064 Result.makeComplexInt();
9065 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9066 return false;
9067 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9068 return false;
9069 }
9070 return true;
9071 }
9072 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9073}
9074
Anders Carlsson537969c2008-11-16 20:27:53 +00009075//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009076// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9077// implicit conversion.
9078//===----------------------------------------------------------------------===//
9079
9080namespace {
9081class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009082 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009083 APValue &Result;
9084public:
9085 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9086 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9087
9088 bool Success(const APValue &V, const Expr *E) {
9089 Result = V;
9090 return true;
9091 }
9092
9093 bool ZeroInitialization(const Expr *E) {
9094 ImplicitValueInitExpr VIE(
9095 E->getType()->castAs<AtomicType>()->getValueType());
9096 return Evaluate(Result, Info, &VIE);
9097 }
9098
9099 bool VisitCastExpr(const CastExpr *E) {
9100 switch (E->getCastKind()) {
9101 default:
9102 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9103 case CK_NonAtomicToAtomic:
9104 return Evaluate(Result, Info, E->getSubExpr());
9105 }
9106 }
9107};
9108} // end anonymous namespace
9109
9110static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9111 assert(E->isRValue() && E->getType()->isAtomicType());
9112 return AtomicExprEvaluator(Info, Result).Visit(E);
9113}
9114
9115//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009116// Void expression evaluation, primarily for a cast to void on the LHS of a
9117// comma operator
9118//===----------------------------------------------------------------------===//
9119
9120namespace {
9121class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009122 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009123public:
9124 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9125
Richard Smith2e312c82012-03-03 22:46:17 +00009126 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009127
9128 bool VisitCastExpr(const CastExpr *E) {
9129 switch (E->getCastKind()) {
9130 default:
9131 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9132 case CK_ToVoid:
9133 VisitIgnoredValue(E->getSubExpr());
9134 return true;
9135 }
9136 }
Hal Finkela8443c32014-07-17 14:49:58 +00009137
9138 bool VisitCallExpr(const CallExpr *E) {
9139 switch (E->getBuiltinCallee()) {
9140 default:
9141 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9142 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009143 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009144 // The argument is not evaluated!
9145 return true;
9146 }
9147 }
Richard Smith42d3af92011-12-07 00:43:50 +00009148};
9149} // end anonymous namespace
9150
9151static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9152 assert(E->isRValue() && E->getType()->isVoidType());
9153 return VoidExprEvaluator(Info).Visit(E);
9154}
9155
9156//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009157// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009158//===----------------------------------------------------------------------===//
9159
Richard Smith2e312c82012-03-03 22:46:17 +00009160static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009161 // In C, function designators are not lvalues, but we evaluate them as if they
9162 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009163 QualType T = E->getType();
9164 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009165 LValue LV;
9166 if (!EvaluateLValue(E, LV, Info))
9167 return false;
9168 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009169 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009170 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009171 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009172 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009173 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009174 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009175 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009176 LValue LV;
9177 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009178 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009179 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009180 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009181 llvm::APFloat F(0.0);
9182 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009183 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009184 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009185 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009186 ComplexValue C;
9187 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009188 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009189 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009190 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009191 MemberPtr P;
9192 if (!EvaluateMemberPointer(E, P, Info))
9193 return false;
9194 P.moveInto(Result);
9195 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009196 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009197 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009198 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009199 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9200 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009201 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009202 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009203 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009204 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009205 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009206 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9207 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009208 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009209 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009210 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009211 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009212 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009213 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009214 if (!EvaluateVoid(E, Info))
9215 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009216 } else if (T->isAtomicType()) {
9217 if (!EvaluateAtomic(E, Result, Info))
9218 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009219 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009220 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009221 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009222 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009223 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009224 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009225 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009226
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009227 return true;
9228}
9229
Richard Smithb228a862012-02-15 02:18:13 +00009230/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9231/// cases, the in-place evaluation is essential, since later initializers for
9232/// an object can indirectly refer to subobjects which were initialized earlier.
9233static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009234 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009235 assert(!E->isValueDependent());
9236
Richard Smith7525ff62013-05-09 07:14:00 +00009237 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009238 return false;
9239
9240 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009241 // Evaluate arrays and record types in-place, so that later initializers can
9242 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009243 if (E->getType()->isArrayType())
9244 return EvaluateArray(E, This, Result, Info);
9245 else if (E->getType()->isRecordType())
9246 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009247 }
9248
9249 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009250 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009251}
9252
Richard Smithf57d8cb2011-12-09 22:58:01 +00009253/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9254/// lvalue-to-rvalue cast if it is an lvalue.
9255static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009256 if (E->getType().isNull())
9257 return false;
9258
Richard Smithfddd3842011-12-30 21:15:51 +00009259 if (!CheckLiteralType(Info, E))
9260 return false;
9261
Richard Smith2e312c82012-03-03 22:46:17 +00009262 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009263 return false;
9264
9265 if (E->isGLValue()) {
9266 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009267 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009268 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009269 return false;
9270 }
9271
Richard Smith2e312c82012-03-03 22:46:17 +00009272 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009273 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009274}
Richard Smith11562c52011-10-28 17:51:58 +00009275
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009276static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9277 const ASTContext &Ctx, bool &IsConst) {
9278 // Fast-path evaluations of integer literals, since we sometimes see files
9279 // containing vast quantities of these.
9280 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9281 Result.Val = APValue(APSInt(L->getValue(),
9282 L->getType()->isUnsignedIntegerType()));
9283 IsConst = true;
9284 return true;
9285 }
James Dennett0492ef02014-03-14 17:44:10 +00009286
9287 // This case should be rare, but we need to check it before we check on
9288 // the type below.
9289 if (Exp->getType().isNull()) {
9290 IsConst = false;
9291 return true;
9292 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009293
9294 // FIXME: Evaluating values of large array and record types can cause
9295 // performance problems. Only do so in C++11 for now.
9296 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9297 Exp->getType()->isRecordType()) &&
9298 !Ctx.getLangOpts().CPlusPlus11) {
9299 IsConst = false;
9300 return true;
9301 }
9302 return false;
9303}
9304
9305
Richard Smith7b553f12011-10-29 00:50:52 +00009306/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009307/// any crazy technique (that has nothing to do with language standards) that
9308/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009309/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9310/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009311bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009312 bool IsConst;
9313 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9314 return IsConst;
9315
Richard Smith6d4c6582013-11-05 22:18:15 +00009316 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009317 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009318}
9319
Jay Foad39c79802011-01-12 09:06:06 +00009320bool Expr::EvaluateAsBooleanCondition(bool &Result,
9321 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009322 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009323 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009324 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009325}
9326
Richard Smithce8eca52015-12-08 03:21:47 +00009327static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9328 Expr::SideEffectsKind SEK) {
9329 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9330 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9331}
9332
Richard Smith5fab0c92011-12-28 19:48:30 +00009333bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9334 SideEffectsKind AllowSideEffects) const {
9335 if (!getType()->isIntegralOrEnumerationType())
9336 return false;
9337
Richard Smith11562c52011-10-28 17:51:58 +00009338 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009339 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009340 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009341 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009342
Richard Smith11562c52011-10-28 17:51:58 +00009343 Result = ExprResult.Val.getInt();
9344 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009345}
9346
Richard Trieube234c32016-04-21 21:04:55 +00009347bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9348 SideEffectsKind AllowSideEffects) const {
9349 if (!getType()->isRealFloatingType())
9350 return false;
9351
9352 EvalResult ExprResult;
9353 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9354 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9355 return false;
9356
9357 Result = ExprResult.Val.getFloat();
9358 return true;
9359}
9360
Jay Foad39c79802011-01-12 09:06:06 +00009361bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009362 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009363
John McCall45d55e42010-05-07 21:00:08 +00009364 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009365 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9366 !CheckLValueConstantExpression(Info, getExprLoc(),
9367 Ctx.getLValueReferenceType(getType()), LV))
9368 return false;
9369
Richard Smith2e312c82012-03-03 22:46:17 +00009370 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009371 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009372}
9373
Richard Smithd0b4dd62011-12-19 06:19:21 +00009374bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9375 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009376 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009377 // FIXME: Evaluating initializers for large array and record types can cause
9378 // performance problems. Only do so in C++11 for now.
9379 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009380 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009381 return false;
9382
Richard Smithd0b4dd62011-12-19 06:19:21 +00009383 Expr::EvalStatus EStatus;
9384 EStatus.Diag = &Notes;
9385
Richard Smith0c6124b2015-12-03 01:36:22 +00009386 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9387 ? EvalInfo::EM_ConstantExpression
9388 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009389 InitInfo.setEvaluatingDecl(VD, Value);
9390
9391 LValue LVal;
9392 LVal.set(VD);
9393
Richard Smithfddd3842011-12-30 21:15:51 +00009394 // C++11 [basic.start.init]p2:
9395 // Variables with static storage duration or thread storage duration shall be
9396 // zero-initialized before any other initialization takes place.
9397 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009398 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009399 !VD->getType()->isReferenceType()) {
9400 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009401 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009402 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009403 return false;
9404 }
9405
Richard Smith7525ff62013-05-09 07:14:00 +00009406 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9407 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009408 EStatus.HasSideEffects)
9409 return false;
9410
9411 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9412 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009413}
9414
Richard Smith7b553f12011-10-29 00:50:52 +00009415/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9416/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009417bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009418 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009419 return EvaluateAsRValue(Result, Ctx) &&
9420 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009421}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009422
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009423APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009424 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009425 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009426 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009427 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009428 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009429 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009430 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009431
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009432 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009433}
John McCall864e3962010-05-07 05:32:02 +00009434
Richard Smithe9ff7702013-11-05 22:23:30 +00009435void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009436 bool IsConst;
9437 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009438 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009439 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009440 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9441 }
9442}
9443
Richard Smithe6c01442013-06-05 00:46:14 +00009444bool Expr::EvalResult::isGlobalLValue() const {
9445 assert(Val.isLValue());
9446 return IsGlobalLValue(Val.getLValueBase());
9447}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009448
9449
John McCall864e3962010-05-07 05:32:02 +00009450/// isIntegerConstantExpr - this recursive routine will test if an expression is
9451/// an integer constant expression.
9452
9453/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9454/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009455
9456// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009457// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9458// and a (possibly null) SourceLocation indicating the location of the problem.
9459//
John McCall864e3962010-05-07 05:32:02 +00009460// Note that to reduce code duplication, this helper does no evaluation
9461// itself; the caller checks whether the expression is evaluatable, and
9462// in the rare cases where CheckICE actually cares about the evaluated
9463// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009464
Dan Gohman28ade552010-07-26 21:25:24 +00009465namespace {
9466
Richard Smith9e575da2012-12-28 13:25:52 +00009467enum ICEKind {
9468 /// This expression is an ICE.
9469 IK_ICE,
9470 /// This expression is not an ICE, but if it isn't evaluated, it's
9471 /// a legal subexpression for an ICE. This return value is used to handle
9472 /// the comma operator in C99 mode, and non-constant subexpressions.
9473 IK_ICEIfUnevaluated,
9474 /// This expression is not an ICE, and is not a legal subexpression for one.
9475 IK_NotICE
9476};
9477
John McCall864e3962010-05-07 05:32:02 +00009478struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009479 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009480 SourceLocation Loc;
9481
Richard Smith9e575da2012-12-28 13:25:52 +00009482 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009483};
9484
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009485}
Dan Gohman28ade552010-07-26 21:25:24 +00009486
Richard Smith9e575da2012-12-28 13:25:52 +00009487static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9488
9489static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009490
Craig Toppera31a8822013-08-22 07:09:37 +00009491static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009492 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009493 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009494 !EVResult.Val.isInt())
9495 return ICEDiag(IK_NotICE, E->getLocStart());
9496
John McCall864e3962010-05-07 05:32:02 +00009497 return NoDiag();
9498}
9499
Craig Toppera31a8822013-08-22 07:09:37 +00009500static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009501 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009502 if (!E->getType()->isIntegralOrEnumerationType())
9503 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009504
9505 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009506#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009507#define STMT(Node, Base) case Expr::Node##Class:
9508#define EXPR(Node, Base)
9509#include "clang/AST/StmtNodes.inc"
9510 case Expr::PredefinedExprClass:
9511 case Expr::FloatingLiteralClass:
9512 case Expr::ImaginaryLiteralClass:
9513 case Expr::StringLiteralClass:
9514 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009515 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009516 case Expr::MemberExprClass:
9517 case Expr::CompoundAssignOperatorClass:
9518 case Expr::CompoundLiteralExprClass:
9519 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009520 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009521 case Expr::NoInitExprClass:
9522 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009523 case Expr::ImplicitValueInitExprClass:
9524 case Expr::ParenListExprClass:
9525 case Expr::VAArgExprClass:
9526 case Expr::AddrLabelExprClass:
9527 case Expr::StmtExprClass:
9528 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009529 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009530 case Expr::CXXDynamicCastExprClass:
9531 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009532 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009533 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009534 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009535 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009536 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009537 case Expr::CXXThisExprClass:
9538 case Expr::CXXThrowExprClass:
9539 case Expr::CXXNewExprClass:
9540 case Expr::CXXDeleteExprClass:
9541 case Expr::CXXPseudoDestructorExprClass:
9542 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009543 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009544 case Expr::DependentScopeDeclRefExprClass:
9545 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009546 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009547 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009548 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009549 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009550 case Expr::CXXTemporaryObjectExprClass:
9551 case Expr::CXXUnresolvedConstructExprClass:
9552 case Expr::CXXDependentScopeMemberExprClass:
9553 case Expr::UnresolvedMemberExprClass:
9554 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009555 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009556 case Expr::ObjCArrayLiteralClass:
9557 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009558 case Expr::ObjCEncodeExprClass:
9559 case Expr::ObjCMessageExprClass:
9560 case Expr::ObjCSelectorExprClass:
9561 case Expr::ObjCProtocolExprClass:
9562 case Expr::ObjCIvarRefExprClass:
9563 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009564 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009565 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009566 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009567 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009568 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009569 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009570 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009571 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009572 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009573 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009574 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009575 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009576 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009577 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009578 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009579 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009580 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009581 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009582 case Expr::CoawaitExprClass:
9583 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009584 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009585
Richard Smithf137f932014-01-25 20:50:08 +00009586 case Expr::InitListExprClass: {
9587 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9588 // form "T x = { a };" is equivalent to "T x = a;".
9589 // Unless we're initializing a reference, T is a scalar as it is known to be
9590 // of integral or enumeration type.
9591 if (E->isRValue())
9592 if (cast<InitListExpr>(E)->getNumInits() == 1)
9593 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9594 return ICEDiag(IK_NotICE, E->getLocStart());
9595 }
9596
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009597 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009598 case Expr::GNUNullExprClass:
9599 // GCC considers the GNU __null value to be an integral constant expression.
9600 return NoDiag();
9601
John McCall7c454bb2011-07-15 05:09:51 +00009602 case Expr::SubstNonTypeTemplateParmExprClass:
9603 return
9604 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9605
John McCall864e3962010-05-07 05:32:02 +00009606 case Expr::ParenExprClass:
9607 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009608 case Expr::GenericSelectionExprClass:
9609 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009610 case Expr::IntegerLiteralClass:
9611 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009612 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009613 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009614 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009615 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009616 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009617 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009618 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009619 return NoDiag();
9620 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009621 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009622 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9623 // constant expressions, but they can never be ICEs because an ICE cannot
9624 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009625 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009626 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009627 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009628 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009629 }
Richard Smith6365c912012-02-24 22:12:32 +00009630 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009631 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9632 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009633 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009634 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009635 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009636 // Parameter variables are never constants. Without this check,
9637 // getAnyInitializer() can find a default argument, which leads
9638 // to chaos.
9639 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009640 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009641
9642 // C++ 7.1.5.1p2
9643 // A variable of non-volatile const-qualified integral or enumeration
9644 // type initialized by an ICE can be used in ICEs.
9645 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009646 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009647 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009648
Richard Smithd0b4dd62011-12-19 06:19:21 +00009649 const VarDecl *VD;
9650 // Look for a declaration of this variable that has an initializer, and
9651 // check whether it is an ICE.
9652 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9653 return NoDiag();
9654 else
Richard Smith9e575da2012-12-28 13:25:52 +00009655 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009656 }
9657 }
Richard Smith9e575da2012-12-28 13:25:52 +00009658 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009659 }
John McCall864e3962010-05-07 05:32:02 +00009660 case Expr::UnaryOperatorClass: {
9661 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9662 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009663 case UO_PostInc:
9664 case UO_PostDec:
9665 case UO_PreInc:
9666 case UO_PreDec:
9667 case UO_AddrOf:
9668 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009669 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009670 // C99 6.6/3 allows increment and decrement within unevaluated
9671 // subexpressions of constant expressions, but they can never be ICEs
9672 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009673 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009674 case UO_Extension:
9675 case UO_LNot:
9676 case UO_Plus:
9677 case UO_Minus:
9678 case UO_Not:
9679 case UO_Real:
9680 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009681 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009682 }
Richard Smith9e575da2012-12-28 13:25:52 +00009683
John McCall864e3962010-05-07 05:32:02 +00009684 // OffsetOf falls through here.
9685 }
9686 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009687 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9688 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9689 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9690 // compliance: we should warn earlier for offsetof expressions with
9691 // array subscripts that aren't ICEs, and if the array subscripts
9692 // are ICEs, the value of the offsetof must be an integer constant.
9693 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009694 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009695 case Expr::UnaryExprOrTypeTraitExprClass: {
9696 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9697 if ((Exp->getKind() == UETT_SizeOf) &&
9698 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009699 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009700 return NoDiag();
9701 }
9702 case Expr::BinaryOperatorClass: {
9703 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9704 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009705 case BO_PtrMemD:
9706 case BO_PtrMemI:
9707 case BO_Assign:
9708 case BO_MulAssign:
9709 case BO_DivAssign:
9710 case BO_RemAssign:
9711 case BO_AddAssign:
9712 case BO_SubAssign:
9713 case BO_ShlAssign:
9714 case BO_ShrAssign:
9715 case BO_AndAssign:
9716 case BO_XorAssign:
9717 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009718 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9719 // constant expressions, but they can never be ICEs because an ICE cannot
9720 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009721 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009722
John McCalle3027922010-08-25 11:45:40 +00009723 case BO_Mul:
9724 case BO_Div:
9725 case BO_Rem:
9726 case BO_Add:
9727 case BO_Sub:
9728 case BO_Shl:
9729 case BO_Shr:
9730 case BO_LT:
9731 case BO_GT:
9732 case BO_LE:
9733 case BO_GE:
9734 case BO_EQ:
9735 case BO_NE:
9736 case BO_And:
9737 case BO_Xor:
9738 case BO_Or:
9739 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009740 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9741 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009742 if (Exp->getOpcode() == BO_Div ||
9743 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009744 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009745 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009746 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009747 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009748 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009749 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009750 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009751 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009752 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009753 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009754 }
9755 }
9756 }
John McCalle3027922010-08-25 11:45:40 +00009757 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009758 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009759 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9760 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009761 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9762 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009763 } else {
9764 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009765 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009766 }
9767 }
Richard Smith9e575da2012-12-28 13:25:52 +00009768 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009769 }
John McCalle3027922010-08-25 11:45:40 +00009770 case BO_LAnd:
9771 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009772 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9773 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009774 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009775 // Rare case where the RHS has a comma "side-effect"; we need
9776 // to actually check the condition to see whether the side
9777 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009778 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009779 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009780 return RHSResult;
9781 return NoDiag();
9782 }
9783
Richard Smith9e575da2012-12-28 13:25:52 +00009784 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009785 }
9786 }
9787 }
9788 case Expr::ImplicitCastExprClass:
9789 case Expr::CStyleCastExprClass:
9790 case Expr::CXXFunctionalCastExprClass:
9791 case Expr::CXXStaticCastExprClass:
9792 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009793 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009794 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009795 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009796 if (isa<ExplicitCastExpr>(E)) {
9797 if (const FloatingLiteral *FL
9798 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9799 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9800 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9801 APSInt IgnoredVal(DestWidth, !DestSigned);
9802 bool Ignored;
9803 // If the value does not fit in the destination type, the behavior is
9804 // undefined, so we are not required to treat it as a constant
9805 // expression.
9806 if (FL->getValue().convertToInteger(IgnoredVal,
9807 llvm::APFloat::rmTowardZero,
9808 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009809 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009810 return NoDiag();
9811 }
9812 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009813 switch (cast<CastExpr>(E)->getCastKind()) {
9814 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009815 case CK_AtomicToNonAtomic:
9816 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009817 case CK_NoOp:
9818 case CK_IntegralToBoolean:
9819 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009820 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009821 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009822 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009823 }
John McCall864e3962010-05-07 05:32:02 +00009824 }
John McCallc07a0c72011-02-17 10:25:35 +00009825 case Expr::BinaryConditionalOperatorClass: {
9826 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9827 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009828 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009829 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009830 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9831 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9832 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009833 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009834 return FalseResult;
9835 }
John McCall864e3962010-05-07 05:32:02 +00009836 case Expr::ConditionalOperatorClass: {
9837 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9838 // If the condition (ignoring parens) is a __builtin_constant_p call,
9839 // then only the true side is actually considered in an integer constant
9840 // expression, and it is fully evaluated. This is an important GNU
9841 // extension. See GCC PR38377 for discussion.
9842 if (const CallExpr *CallCE
9843 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009844 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009845 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009846 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009847 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009848 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009849
Richard Smithf57d8cb2011-12-09 22:58:01 +00009850 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9851 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009852
Richard Smith9e575da2012-12-28 13:25:52 +00009853 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009854 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009855 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009856 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009857 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009858 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009859 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009860 return NoDiag();
9861 // Rare case where the diagnostics depend on which side is evaluated
9862 // Note that if we get here, CondResult is 0, and at least one of
9863 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009864 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009865 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009866 return TrueResult;
9867 }
9868 case Expr::CXXDefaultArgExprClass:
9869 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009870 case Expr::CXXDefaultInitExprClass:
9871 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009872 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009873 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009874 }
9875 }
9876
David Blaikiee4d798f2012-01-20 21:50:17 +00009877 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009878}
9879
Richard Smithf57d8cb2011-12-09 22:58:01 +00009880/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009881static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009882 const Expr *E,
9883 llvm::APSInt *Value,
9884 SourceLocation *Loc) {
9885 if (!E->getType()->isIntegralOrEnumerationType()) {
9886 if (Loc) *Loc = E->getExprLoc();
9887 return false;
9888 }
9889
Richard Smith66e05fe2012-01-18 05:21:49 +00009890 APValue Result;
9891 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009892 return false;
9893
Richard Smith98710fc2014-11-13 23:03:19 +00009894 if (!Result.isInt()) {
9895 if (Loc) *Loc = E->getExprLoc();
9896 return false;
9897 }
9898
Richard Smith66e05fe2012-01-18 05:21:49 +00009899 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009900 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009901}
9902
Craig Toppera31a8822013-08-22 07:09:37 +00009903bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9904 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009905 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009906 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009907
Richard Smith9e575da2012-12-28 13:25:52 +00009908 ICEDiag D = CheckICE(this, Ctx);
9909 if (D.Kind != IK_ICE) {
9910 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009911 return false;
9912 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009913 return true;
9914}
9915
Craig Toppera31a8822013-08-22 07:09:37 +00009916bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009917 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009918 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009919 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9920
9921 if (!isIntegerConstantExpr(Ctx, Loc))
9922 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009923 // The only possible side-effects here are due to UB discovered in the
9924 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9925 // required to treat the expression as an ICE, so we produce the folded
9926 // value.
9927 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009928 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009929 return true;
9930}
Richard Smith66e05fe2012-01-18 05:21:49 +00009931
Craig Toppera31a8822013-08-22 07:09:37 +00009932bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009933 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009934}
9935
Craig Toppera31a8822013-08-22 07:09:37 +00009936bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009937 SourceLocation *Loc) const {
9938 // We support this checking in C++98 mode in order to diagnose compatibility
9939 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009940 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009941
Richard Smith98a0a492012-02-14 21:38:30 +00009942 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009943 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009944 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009945 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009946 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009947
9948 APValue Scratch;
9949 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9950
9951 if (!Diags.empty()) {
9952 IsConstExpr = false;
9953 if (Loc) *Loc = Diags[0].first;
9954 } else if (!IsConstExpr) {
9955 // FIXME: This shouldn't happen.
9956 if (Loc) *Loc = getExprLoc();
9957 }
9958
9959 return IsConstExpr;
9960}
Richard Smith253c2a32012-01-27 01:14:48 +00009961
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009962bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9963 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009964 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009965 Expr::EvalStatus Status;
9966 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9967
9968 ArgVector ArgValues(Args.size());
9969 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9970 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009971 if ((*I)->isValueDependent() ||
9972 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009973 // If evaluation fails, throw away the argument entirely.
9974 ArgValues[I - Args.begin()] = APValue();
9975 if (Info.EvalStatus.HasSideEffects)
9976 return false;
9977 }
9978
9979 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009980 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009981 ArgValues.data());
9982 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9983}
9984
Richard Smith253c2a32012-01-27 01:14:48 +00009985bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009986 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009987 PartialDiagnosticAt> &Diags) {
9988 // FIXME: It would be useful to check constexpr function templates, but at the
9989 // moment the constant expression evaluator cannot cope with the non-rigorous
9990 // ASTs which we build for dependent expressions.
9991 if (FD->isDependentContext())
9992 return true;
9993
9994 Expr::EvalStatus Status;
9995 Status.Diag = &Diags;
9996
Richard Smith6d4c6582013-11-05 22:18:15 +00009997 EvalInfo Info(FD->getASTContext(), Status,
9998 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009999
10000 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010001 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010002
Richard Smith7525ff62013-05-09 07:14:00 +000010003 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010004 // is a temporary being used as the 'this' pointer.
10005 LValue This;
10006 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010007 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010008
Richard Smith253c2a32012-01-27 01:14:48 +000010009 ArrayRef<const Expr*> Args;
10010
Richard Smith2e312c82012-03-03 22:46:17 +000010011 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010012 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10013 // Evaluate the call as a constant initializer, to allow the construction
10014 // of objects of non-literal types.
10015 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010016 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10017 } else {
10018 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010019 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010020 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010021 }
Richard Smith253c2a32012-01-27 01:14:48 +000010022
10023 return Diags.empty();
10024}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010025
10026bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10027 const FunctionDecl *FD,
10028 SmallVectorImpl<
10029 PartialDiagnosticAt> &Diags) {
10030 Expr::EvalStatus Status;
10031 Status.Diag = &Diags;
10032
10033 EvalInfo Info(FD->getASTContext(), Status,
10034 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10035
10036 // Fabricate a call stack frame to give the arguments a plausible cover story.
10037 ArrayRef<const Expr*> Args;
10038 ArgVector ArgValues(0);
10039 bool Success = EvaluateArgs(Args, ArgValues, Info);
10040 (void)Success;
10041 assert(Success &&
10042 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010043 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010044
10045 APValue ResultScratch;
10046 Evaluate(ResultScratch, Info, E);
10047 return Diags.empty();
10048}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010049
10050bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10051 unsigned Type) const {
10052 if (!getType()->isPointerType())
10053 return false;
10054
10055 Expr::EvalStatus Status;
10056 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10057 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10058}