blob: 36f5e6aae554b5d93edefc1db7b4ca81e69cfb09 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
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.
Reid Kleckner06df4022016-12-13 19:48:32 +0000436 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith410306b2016-12-12 02:53:20 +0000472 /// The current array initialization index, if we're performing array
473 /// initialization.
474 uint64_t ArrayInitIndex = -1;
475
Richard Smith357362d2011-12-13 06:39:58 +0000476 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
477 /// notes attached to it will also be stored, otherwise they will not be.
478 bool HasActiveDiagnostic;
479
Richard Smith0c6124b2015-12-03 01:36:22 +0000480 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
481 /// fold (not just why it's not strictly a constant expression)?
482 bool HasFoldFailureDiagnostic;
483
George Burgess IV8c892b52016-05-25 22:31:54 +0000484 /// \brief Whether or not we're currently speculatively evaluating.
485 bool IsSpeculativelyEvaluating;
486
Richard Smith6d4c6582013-11-05 22:18:15 +0000487 enum EvaluationMode {
488 /// Evaluate as a constant expression. Stop if we find that the expression
489 /// is not a constant expression.
490 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000491
Richard Smith6d4c6582013-11-05 22:18:15 +0000492 /// Evaluate as a potential constant expression. Keep going if we hit a
493 /// construct that we can't evaluate yet (because we don't yet know the
494 /// value of something) but stop if we hit something that could never be
495 /// a constant expression.
496 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000497
Richard Smith6d4c6582013-11-05 22:18:15 +0000498 /// Fold the expression to a constant. Stop if we hit a side-effect that
499 /// we can't model.
500 EM_ConstantFold,
501
502 /// Evaluate the expression looking for integer overflow and similar
503 /// issues. Don't worry about side-effects, and try to visit all
504 /// subexpressions.
505 EM_EvaluateForOverflow,
506
507 /// Evaluate in any way we know how. Don't worry about side-effects that
508 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000509 EM_IgnoreSideEffects,
510
511 /// Evaluate as a constant expression. Stop if we find that the expression
512 /// is not a constant expression. Some expressions can be retried in the
513 /// optimizer if we don't constant fold them here, but in an unevaluated
514 /// context we try to fold them immediately since the optimizer never
515 /// gets a chance to look at it.
516 EM_ConstantExpressionUnevaluated,
517
518 /// Evaluate as a potential constant expression. Keep going if we hit a
519 /// construct that we can't evaluate yet (because we don't yet know the
520 /// value of something) but stop if we hit something that could never be
521 /// a constant expression. Some expressions can be retried in the
522 /// optimizer if we don't constant fold them here, but in an unevaluated
523 /// context we try to fold them immediately since the optimizer never
524 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000525 EM_PotentialConstantExpressionUnevaluated,
526
527 /// Evaluate as a constant expression. Continue evaluating if we find a
528 /// MemberExpr with a base that can't be evaluated.
529 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000530 } EvalMode;
531
532 /// Are we checking whether the expression is a potential constant
533 /// expression?
534 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000535 return EvalMode == EM_PotentialConstantExpression ||
536 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000537 }
538
539 /// Are we checking an expression for overflow?
540 // FIXME: We should check for any kind of undefined or suspicious behavior
541 // in such constructs, not just overflow.
542 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
543
544 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000545 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000546 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000547 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000548 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
549 EvaluatingDecl((const ValueDecl *)nullptr),
550 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000551 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
552 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000553
Richard Smith7525ff62013-05-09 07:14:00 +0000554 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
555 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000556 EvaluatingDeclValue = &Value;
557 }
558
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000560
Richard Smith357362d2011-12-13 06:39:58 +0000561 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000562 // Don't perform any constexpr calls (other than the call we're checking)
563 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000564 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000565 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000566 if (NextCallIndex == 0) {
567 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000568 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000569 return false;
570 }
Richard Smith357362d2011-12-13 06:39:58 +0000571 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
572 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000573 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000574 << getLangOpts().ConstexprCallDepth;
575 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000576 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000577
Richard Smithb228a862012-02-15 02:18:13 +0000578 CallStackFrame *getCallFrame(unsigned CallIndex) {
579 assert(CallIndex && "no call index in getCallFrame");
580 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
581 // be null in this loop.
582 CallStackFrame *Frame = CurrentCall;
583 while (Frame->Index > CallIndex)
584 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000585 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000586 }
587
Richard Smitha3d3bd22013-05-08 02:12:03 +0000588 bool nextStep(const Stmt *S) {
589 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000590 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000591 return false;
592 }
593 --StepsLeft;
594 return true;
595 }
596
Richard Smith357362d2011-12-13 06:39:58 +0000597 private:
598 /// Add a diagnostic to the diagnostics list.
599 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
600 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
601 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
602 return EvalStatus.Diag->back().second;
603 }
604
Richard Smithf6f003a2011-12-16 19:06:07 +0000605 /// Add notes containing a call stack to the current point of evaluation.
606 void addCallStack(unsigned Limit);
607
Faisal Valie690b7a2016-07-02 22:34:24 +0000608 private:
609 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
610 unsigned ExtraNotes, bool IsCCEDiag) {
611
Richard Smith92b1ce02011-12-12 09:28:41 +0000612 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000613 // If we have a prior diagnostic, it will be noting that the expression
614 // isn't a constant expression. This diagnostic is more important,
615 // unless we require this evaluation to produce a constant expression.
616 //
617 // FIXME: We might want to show both diagnostics to the user in
618 // EM_ConstantFold mode.
619 if (!EvalStatus.Diag->empty()) {
620 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000621 case EM_ConstantFold:
622 case EM_IgnoreSideEffects:
623 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000625 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000626 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 case EM_ConstantExpression:
628 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000629 case EM_ConstantExpressionUnevaluated:
630 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000631 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 HasActiveDiagnostic = false;
633 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000634 }
635 }
636
Richard Smithf6f003a2011-12-16 19:06:07 +0000637 unsigned CallStackNotes = CallStackDepth - 1;
638 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
639 if (Limit)
640 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000642 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000643
Richard Smith357362d2011-12-13 06:39:58 +0000644 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000645 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000647 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
648 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000650 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 }
Richard Smith357362d2011-12-13 06:39:58 +0000653 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000654 return OptionalDiagnostic();
655 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000656 public:
657 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
658 OptionalDiagnostic
659 FFDiag(SourceLocation Loc,
660 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
661 unsigned ExtraNotes = 0) {
662 return Diag(Loc, DiagId, ExtraNotes, false);
663 }
664
665 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000666 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000667 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000668 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000669 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000670 HasActiveDiagnostic = false;
671 return OptionalDiagnostic();
672 }
673
Richard Smith92b1ce02011-12-12 09:28:41 +0000674 /// Diagnose that the evaluation does not produce a C++11 core constant
675 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 ///
677 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
678 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000679 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000680 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000681 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000682 // Don't override a previous diagnostic. Don't bother collecting
683 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000684 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000685 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000686 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000687 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000688 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000689 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000690 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
691 = diag::note_invalid_subexpr_in_const_expr,
692 unsigned ExtraNotes = 0) {
693 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
694 }
Richard Smith357362d2011-12-13 06:39:58 +0000695 /// Add a note to a prior diagnostic.
696 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
697 if (!HasActiveDiagnostic)
698 return OptionalDiagnostic();
699 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000700 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000701
702 /// Add a stack of notes to a prior diagnostic.
703 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
704 if (HasActiveDiagnostic) {
705 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
706 Diags.begin(), Diags.end());
707 }
708 }
Richard Smith253c2a32012-01-27 01:14:48 +0000709
Richard Smith6d4c6582013-11-05 22:18:15 +0000710 /// Should we continue evaluation after encountering a side-effect that we
711 /// couldn't model?
712 bool keepEvaluatingAfterSideEffect() {
713 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000714 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000715 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000716 case EM_EvaluateForOverflow:
717 case EM_IgnoreSideEffects:
718 return true;
719
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000721 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000722 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000723 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 return false;
725 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000726 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 }
728
729 /// Note that we have had a side-effect, and determine whether we should
730 /// keep evaluating.
731 bool noteSideEffect() {
732 EvalStatus.HasSideEffects = true;
733 return keepEvaluatingAfterSideEffect();
734 }
735
Richard Smithce8eca52015-12-08 03:21:47 +0000736 /// Should we continue evaluation after encountering undefined behavior?
737 bool keepEvaluatingAfterUndefinedBehavior() {
738 switch (EvalMode) {
739 case EM_EvaluateForOverflow:
740 case EM_IgnoreSideEffects:
741 case EM_ConstantFold:
742 case EM_DesignatorFold:
743 return true;
744
745 case EM_PotentialConstantExpression:
746 case EM_PotentialConstantExpressionUnevaluated:
747 case EM_ConstantExpression:
748 case EM_ConstantExpressionUnevaluated:
749 return false;
750 }
751 llvm_unreachable("Missed EvalMode case");
752 }
753
754 /// Note that we hit something that was technically undefined behavior, but
755 /// that we can evaluate past it (such as signed overflow or floating-point
756 /// division by zero.)
757 bool noteUndefinedBehavior() {
758 EvalStatus.HasUndefinedBehavior = true;
759 return keepEvaluatingAfterUndefinedBehavior();
760 }
761
Richard Smith253c2a32012-01-27 01:14:48 +0000762 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000764 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000765 if (!StepsLeft)
766 return false;
767
768 switch (EvalMode) {
769 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000770 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 case EM_EvaluateForOverflow:
772 return true;
773
774 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000775 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 case EM_ConstantFold:
777 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000778 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000779 return false;
780 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000781 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000782 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000783
George Burgess IV8c892b52016-05-25 22:31:54 +0000784 /// Notes that we failed to evaluate an expression that other expressions
785 /// directly depend on, and determine if we should keep evaluating. This
786 /// should only be called if we actually intend to keep evaluating.
787 ///
788 /// Call noteSideEffect() instead if we may be able to ignore the value that
789 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
790 ///
791 /// (Foo(), 1) // use noteSideEffect
792 /// (Foo() || true) // use noteSideEffect
793 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000794 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000795 // Failure when evaluating some expression often means there is some
796 // subexpression whose evaluation was skipped. Therefore, (because we
797 // don't track whether we skipped an expression when unwinding after an
798 // evaluation failure) every evaluation failure that bubbles up from a
799 // subexpression implies that a side-effect has potentially happened. We
800 // skip setting the HasSideEffects flag to true until we decide to
801 // continue evaluating after that point, which happens here.
802 bool KeepGoing = keepEvaluatingAfterFailure();
803 EvalStatus.HasSideEffects |= KeepGoing;
804 return KeepGoing;
805 }
806
George Burgess IV3a03fab2015-09-04 21:28:13 +0000807 bool allowInvalidBaseExpr() const {
808 return EvalMode == EM_DesignatorFold;
809 }
Richard Smith410306b2016-12-12 02:53:20 +0000810
811 class ArrayInitLoopIndex {
812 EvalInfo &Info;
813 uint64_t OuterIndex;
814
815 public:
816 ArrayInitLoopIndex(EvalInfo &Info)
817 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
818 Info.ArrayInitIndex = 0;
819 }
820 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
821
822 operator uint64_t&() { return Info.ArrayInitIndex; }
823 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000824 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000825
826 /// Object used to treat all foldable expressions as constant expressions.
827 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000829 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000830 bool HadNoPriorDiags;
831 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000832
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 explicit FoldConstant(EvalInfo &Info, bool Enabled)
834 : Info(Info),
835 Enabled(Enabled),
836 HadNoPriorDiags(Info.EvalStatus.Diag &&
837 Info.EvalStatus.Diag->empty() &&
838 !Info.EvalStatus.HasSideEffects),
839 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000840 if (Enabled &&
841 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
842 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000843 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000844 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000845 void keepDiagnostics() { Enabled = false; }
846 ~FoldConstant() {
847 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000848 !Info.EvalStatus.HasSideEffects)
849 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000851 }
852 };
Richard Smith17100ba2012-02-16 02:46:34 +0000853
George Burgess IV3a03fab2015-09-04 21:28:13 +0000854 /// RAII object used to treat the current evaluation as the correct pointer
855 /// offset fold for the current EvalMode
856 struct FoldOffsetRAII {
857 EvalInfo &Info;
858 EvalInfo::EvaluationMode OldMode;
859 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
860 : Info(Info), OldMode(Info.EvalMode) {
861 if (!Info.checkingPotentialConstantExpression())
862 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
863 : EvalInfo::EM_ConstantFold;
864 }
865
866 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
867 };
868
George Burgess IV8c892b52016-05-25 22:31:54 +0000869 /// RAII object used to optionally suppress diagnostics and side-effects from
870 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000871 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000872 /// Pair of EvalInfo, and a bit that stores whether or not we were
873 /// speculatively evaluating when we created this RAII.
874 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000875 Expr::EvalStatus Old;
876
George Burgess IV8c892b52016-05-25 22:31:54 +0000877 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
878 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
879 Old = Other.Old;
880 Other.InfoAndOldSpecEval.setPointer(nullptr);
881 }
882
883 void maybeRestoreState() {
884 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
885 if (!Info)
886 return;
887
888 Info->EvalStatus = Old;
889 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
890 }
891
Richard Smith17100ba2012-02-16 02:46:34 +0000892 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000893 SpeculativeEvaluationRAII() = default;
894
895 SpeculativeEvaluationRAII(
896 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
897 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
898 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000899 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000900 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000901 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000902
903 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
904 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
905 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000906 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000907
908 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
909 maybeRestoreState();
910 moveFromAndCancel(std::move(Other));
911 return *this;
912 }
913
914 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000915 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000916
917 /// RAII object wrapping a full-expression or block scope, and handling
918 /// the ending of the lifetime of temporaries created within it.
919 template<bool IsFullExpression>
920 class ScopeRAII {
921 EvalInfo &Info;
922 unsigned OldStackSize;
923 public:
924 ScopeRAII(EvalInfo &Info)
925 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
926 ~ScopeRAII() {
927 // Body moved to a static method to encourage the compiler to inline away
928 // instances of this class.
929 cleanup(Info, OldStackSize);
930 }
931 private:
932 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
933 unsigned NewEnd = OldStackSize;
934 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
935 I != N; ++I) {
936 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
937 // Full-expression cleanup of a lifetime-extended temporary: nothing
938 // to do, just move this cleanup to the right place in the stack.
939 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
940 ++NewEnd;
941 } else {
942 // End the lifetime of the object.
943 Info.CleanupStack[I].endLifetime();
944 }
945 }
946 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
947 Info.CleanupStack.end());
948 }
949 };
950 typedef ScopeRAII<false> BlockScopeRAII;
951 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000952}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000953
Richard Smitha8105bc2012-01-06 16:39:00 +0000954bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Invalid)
957 return false;
958 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 setInvalid();
962 return false;
963 }
964 return true;
965}
966
967void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
968 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000969 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000971 << static_cast<int>(N) << /*array*/ 0
972 << static_cast<unsigned>(MostDerivedArraySize);
973 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000974 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 << static_cast<int>(N) << /*non-array*/ 1;
976 setInvalid();
977}
978
Richard Smithf6f003a2011-12-16 19:06:07 +0000979CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
980 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000981 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +0000982 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
983 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000984 Info.CurrentCall = this;
985 ++Info.CallStackDepth;
986}
987
988CallStackFrame::~CallStackFrame() {
989 assert(Info.CurrentCall == this && "calls retired out of order");
990 --Info.CallStackDepth;
991 Info.CurrentCall = Caller;
992}
993
Richard Smith08d6a2c2013-07-24 07:11:57 +0000994APValue &CallStackFrame::createTemporary(const void *Key,
995 bool IsLifetimeExtended) {
996 APValue &Result = Temporaries[Key];
997 assert(Result.isUninit() && "temporary created multiple times");
998 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
999 return Result;
1000}
1001
Richard Smith84401042013-06-03 05:03:02 +00001002static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001003
1004void EvalInfo::addCallStack(unsigned Limit) {
1005 // Determine which calls to skip, if any.
1006 unsigned ActiveCalls = CallStackDepth - 1;
1007 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1008 if (Limit && Limit < ActiveCalls) {
1009 SkipStart = Limit / 2 + Limit % 2;
1010 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001011 }
1012
Richard Smithf6f003a2011-12-16 19:06:07 +00001013 // Walk the call stack and add the diagnostics.
1014 unsigned CallIdx = 0;
1015 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1016 Frame = Frame->Caller, ++CallIdx) {
1017 // Skip this call?
1018 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1019 if (CallIdx == SkipStart) {
1020 // Note that we're skipping calls.
1021 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1022 << unsigned(ActiveCalls - Limit);
1023 }
1024 continue;
1025 }
1026
Richard Smith5179eb72016-06-28 19:03:57 +00001027 // Use a different note for an inheriting constructor, because from the
1028 // user's perspective it's not really a function at all.
1029 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1030 if (CD->isInheritingConstructor()) {
1031 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1032 << CD->getParent();
1033 continue;
1034 }
1035 }
1036
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001037 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001038 llvm::raw_svector_ostream Out(Buffer);
1039 describeCall(Frame, Out);
1040 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1041 }
1042}
1043
1044namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001045 struct ComplexValue {
1046 private:
1047 bool IsInt;
1048
1049 public:
1050 APSInt IntReal, IntImag;
1051 APFloat FloatReal, FloatImag;
1052
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001053 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001054
1055 void makeComplexFloat() { IsInt = false; }
1056 bool isComplexFloat() const { return !IsInt; }
1057 APFloat &getComplexFloatReal() { return FloatReal; }
1058 APFloat &getComplexFloatImag() { return FloatImag; }
1059
1060 void makeComplexInt() { IsInt = true; }
1061 bool isComplexInt() const { return IsInt; }
1062 APSInt &getComplexIntReal() { return IntReal; }
1063 APSInt &getComplexIntImag() { return IntImag; }
1064
Richard Smith2e312c82012-03-03 22:46:17 +00001065 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001066 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001067 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001068 else
Richard Smith2e312c82012-03-03 22:46:17 +00001069 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001070 }
Richard Smith2e312c82012-03-03 22:46:17 +00001071 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001072 assert(v.isComplexFloat() || v.isComplexInt());
1073 if (v.isComplexFloat()) {
1074 makeComplexFloat();
1075 FloatReal = v.getComplexFloatReal();
1076 FloatImag = v.getComplexFloatImag();
1077 } else {
1078 makeComplexInt();
1079 IntReal = v.getComplexIntReal();
1080 IntImag = v.getComplexIntImag();
1081 }
1082 }
John McCall93d91dc2010-05-07 17:22:02 +00001083 };
John McCall45d55e42010-05-07 21:00:08 +00001084
1085 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001086 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001087 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001088 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001090 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001091
Richard Smithce40ad62011-11-12 22:28:03 +00001092 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001093 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001094 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001095 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001096 SubobjectDesignator &getLValueDesignator() { return Designator; }
1097 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001098
Richard Smith2e312c82012-03-03 22:46:17 +00001099 void moveInto(APValue &V) const {
1100 if (Designator.Invalid)
Nico Weber7849eeb2016-12-14 21:38:18 +00001101 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
Richard Smith2e312c82012-03-03 22:46:17 +00001102 else
1103 V = APValue(Base, Offset, Designator.Entries,
Nico Weber7849eeb2016-12-14 21:38:18 +00001104 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001105 }
Richard Smith2e312c82012-03-03 22:46:17 +00001106 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001107 assert(V.isLValue());
1108 Base = V.getLValueBase();
1109 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001110 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001111 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001112 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001113 }
1114
Nico Weber7849eeb2016-12-14 21:38:18 +00001115 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001116 Base = B;
Nico Weber7849eeb2016-12-14 21:38:18 +00001117 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001118 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001119 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001120 Designator = SubobjectDesignator(getType(B));
1121 }
1122
George Burgess IV3a03fab2015-09-04 21:28:13 +00001123 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1124 set(B, I, true);
1125 }
1126
Richard Smitha8105bc2012-01-06 16:39:00 +00001127 // Check that this LValue is not based on a null pointer. If it is, produce
1128 // a diagnostic and mark the designator as invalid.
1129 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1130 CheckSubobjectKind CSK) {
1131 if (Designator.Invalid)
1132 return false;
Nico Weber7849eeb2016-12-14 21:38:18 +00001133 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001134 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001135 << CSK;
1136 Designator.setInvalid();
1137 return false;
1138 }
1139 return true;
1140 }
1141
1142 // Check this LValue refers to an object. If not, set the designator to be
1143 // invalid and emit a diagnostic.
1144 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001145 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001146 Designator.checkSubobject(Info, E, CSK);
1147 }
1148
1149 void addDecl(EvalInfo &Info, const Expr *E,
1150 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001151 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1152 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001153 }
1154 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001155 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1156 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001157 }
Richard Smith66c96992012-02-18 22:04:06 +00001158 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001159 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1160 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001161 }
Nico Weber7849eeb2016-12-14 21:38:18 +00001162 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
1163 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
1164 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001165 }
John McCall45d55e42010-05-07 21:00:08 +00001166 };
Richard Smith027bf112011-11-17 22:56:20 +00001167
1168 struct MemberPtr {
1169 MemberPtr() {}
1170 explicit MemberPtr(const ValueDecl *Decl) :
1171 DeclAndIsDerivedMember(Decl, false), Path() {}
1172
1173 /// The member or (direct or indirect) field referred to by this member
1174 /// pointer, or 0 if this is a null member pointer.
1175 const ValueDecl *getDecl() const {
1176 return DeclAndIsDerivedMember.getPointer();
1177 }
1178 /// Is this actually a member of some type derived from the relevant class?
1179 bool isDerivedMember() const {
1180 return DeclAndIsDerivedMember.getInt();
1181 }
1182 /// Get the class which the declaration actually lives in.
1183 const CXXRecordDecl *getContainingRecord() const {
1184 return cast<CXXRecordDecl>(
1185 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1186 }
1187
Richard Smith2e312c82012-03-03 22:46:17 +00001188 void moveInto(APValue &V) const {
1189 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001190 }
Richard Smith2e312c82012-03-03 22:46:17 +00001191 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001192 assert(V.isMemberPointer());
1193 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1194 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1195 Path.clear();
1196 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1197 Path.insert(Path.end(), P.begin(), P.end());
1198 }
1199
1200 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1201 /// whether the member is a member of some class derived from the class type
1202 /// of the member pointer.
1203 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1204 /// Path - The path of base/derived classes from the member declaration's
1205 /// class (exclusive) to the class type of the member pointer (inclusive).
1206 SmallVector<const CXXRecordDecl*, 4> Path;
1207
1208 /// Perform a cast towards the class of the Decl (either up or down the
1209 /// hierarchy).
1210 bool castBack(const CXXRecordDecl *Class) {
1211 assert(!Path.empty());
1212 const CXXRecordDecl *Expected;
1213 if (Path.size() >= 2)
1214 Expected = Path[Path.size() - 2];
1215 else
1216 Expected = getContainingRecord();
1217 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1218 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1219 // if B does not contain the original member and is not a base or
1220 // derived class of the class containing the original member, the result
1221 // of the cast is undefined.
1222 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1223 // (D::*). We consider that to be a language defect.
1224 return false;
1225 }
1226 Path.pop_back();
1227 return true;
1228 }
1229 /// Perform a base-to-derived member pointer cast.
1230 bool castToDerived(const CXXRecordDecl *Derived) {
1231 if (!getDecl())
1232 return true;
1233 if (!isDerivedMember()) {
1234 Path.push_back(Derived);
1235 return true;
1236 }
1237 if (!castBack(Derived))
1238 return false;
1239 if (Path.empty())
1240 DeclAndIsDerivedMember.setInt(false);
1241 return true;
1242 }
1243 /// Perform a derived-to-base member pointer cast.
1244 bool castToBase(const CXXRecordDecl *Base) {
1245 if (!getDecl())
1246 return true;
1247 if (Path.empty())
1248 DeclAndIsDerivedMember.setInt(true);
1249 if (isDerivedMember()) {
1250 Path.push_back(Base);
1251 return true;
1252 }
1253 return castBack(Base);
1254 }
1255 };
Richard Smith357362d2011-12-13 06:39:58 +00001256
Richard Smith7bb00672012-02-01 01:42:44 +00001257 /// Compare two member pointers, which are assumed to be of the same type.
1258 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1259 if (!LHS.getDecl() || !RHS.getDecl())
1260 return !LHS.getDecl() && !RHS.getDecl();
1261 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1262 return false;
1263 return LHS.Path == RHS.Path;
1264 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001265}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001266
Richard Smith2e312c82012-03-03 22:46:17 +00001267static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001268static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1269 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001270 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001271static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1272static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001273static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1274 EvalInfo &Info);
1275static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001276static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001277static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001278 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001279static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001280static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001281static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001282static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001283
1284//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001285// Misc utilities
1286//===----------------------------------------------------------------------===//
1287
Richard Smith84401042013-06-03 05:03:02 +00001288/// Produce a string describing the given constexpr call.
1289static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1290 unsigned ArgIndex = 0;
1291 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1292 !isa<CXXConstructorDecl>(Frame->Callee) &&
1293 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1294
1295 if (!IsMemberCall)
1296 Out << *Frame->Callee << '(';
1297
1298 if (Frame->This && IsMemberCall) {
1299 APValue Val;
1300 Frame->This->moveInto(Val);
1301 Val.printPretty(Out, Frame->Info.Ctx,
1302 Frame->This->Designator.MostDerivedType);
1303 // FIXME: Add parens around Val if needed.
1304 Out << "->" << *Frame->Callee << '(';
1305 IsMemberCall = false;
1306 }
1307
1308 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1309 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1310 if (ArgIndex > (unsigned)IsMemberCall)
1311 Out << ", ";
1312
1313 const ParmVarDecl *Param = *I;
1314 const APValue &Arg = Frame->Arguments[ArgIndex];
1315 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1316
1317 if (ArgIndex == 0 && IsMemberCall)
1318 Out << "->" << *Frame->Callee << '(';
1319 }
1320
1321 Out << ')';
1322}
1323
Richard Smithd9f663b2013-04-22 15:31:51 +00001324/// Evaluate an expression to see if it had side-effects, and discard its
1325/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001326/// \return \c true if the caller should keep evaluating.
1327static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001328 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001329 if (!Evaluate(Scratch, Info, E))
1330 // We don't need the value, but we might have skipped a side effect here.
1331 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001332 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001333}
1334
Richard Smith861b5b52013-05-07 23:34:45 +00001335/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1336/// return its existing value.
1337static int64_t getExtValue(const APSInt &Value) {
1338 return Value.isSigned() ? Value.getSExtValue()
1339 : static_cast<int64_t>(Value.getZExtValue());
1340}
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342/// Should this call expression be treated as a string literal?
1343static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001344 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001345 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1346 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1347}
1348
Richard Smithce40ad62011-11-12 22:28:03 +00001349static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001350 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1351 // constant expression of pointer type that evaluates to...
1352
1353 // ... a null pointer value, or a prvalue core constant expression of type
1354 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001355 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001356
Richard Smithce40ad62011-11-12 22:28:03 +00001357 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1358 // ... the address of an object with static storage duration,
1359 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1360 return VD->hasGlobalStorage();
1361 // ... the address of a function,
1362 return isa<FunctionDecl>(D);
1363 }
1364
1365 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001366 switch (E->getStmtClass()) {
1367 default:
1368 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001369 case Expr::CompoundLiteralExprClass: {
1370 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1371 return CLE->isFileScope() && CLE->isLValue();
1372 }
Richard Smithe6c01442013-06-05 00:46:14 +00001373 case Expr::MaterializeTemporaryExprClass:
1374 // A materialized temporary might have been lifetime-extended to static
1375 // storage duration.
1376 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001377 // A string literal has static storage duration.
1378 case Expr::StringLiteralClass:
1379 case Expr::PredefinedExprClass:
1380 case Expr::ObjCStringLiteralClass:
1381 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001382 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001383 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001384 return true;
1385 case Expr::CallExprClass:
1386 return IsStringLiteralCall(cast<CallExpr>(E));
1387 // For GCC compatibility, &&label has static storage duration.
1388 case Expr::AddrLabelExprClass:
1389 return true;
1390 // A Block literal expression may be used as the initialization value for
1391 // Block variables at global or local static scope.
1392 case Expr::BlockExprClass:
1393 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001394 case Expr::ImplicitValueInitExprClass:
1395 // FIXME:
1396 // We can never form an lvalue with an implicit value initialization as its
1397 // base through expression evaluation, so these only appear in one case: the
1398 // implicit variable declaration we invent when checking whether a constexpr
1399 // constructor can produce a constant expression. We must assume that such
1400 // an expression might be a global lvalue.
1401 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001402 }
John McCall95007602010-05-10 23:27:23 +00001403}
1404
Richard Smithb228a862012-02-15 02:18:13 +00001405static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1406 assert(Base && "no location for a null lvalue");
1407 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1408 if (VD)
1409 Info.Note(VD->getLocation(), diag::note_declared_at);
1410 else
Ted Kremenek28831752012-08-23 20:46:57 +00001411 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001412 diag::note_constexpr_temporary_here);
1413}
1414
Richard Smith80815602011-11-07 05:07:52 +00001415/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001416/// value for an address or reference constant expression. Return true if we
1417/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001418static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1419 QualType Type, const LValue &LVal) {
1420 bool IsReferenceType = Type->isReferenceType();
1421
Richard Smith357362d2011-12-13 06:39:58 +00001422 APValue::LValueBase Base = LVal.getLValueBase();
1423 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1424
Richard Smith0dea49e2012-02-18 04:58:18 +00001425 // Check that the object is a global. Note that the fake 'this' object we
1426 // manufacture when checking potential constant expressions is conservatively
1427 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001428 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001429 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001430 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001431 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001432 << IsReferenceType << !Designator.Entries.empty()
1433 << !!VD << VD;
1434 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001435 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001436 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001437 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001438 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001439 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001440 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001441 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001442 LVal.getLValueCallIndex() == 0) &&
1443 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001444
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001445 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1446 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001447 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001448 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001449 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001450
Hans Wennborg82dd8772014-06-25 22:19:48 +00001451 // A dllimport variable never acts like a constant.
1452 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001453 return false;
1454 }
1455 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1456 // __declspec(dllimport) must be handled very carefully:
1457 // We must never initialize an expression with the thunk in C++.
1458 // Doing otherwise would allow the same id-expression to yield
1459 // different addresses for the same function in different translation
1460 // units. However, this means that we must dynamically initialize the
1461 // expression with the contents of the import address table at runtime.
1462 //
1463 // The C language has no notion of ODR; furthermore, it has no notion of
1464 // dynamic initialization. This means that we are permitted to
1465 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001466 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001467 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001468 }
1469 }
1470
Richard Smitha8105bc2012-01-06 16:39:00 +00001471 // Allow address constant expressions to be past-the-end pointers. This is
1472 // an extension: the standard requires them to point to an object.
1473 if (!IsReferenceType)
1474 return true;
1475
1476 // A reference constant expression must refer to an object.
1477 if (!Base) {
1478 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001479 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001480 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001481 }
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001484 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001485 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001486 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001487 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001488 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001489 }
1490
Richard Smith80815602011-11-07 05:07:52 +00001491 return true;
1492}
1493
Richard Smithfddd3842011-12-30 21:15:51 +00001494/// Check that this core constant expression is of literal type, and if not,
1495/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001496static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001497 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001498 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001499 return true;
1500
Richard Smith7525ff62013-05-09 07:14:00 +00001501 // C++1y: A constant initializer for an object o [...] may also invoke
1502 // constexpr constructors for o and its subobjects even if those objects
1503 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001504 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001505 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001506 return true;
1507
Richard Smithfddd3842011-12-30 21:15:51 +00001508 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001509 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001510 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001511 << E->getType();
1512 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001513 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001514 return false;
1515}
1516
Richard Smith0b0a0b62011-10-29 20:57:55 +00001517/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001518/// constant expression. If not, report an appropriate diagnostic. Does not
1519/// check that the expression is of literal type.
1520static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1521 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001522 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001523 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001524 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001525 return false;
1526 }
1527
Richard Smith77be48a2014-07-31 06:31:19 +00001528 // We allow _Atomic(T) to be initialized from anything that T can be
1529 // initialized from.
1530 if (const AtomicType *AT = Type->getAs<AtomicType>())
1531 Type = AT->getValueType();
1532
Richard Smithb228a862012-02-15 02:18:13 +00001533 // Core issue 1454: For a literal constant expression of array or class type,
1534 // each subobject of its value shall have been initialized by a constant
1535 // expression.
1536 if (Value.isArray()) {
1537 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1538 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1539 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1540 Value.getArrayInitializedElt(I)))
1541 return false;
1542 }
1543 if (!Value.hasArrayFiller())
1544 return true;
1545 return CheckConstantExpression(Info, DiagLoc, EltTy,
1546 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001547 }
Richard Smithb228a862012-02-15 02:18:13 +00001548 if (Value.isUnion() && Value.getUnionField()) {
1549 return CheckConstantExpression(Info, DiagLoc,
1550 Value.getUnionField()->getType(),
1551 Value.getUnionValue());
1552 }
1553 if (Value.isStruct()) {
1554 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1555 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1556 unsigned BaseIndex = 0;
1557 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1558 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1559 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1560 Value.getStructBase(BaseIndex)))
1561 return false;
1562 }
1563 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001564 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001565 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1566 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001567 return false;
1568 }
1569 }
1570
1571 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001572 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001573 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001574 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1575 }
1576
1577 // Everything else is fine.
1578 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001579}
1580
Benjamin Kramer8407df72015-03-09 16:47:52 +00001581static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001582 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001583}
1584
1585static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001586 if (Value.CallIndex)
1587 return false;
1588 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1589 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001590}
1591
Richard Smithcecf1842011-11-01 21:06:14 +00001592static bool IsWeakLValue(const LValue &Value) {
1593 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001594 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001595}
1596
David Majnemerb5116032014-12-09 23:32:34 +00001597static bool isZeroSized(const LValue &Value) {
1598 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001599 if (Decl && isa<VarDecl>(Decl)) {
1600 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001601 if (Ty->isArrayType())
1602 return Ty->isIncompleteType() ||
1603 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001604 }
1605 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001606}
1607
Richard Smith2e312c82012-03-03 22:46:17 +00001608static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001609 // A null base expression indicates a null pointer. These are always
1610 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001611 if (!Value.getLValueBase()) {
1612 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001613 return true;
1614 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001615
Richard Smith027bf112011-11-17 22:56:20 +00001616 // We have a non-null base. These are generally known to be true, but if it's
1617 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001618 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001619 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001620 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001621}
1622
Richard Smith2e312c82012-03-03 22:46:17 +00001623static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001624 switch (Val.getKind()) {
1625 case APValue::Uninitialized:
1626 return false;
1627 case APValue::Int:
1628 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001629 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001630 case APValue::Float:
1631 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001632 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001633 case APValue::ComplexInt:
1634 Result = Val.getComplexIntReal().getBoolValue() ||
1635 Val.getComplexIntImag().getBoolValue();
1636 return true;
1637 case APValue::ComplexFloat:
1638 Result = !Val.getComplexFloatReal().isZero() ||
1639 !Val.getComplexFloatImag().isZero();
1640 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001641 case APValue::LValue:
1642 return EvalPointerValueAsBool(Val, Result);
1643 case APValue::MemberPointer:
1644 Result = Val.getMemberPointerDecl();
1645 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001646 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001647 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001648 case APValue::Struct:
1649 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001650 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001651 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001652 }
1653
Richard Smith11562c52011-10-28 17:51:58 +00001654 llvm_unreachable("unknown APValue kind");
1655}
1656
1657static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1658 EvalInfo &Info) {
1659 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001660 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001661 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001662 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001663 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001664}
1665
Richard Smith357362d2011-12-13 06:39:58 +00001666template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001667static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001668 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001669 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001670 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001671 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001672}
1673
1674static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1675 QualType SrcType, const APFloat &Value,
1676 QualType DestType, APSInt &Result) {
1677 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001678 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001679 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001680
Richard Smith357362d2011-12-13 06:39:58 +00001681 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001682 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001683 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1684 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001685 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001686 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001687}
1688
Richard Smith357362d2011-12-13 06:39:58 +00001689static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1690 QualType SrcType, QualType DestType,
1691 APFloat &Result) {
1692 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001693 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001694 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1695 APFloat::rmNearestTiesToEven, &ignored)
1696 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001697 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001698 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001699}
1700
Richard Smith911e1422012-01-30 22:27:01 +00001701static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1702 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001703 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001704 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001705 APSInt Result = Value;
1706 // Figure out if this is a truncate, extend or noop cast.
1707 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001708 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001709 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001710 return Result;
1711}
1712
Richard Smith357362d2011-12-13 06:39:58 +00001713static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1714 QualType SrcType, const APSInt &Value,
1715 QualType DestType, APFloat &Result) {
1716 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1717 if (Result.convertFromAPInt(Value, Value.isSigned(),
1718 APFloat::rmNearestTiesToEven)
1719 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001720 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001721 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001722}
1723
Richard Smith49ca8aa2013-08-06 07:09:20 +00001724static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1725 APValue &Value, const FieldDecl *FD) {
1726 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1727
1728 if (!Value.isInt()) {
1729 // Trying to store a pointer-cast-to-integer into a bitfield.
1730 // FIXME: In this case, we should provide the diagnostic for casting
1731 // a pointer to an integer.
1732 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001733 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001734 return false;
1735 }
1736
1737 APSInt &Int = Value.getInt();
1738 unsigned OldBitWidth = Int.getBitWidth();
1739 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1740 if (NewBitWidth < OldBitWidth)
1741 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1742 return true;
1743}
1744
Eli Friedman803acb32011-12-22 03:51:45 +00001745static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1746 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001747 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001748 if (!Evaluate(SVal, Info, E))
1749 return false;
1750 if (SVal.isInt()) {
1751 Res = SVal.getInt();
1752 return true;
1753 }
1754 if (SVal.isFloat()) {
1755 Res = SVal.getFloat().bitcastToAPInt();
1756 return true;
1757 }
1758 if (SVal.isVector()) {
1759 QualType VecTy = E->getType();
1760 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1761 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1762 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1763 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1764 Res = llvm::APInt::getNullValue(VecSize);
1765 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1766 APValue &Elt = SVal.getVectorElt(i);
1767 llvm::APInt EltAsInt;
1768 if (Elt.isInt()) {
1769 EltAsInt = Elt.getInt();
1770 } else if (Elt.isFloat()) {
1771 EltAsInt = Elt.getFloat().bitcastToAPInt();
1772 } else {
1773 // Don't try to handle vectors of anything other than int or float
1774 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001775 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001776 return false;
1777 }
1778 unsigned BaseEltSize = EltAsInt.getBitWidth();
1779 if (BigEndian)
1780 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1781 else
1782 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1783 }
1784 return true;
1785 }
1786 // Give up if the input isn't an int, float, or vector. For example, we
1787 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001788 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001789 return false;
1790}
1791
Richard Smith43e77732013-05-07 04:50:00 +00001792/// Perform the given integer operation, which is known to need at most BitWidth
1793/// bits, and check for overflow in the original type (if that type was not an
1794/// unsigned type).
1795template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001796static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1797 const APSInt &LHS, const APSInt &RHS,
1798 unsigned BitWidth, Operation Op,
1799 APSInt &Result) {
1800 if (LHS.isUnsigned()) {
1801 Result = Op(LHS, RHS);
1802 return true;
1803 }
Richard Smith43e77732013-05-07 04:50:00 +00001804
1805 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001806 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001807 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001808 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001809 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001810 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001811 << Result.toString(10) << E->getType();
1812 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001813 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001814 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001815 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001816}
1817
1818/// Perform the given binary integer operation.
1819static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1820 BinaryOperatorKind Opcode, APSInt RHS,
1821 APSInt &Result) {
1822 switch (Opcode) {
1823 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001824 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001825 return false;
1826 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001827 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1828 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001829 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001830 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1831 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001832 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001833 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1834 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001835 case BO_And: Result = LHS & RHS; return true;
1836 case BO_Xor: Result = LHS ^ RHS; return true;
1837 case BO_Or: Result = LHS | RHS; return true;
1838 case BO_Div:
1839 case BO_Rem:
1840 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001841 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001842 return false;
1843 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001844 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1845 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1846 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001847 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1848 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001849 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1850 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001851 return true;
1852 case BO_Shl: {
1853 if (Info.getLangOpts().OpenCL)
1854 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1855 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1856 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1857 RHS.isUnsigned());
1858 else if (RHS.isSigned() && RHS.isNegative()) {
1859 // During constant-folding, a negative shift is an opposite shift. Such
1860 // a shift is not a constant expression.
1861 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1862 RHS = -RHS;
1863 goto shift_right;
1864 }
1865 shift_left:
1866 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1867 // the shifted type.
1868 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1869 if (SA != RHS) {
1870 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1871 << RHS << E->getType() << LHS.getBitWidth();
1872 } else if (LHS.isSigned()) {
1873 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1874 // operand, and must not overflow the corresponding unsigned type.
1875 if (LHS.isNegative())
1876 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1877 else if (LHS.countLeadingZeros() < SA)
1878 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1879 }
1880 Result = LHS << SA;
1881 return true;
1882 }
1883 case BO_Shr: {
1884 if (Info.getLangOpts().OpenCL)
1885 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1886 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1887 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1888 RHS.isUnsigned());
1889 else if (RHS.isSigned() && RHS.isNegative()) {
1890 // During constant-folding, a negative shift is an opposite shift. Such a
1891 // shift is not a constant expression.
1892 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1893 RHS = -RHS;
1894 goto shift_left;
1895 }
1896 shift_right:
1897 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1898 // shifted type.
1899 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1900 if (SA != RHS)
1901 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1902 << RHS << E->getType() << LHS.getBitWidth();
1903 Result = LHS >> SA;
1904 return true;
1905 }
1906
1907 case BO_LT: Result = LHS < RHS; return true;
1908 case BO_GT: Result = LHS > RHS; return true;
1909 case BO_LE: Result = LHS <= RHS; return true;
1910 case BO_GE: Result = LHS >= RHS; return true;
1911 case BO_EQ: Result = LHS == RHS; return true;
1912 case BO_NE: Result = LHS != RHS; return true;
1913 }
1914}
1915
Richard Smith861b5b52013-05-07 23:34:45 +00001916/// Perform the given binary floating-point operation, in-place, on LHS.
1917static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1918 APFloat &LHS, BinaryOperatorKind Opcode,
1919 const APFloat &RHS) {
1920 switch (Opcode) {
1921 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001922 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001923 return false;
1924 case BO_Mul:
1925 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1926 break;
1927 case BO_Add:
1928 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1929 break;
1930 case BO_Sub:
1931 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1932 break;
1933 case BO_Div:
1934 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1935 break;
1936 }
1937
Richard Smith0c6124b2015-12-03 01:36:22 +00001938 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001939 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001940 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001941 }
Richard Smith861b5b52013-05-07 23:34:45 +00001942 return true;
1943}
1944
Richard Smitha8105bc2012-01-06 16:39:00 +00001945/// Cast an lvalue referring to a base subobject to a derived class, by
1946/// truncating the lvalue's path to the given length.
1947static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1948 const RecordDecl *TruncatedType,
1949 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001950 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001951
1952 // Check we actually point to a derived class object.
1953 if (TruncatedElements == D.Entries.size())
1954 return true;
1955 assert(TruncatedElements >= D.MostDerivedPathLength &&
1956 "not casting to a derived class");
1957 if (!Result.checkSubobject(Info, E, CSK_Derived))
1958 return false;
1959
1960 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001961 const RecordDecl *RD = TruncatedType;
1962 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001963 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001964 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1965 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001966 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001967 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001968 else
Richard Smithd62306a2011-11-10 06:34:14 +00001969 Result.Offset -= Layout.getBaseClassOffset(Base);
1970 RD = Base;
1971 }
Richard Smith027bf112011-11-17 22:56:20 +00001972 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001973 return true;
1974}
1975
John McCalld7bca762012-05-01 00:38:49 +00001976static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001977 const CXXRecordDecl *Derived,
1978 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001979 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001980 if (!RL) {
1981 if (Derived->isInvalidDecl()) return false;
1982 RL = &Info.Ctx.getASTRecordLayout(Derived);
1983 }
1984
Richard Smithd62306a2011-11-10 06:34:14 +00001985 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001986 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001987 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001988}
1989
Richard Smitha8105bc2012-01-06 16:39:00 +00001990static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001991 const CXXRecordDecl *DerivedDecl,
1992 const CXXBaseSpecifier *Base) {
1993 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1994
John McCalld7bca762012-05-01 00:38:49 +00001995 if (!Base->isVirtual())
1996 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001997
Richard Smitha8105bc2012-01-06 16:39:00 +00001998 SubobjectDesignator &D = Obj.Designator;
1999 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002000 return false;
2001
Richard Smitha8105bc2012-01-06 16:39:00 +00002002 // Extract most-derived object and corresponding type.
2003 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2004 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2005 return false;
2006
2007 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002008 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002009 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2010 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002011 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002012 return true;
2013}
2014
Richard Smith84401042013-06-03 05:03:02 +00002015static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2016 QualType Type, LValue &Result) {
2017 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2018 PathE = E->path_end();
2019 PathI != PathE; ++PathI) {
2020 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2021 *PathI))
2022 return false;
2023 Type = (*PathI)->getType();
2024 }
2025 return true;
2026}
2027
Richard Smithd62306a2011-11-10 06:34:14 +00002028/// Update LVal to refer to the given field, which must be a member of the type
2029/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002030static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002031 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002032 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002033 if (!RL) {
2034 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002035 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002036 }
Richard Smithd62306a2011-11-10 06:34:14 +00002037
2038 unsigned I = FD->getFieldIndex();
Nico Weber7849eeb2016-12-14 21:38:18 +00002039 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002040 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002041 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002042}
2043
Richard Smith1b78b3d2012-01-25 22:15:11 +00002044/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002045static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002046 LValue &LVal,
2047 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002048 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002049 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002050 return false;
2051 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002052}
2053
Richard Smithd62306a2011-11-10 06:34:14 +00002054/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002055static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2056 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002057 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2058 // extension.
2059 if (Type->isVoidType() || Type->isFunctionType()) {
2060 Size = CharUnits::One();
2061 return true;
2062 }
2063
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002064 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002066 return false;
2067 }
2068
Richard Smithd62306a2011-11-10 06:34:14 +00002069 if (!Type->isConstantSizeType()) {
2070 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002071 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002072 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002073 return false;
2074 }
2075
2076 Size = Info.Ctx.getTypeSizeInChars(Type);
2077 return true;
2078}
2079
2080/// Update a pointer value to model pointer arithmetic.
2081/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002082/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002083/// \param LVal - The pointer value to be updated.
2084/// \param EltTy - The pointee type represented by LVal.
2085/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002086static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2087 LValue &LVal, QualType EltTy,
2088 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002089 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002090 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002091 return false;
2092
Nico Weber7849eeb2016-12-14 21:38:18 +00002093 // Compute the new offset in the appropriate width.
2094 LVal.Offset += Adjustment * SizeOfPointee;
2095 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002096 return true;
2097}
2098
Richard Smith66c96992012-02-18 22:04:06 +00002099/// Update an lvalue to refer to a component of a complex number.
2100/// \param Info - Information about the ongoing evaluation.
2101/// \param LVal - The lvalue to be updated.
2102/// \param EltTy - The complex number's component type.
2103/// \param Imag - False for the real component, true for the imaginary.
2104static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2105 LValue &LVal, QualType EltTy,
2106 bool Imag) {
2107 if (Imag) {
2108 CharUnits SizeOfComponent;
2109 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2110 return false;
2111 LVal.Offset += SizeOfComponent;
2112 }
2113 LVal.addComplex(Info, E, EltTy, Imag);
2114 return true;
2115}
2116
Richard Smith27908702011-10-24 17:54:18 +00002117/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002118///
2119/// \param Info Information about the ongoing evaluation.
2120/// \param E An expression to be used when printing diagnostics.
2121/// \param VD The variable whose initializer should be obtained.
2122/// \param Frame The frame in which the variable was created. Must be null
2123/// if this variable is not local to the evaluation.
2124/// \param Result Filled in with a pointer to the value of the variable.
2125static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2126 const VarDecl *VD, CallStackFrame *Frame,
2127 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002128 // If this is a parameter to an active constexpr function call, perform
2129 // argument substitution.
2130 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002131 // Assume arguments of a potential constant expression are unknown
2132 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002133 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002134 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002135 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002136 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002137 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002138 }
Richard Smith3229b742013-05-05 21:17:10 +00002139 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002140 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002141 }
Richard Smith27908702011-10-24 17:54:18 +00002142
Richard Smithd9f663b2013-04-22 15:31:51 +00002143 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002144 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002145 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002146 if (!Result) {
2147 // Assume variables referenced within a lambda's call operator that were
2148 // not declared within the call operator are captures and during checking
2149 // of a potential constant expression, assume they are unknown constant
2150 // expressions.
2151 assert(isLambdaCallOperator(Frame->Callee) &&
2152 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2153 "missing value for local variable");
2154 if (Info.checkingPotentialConstantExpression())
2155 return false;
2156 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002157 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002158 diag::note_unimplemented_constexpr_lambda_feature_ast)
2159 << "captures not currently allowed";
2160 return false;
2161 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002162 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002163 }
2164
Richard Smithd0b4dd62011-12-19 06:19:21 +00002165 // Dig out the initializer, and use the declaration which it's attached to.
2166 const Expr *Init = VD->getAnyInitializer(VD);
2167 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002168 // If we're checking a potential constant expression, the variable could be
2169 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002170 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002171 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002172 return false;
2173 }
2174
Richard Smithd62306a2011-11-10 06:34:14 +00002175 // If we're currently evaluating the initializer of this declaration, use that
2176 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002177 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002178 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002179 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002180 }
2181
Richard Smithcecf1842011-11-01 21:06:14 +00002182 // Never evaluate the initializer of a weak variable. We can't be sure that
2183 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002184 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002185 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002186 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002187 }
Richard Smithcecf1842011-11-01 21:06:14 +00002188
Richard Smithd0b4dd62011-12-19 06:19:21 +00002189 // Check that we can fold the initializer. In C++, we will have already done
2190 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002191 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002192 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002193 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002194 Notes.size() + 1) << VD;
2195 Info.Note(VD->getLocation(), diag::note_declared_at);
2196 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002197 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002198 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002199 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002200 Notes.size() + 1) << VD;
2201 Info.Note(VD->getLocation(), diag::note_declared_at);
2202 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002203 }
Richard Smith27908702011-10-24 17:54:18 +00002204
Richard Smith3229b742013-05-05 21:17:10 +00002205 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002206 return true;
Richard Smith27908702011-10-24 17:54:18 +00002207}
2208
Richard Smith11562c52011-10-28 17:51:58 +00002209static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002210 Qualifiers Quals = T.getQualifiers();
2211 return Quals.hasConst() && !Quals.hasVolatile();
2212}
2213
Richard Smithe97cbd72011-11-11 04:05:33 +00002214/// Get the base index of the given base class within an APValue representing
2215/// the given derived class.
2216static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2217 const CXXRecordDecl *Base) {
2218 Base = Base->getCanonicalDecl();
2219 unsigned Index = 0;
2220 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2221 E = Derived->bases_end(); I != E; ++I, ++Index) {
2222 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2223 return Index;
2224 }
2225
2226 llvm_unreachable("base class missing from derived class's bases list");
2227}
2228
Richard Smith3da88fa2013-04-26 14:36:30 +00002229/// Extract the value of a character from a string literal.
2230static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2231 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002232 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2233 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2234 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002235 const StringLiteral *S = cast<StringLiteral>(Lit);
2236 const ConstantArrayType *CAT =
2237 Info.Ctx.getAsConstantArrayType(S->getType());
2238 assert(CAT && "string literal isn't an array");
2239 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002240 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002241
2242 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002243 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002244 if (Index < S->getLength())
2245 Value = S->getCodeUnit(Index);
2246 return Value;
2247}
2248
Richard Smith3da88fa2013-04-26 14:36:30 +00002249// Expand a string literal into an array of characters.
2250static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2251 APValue &Result) {
2252 const StringLiteral *S = cast<StringLiteral>(Lit);
2253 const ConstantArrayType *CAT =
2254 Info.Ctx.getAsConstantArrayType(S->getType());
2255 assert(CAT && "string literal isn't an array");
2256 QualType CharType = CAT->getElementType();
2257 assert(CharType->isIntegerType() && "unexpected character type");
2258
2259 unsigned Elts = CAT->getSize().getZExtValue();
2260 Result = APValue(APValue::UninitArray(),
2261 std::min(S->getLength(), Elts), Elts);
2262 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2263 CharType->isUnsignedIntegerType());
2264 if (Result.hasArrayFiller())
2265 Result.getArrayFiller() = APValue(Value);
2266 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2267 Value = S->getCodeUnit(I);
2268 Result.getArrayInitializedElt(I) = APValue(Value);
2269 }
2270}
2271
2272// Expand an array so that it has more than Index filled elements.
2273static void expandArray(APValue &Array, unsigned Index) {
2274 unsigned Size = Array.getArraySize();
2275 assert(Index < Size);
2276
2277 // Always at least double the number of elements for which we store a value.
2278 unsigned OldElts = Array.getArrayInitializedElts();
2279 unsigned NewElts = std::max(Index+1, OldElts * 2);
2280 NewElts = std::min(Size, std::max(NewElts, 8u));
2281
2282 // Copy the data across.
2283 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2284 for (unsigned I = 0; I != OldElts; ++I)
2285 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2286 for (unsigned I = OldElts; I != NewElts; ++I)
2287 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2288 if (NewValue.hasArrayFiller())
2289 NewValue.getArrayFiller() = Array.getArrayFiller();
2290 Array.swap(NewValue);
2291}
2292
Richard Smithb01fe402014-09-16 01:24:02 +00002293/// Determine whether a type would actually be read by an lvalue-to-rvalue
2294/// conversion. If it's of class type, we may assume that the copy operation
2295/// is trivial. Note that this is never true for a union type with fields
2296/// (because the copy always "reads" the active member) and always true for
2297/// a non-class type.
2298static bool isReadByLvalueToRvalueConversion(QualType T) {
2299 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2300 if (!RD || (RD->isUnion() && !RD->field_empty()))
2301 return true;
2302 if (RD->isEmpty())
2303 return false;
2304
2305 for (auto *Field : RD->fields())
2306 if (isReadByLvalueToRvalueConversion(Field->getType()))
2307 return true;
2308
2309 for (auto &BaseSpec : RD->bases())
2310 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2311 return true;
2312
2313 return false;
2314}
2315
2316/// Diagnose an attempt to read from any unreadable field within the specified
2317/// type, which might be a class type.
2318static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2319 QualType T) {
2320 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2321 if (!RD)
2322 return false;
2323
2324 if (!RD->hasMutableFields())
2325 return false;
2326
2327 for (auto *Field : RD->fields()) {
2328 // If we're actually going to read this field in some way, then it can't
2329 // be mutable. If we're in a union, then assigning to a mutable field
2330 // (even an empty one) can change the active member, so that's not OK.
2331 // FIXME: Add core issue number for the union case.
2332 if (Field->isMutable() &&
2333 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002334 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002335 Info.Note(Field->getLocation(), diag::note_declared_at);
2336 return true;
2337 }
2338
2339 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2340 return true;
2341 }
2342
2343 for (auto &BaseSpec : RD->bases())
2344 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2345 return true;
2346
2347 // All mutable fields were empty, and thus not actually read.
2348 return false;
2349}
2350
Richard Smith861b5b52013-05-07 23:34:45 +00002351/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002352enum AccessKinds {
2353 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002354 AK_Assign,
2355 AK_Increment,
2356 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002357};
2358
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002359namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002360/// A handle to a complete object (an object that is not a subobject of
2361/// another object).
2362struct CompleteObject {
2363 /// The value of the complete object.
2364 APValue *Value;
2365 /// The type of the complete object.
2366 QualType Type;
2367
Craig Topper36250ad2014-05-12 05:36:57 +00002368 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002369 CompleteObject(APValue *Value, QualType Type)
2370 : Value(Value), Type(Type) {
2371 assert(Value && "missing value for complete object");
2372 }
2373
Aaron Ballman67347662015-02-15 22:00:28 +00002374 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002375};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002376} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002377
Richard Smith3da88fa2013-04-26 14:36:30 +00002378/// Find the designated sub-object of an rvalue.
2379template<typename SubobjectHandler>
2380typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002381findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002382 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002383 if (Sub.Invalid)
2384 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002385 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002386 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002387 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002388 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002389 << handler.AccessKind;
2390 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002391 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002392 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002393 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002394
Richard Smith3229b742013-05-05 21:17:10 +00002395 APValue *O = Obj.Value;
2396 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002397 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002398
Richard Smithd62306a2011-11-10 06:34:14 +00002399 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002400 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2401 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002402 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002403 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002404 return handler.failed();
2405 }
2406
Richard Smith49ca8aa2013-08-06 07:09:20 +00002407 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002408 // If we are reading an object of class type, there may still be more
2409 // things we need to check: if there are any mutable subobjects, we
2410 // cannot perform this read. (This only happens when performing a trivial
2411 // copy or assignment.)
2412 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2413 diagnoseUnreadableFields(Info, E, ObjType))
2414 return handler.failed();
2415
Richard Smith49ca8aa2013-08-06 07:09:20 +00002416 if (!handler.found(*O, ObjType))
2417 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002418
Richard Smith49ca8aa2013-08-06 07:09:20 +00002419 // If we modified a bit-field, truncate it to the right width.
2420 if (handler.AccessKind != AK_Read &&
2421 LastField && LastField->isBitField() &&
2422 !truncateBitfieldValue(Info, E, *O, LastField))
2423 return false;
2424
2425 return true;
2426 }
2427
Craig Topper36250ad2014-05-12 05:36:57 +00002428 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002429 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002430 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002431 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002432 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002433 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002434 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002435 // Note, it should not be possible to form a pointer with a valid
2436 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002437 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002438 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002439 << handler.AccessKind;
2440 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002441 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002442 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002443 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002444
2445 ObjType = CAT->getElementType();
2446
Richard Smith14a94132012-02-17 03:35:37 +00002447 // An array object is represented as either an Array APValue or as an
2448 // LValue which refers to a string literal.
2449 if (O->isLValue()) {
2450 assert(I == N - 1 && "extracting subobject of character?");
2451 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 if (handler.AccessKind != AK_Read)
2453 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2454 *O);
2455 else
2456 return handler.foundString(*O, ObjType, Index);
2457 }
2458
2459 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002460 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002461 else if (handler.AccessKind != AK_Read) {
2462 expandArray(*O, Index);
2463 O = &O->getArrayInitializedElt(Index);
2464 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002465 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002466 } else if (ObjType->isAnyComplexType()) {
2467 // Next subobject is a complex number.
2468 uint64_t Index = Sub.Entries[I].ArrayIndex;
2469 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002470 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002471 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002472 << handler.AccessKind;
2473 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002474 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002475 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002476 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002477
2478 bool WasConstQualified = ObjType.isConstQualified();
2479 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2480 if (WasConstQualified)
2481 ObjType.addConst();
2482
Richard Smith66c96992012-02-18 22:04:06 +00002483 assert(I == N - 1 && "extracting subobject of scalar?");
2484 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002485 return handler.found(Index ? O->getComplexIntImag()
2486 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002487 } else {
2488 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 return handler.found(Index ? O->getComplexFloatImag()
2490 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002491 }
Richard Smithd62306a2011-11-10 06:34:14 +00002492 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002493 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002494 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002495 << Field;
2496 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002497 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002498 }
2499
Richard Smithd62306a2011-11-10 06:34:14 +00002500 // Next subobject is a class, struct or union field.
2501 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2502 if (RD->isUnion()) {
2503 const FieldDecl *UnionField = O->getUnionField();
2504 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002505 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002506 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002507 << handler.AccessKind << Field << !UnionField << UnionField;
2508 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002509 }
Richard Smithd62306a2011-11-10 06:34:14 +00002510 O = &O->getUnionValue();
2511 } else
2512 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002513
2514 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002515 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002516 if (WasConstQualified && !Field->isMutable())
2517 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002518
2519 if (ObjType.isVolatileQualified()) {
2520 if (Info.getLangOpts().CPlusPlus) {
2521 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002522 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002523 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002524 Info.Note(Field->getLocation(), diag::note_declared_at);
2525 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002526 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002527 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002528 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002529 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002530
2531 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002532 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002533 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002534 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2535 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2536 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002537
2538 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002539 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002540 if (WasConstQualified)
2541 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002542 }
2543 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002544}
2545
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002546namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002547struct ExtractSubobjectHandler {
2548 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002549 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002550
2551 static const AccessKinds AccessKind = AK_Read;
2552
2553 typedef bool result_type;
2554 bool failed() { return false; }
2555 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002556 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 return true;
2558 }
2559 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002560 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002561 return true;
2562 }
2563 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002564 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002565 return true;
2566 }
2567 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002568 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002569 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2570 return true;
2571 }
2572};
Richard Smith3229b742013-05-05 21:17:10 +00002573} // end anonymous namespace
2574
Richard Smith3da88fa2013-04-26 14:36:30 +00002575const AccessKinds ExtractSubobjectHandler::AccessKind;
2576
2577/// Extract the designated sub-object of an rvalue.
2578static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002579 const CompleteObject &Obj,
2580 const SubobjectDesignator &Sub,
2581 APValue &Result) {
2582 ExtractSubobjectHandler Handler = { Info, Result };
2583 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002584}
2585
Richard Smith3229b742013-05-05 21:17:10 +00002586namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002587struct ModifySubobjectHandler {
2588 EvalInfo &Info;
2589 APValue &NewVal;
2590 const Expr *E;
2591
2592 typedef bool result_type;
2593 static const AccessKinds AccessKind = AK_Assign;
2594
2595 bool checkConst(QualType QT) {
2596 // Assigning to a const object has undefined behavior.
2597 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002598 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002599 return false;
2600 }
2601 return true;
2602 }
2603
2604 bool failed() { return false; }
2605 bool found(APValue &Subobj, QualType SubobjType) {
2606 if (!checkConst(SubobjType))
2607 return false;
2608 // We've been given ownership of NewVal, so just swap it in.
2609 Subobj.swap(NewVal);
2610 return true;
2611 }
2612 bool found(APSInt &Value, QualType SubobjType) {
2613 if (!checkConst(SubobjType))
2614 return false;
2615 if (!NewVal.isInt()) {
2616 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002617 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002618 return false;
2619 }
2620 Value = NewVal.getInt();
2621 return true;
2622 }
2623 bool found(APFloat &Value, QualType SubobjType) {
2624 if (!checkConst(SubobjType))
2625 return false;
2626 Value = NewVal.getFloat();
2627 return true;
2628 }
2629 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2630 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2631 }
2632};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002633} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002634
Richard Smith3229b742013-05-05 21:17:10 +00002635const AccessKinds ModifySubobjectHandler::AccessKind;
2636
Richard Smith3da88fa2013-04-26 14:36:30 +00002637/// Update the designated sub-object of an rvalue to the given value.
2638static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002639 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 const SubobjectDesignator &Sub,
2641 APValue &NewVal) {
2642 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002643 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002644}
2645
Richard Smith84f6dcf2012-02-02 01:16:57 +00002646/// Find the position where two subobject designators diverge, or equivalently
2647/// the length of the common initial subsequence.
2648static unsigned FindDesignatorMismatch(QualType ObjType,
2649 const SubobjectDesignator &A,
2650 const SubobjectDesignator &B,
2651 bool &WasArrayIndex) {
2652 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2653 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002654 if (!ObjType.isNull() &&
2655 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002656 // Next subobject is an array element.
2657 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2658 WasArrayIndex = true;
2659 return I;
2660 }
Richard Smith66c96992012-02-18 22:04:06 +00002661 if (ObjType->isAnyComplexType())
2662 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2663 else
2664 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002665 } else {
2666 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2667 WasArrayIndex = false;
2668 return I;
2669 }
2670 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2671 // Next subobject is a field.
2672 ObjType = FD->getType();
2673 else
2674 // Next subobject is a base class.
2675 ObjType = QualType();
2676 }
2677 }
2678 WasArrayIndex = false;
2679 return I;
2680}
2681
2682/// Determine whether the given subobject designators refer to elements of the
2683/// same array object.
2684static bool AreElementsOfSameArray(QualType ObjType,
2685 const SubobjectDesignator &A,
2686 const SubobjectDesignator &B) {
2687 if (A.Entries.size() != B.Entries.size())
2688 return false;
2689
George Burgess IVa51c4072015-10-16 01:49:01 +00002690 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002691 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2692 // A is a subobject of the array element.
2693 return false;
2694
2695 // If A (and B) designates an array element, the last entry will be the array
2696 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2697 // of length 1' case, and the entire path must match.
2698 bool WasArrayIndex;
2699 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2700 return CommonLength >= A.Entries.size() - IsArray;
2701}
2702
Richard Smith3229b742013-05-05 21:17:10 +00002703/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002704static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2705 AccessKinds AK, const LValue &LVal,
2706 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002707 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002708 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002709 return CompleteObject();
2710 }
2711
Craig Topper36250ad2014-05-12 05:36:57 +00002712 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002713 if (LVal.CallIndex) {
2714 Frame = Info.getCallFrame(LVal.CallIndex);
2715 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002716 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002717 << AK << LVal.Base.is<const ValueDecl*>();
2718 NoteLValueLocation(Info, LVal.Base);
2719 return CompleteObject();
2720 }
Richard Smith3229b742013-05-05 21:17:10 +00002721 }
2722
2723 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2724 // is not a constant expression (even if the object is non-volatile). We also
2725 // apply this rule to C++98, in order to conform to the expected 'volatile'
2726 // semantics.
2727 if (LValType.isVolatileQualified()) {
2728 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002729 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002730 << AK << LValType;
2731 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002732 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002733 return CompleteObject();
2734 }
2735
2736 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002737 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002738 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002739
2740 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2741 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2742 // In C++11, constexpr, non-volatile variables initialized with constant
2743 // expressions are constant expressions too. Inside constexpr functions,
2744 // parameters are constant expressions even if they're non-const.
2745 // In C++1y, objects local to a constant expression (those with a Frame) are
2746 // both readable and writable inside constant expressions.
2747 // In C, such things can also be folded, although they are not ICEs.
2748 const VarDecl *VD = dyn_cast<VarDecl>(D);
2749 if (VD) {
2750 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2751 VD = VDef;
2752 }
2753 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002754 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002755 return CompleteObject();
2756 }
2757
2758 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002759 if (BaseType.isVolatileQualified()) {
2760 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002761 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002762 << AK << 1 << VD;
2763 Info.Note(VD->getLocation(), diag::note_declared_at);
2764 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002765 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002766 }
2767 return CompleteObject();
2768 }
2769
2770 // Unless we're looking at a local variable or argument in a constexpr call,
2771 // the variable we're reading must be const.
2772 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002773 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002774 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2775 // OK, we can read and modify an object if we're in the process of
2776 // evaluating its initializer, because its lifetime began in this
2777 // evaluation.
2778 } else if (AK != AK_Read) {
2779 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002780 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002781 return CompleteObject();
2782 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002783 // OK, we can read this variable.
2784 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002785 // In OpenCL if a variable is in constant address space it is a const value.
2786 if (!(BaseType.isConstQualified() ||
2787 (Info.getLangOpts().OpenCL &&
2788 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002789 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002790 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002791 Info.Note(VD->getLocation(), diag::note_declared_at);
2792 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002793 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002794 }
2795 return CompleteObject();
2796 }
2797 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2798 // We support folding of const floating-point types, in order to make
2799 // static const data members of such types (supported as an extension)
2800 // more useful.
2801 if (Info.getLangOpts().CPlusPlus11) {
2802 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2803 Info.Note(VD->getLocation(), diag::note_declared_at);
2804 } else {
2805 Info.CCEDiag(E);
2806 }
2807 } else {
2808 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002809 if (Info.checkingPotentialConstantExpression() &&
2810 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2811 // The definition of this variable could be constexpr. We can't
2812 // access it right now, but may be able to in future.
2813 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002814 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002815 Info.Note(VD->getLocation(), diag::note_declared_at);
2816 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002817 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002818 }
2819 return CompleteObject();
2820 }
2821 }
2822
2823 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2824 return CompleteObject();
2825 } else {
2826 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2827
2828 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002829 if (const MaterializeTemporaryExpr *MTE =
2830 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2831 assert(MTE->getStorageDuration() == SD_Static &&
2832 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002833
Richard Smithe6c01442013-06-05 00:46:14 +00002834 // Per C++1y [expr.const]p2:
2835 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2836 // - a [...] glvalue of integral or enumeration type that refers to
2837 // a non-volatile const object [...]
2838 // [...]
2839 // - a [...] glvalue of literal type that refers to a non-volatile
2840 // object whose lifetime began within the evaluation of e.
2841 //
2842 // C++11 misses the 'began within the evaluation of e' check and
2843 // instead allows all temporaries, including things like:
2844 // int &&r = 1;
2845 // int x = ++r;
2846 // constexpr int k = r;
2847 // Therefore we use the C++1y rules in C++11 too.
2848 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2849 const ValueDecl *ED = MTE->getExtendingDecl();
2850 if (!(BaseType.isConstQualified() &&
2851 BaseType->isIntegralOrEnumerationType()) &&
2852 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002853 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002854 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2855 return CompleteObject();
2856 }
2857
2858 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2859 assert(BaseVal && "got reference to unevaluated temporary");
2860 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002861 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002862 return CompleteObject();
2863 }
2864 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002865 BaseVal = Frame->getTemporary(Base);
2866 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002867 }
Richard Smith3229b742013-05-05 21:17:10 +00002868
2869 // Volatile temporary objects cannot be accessed in constant expressions.
2870 if (BaseType.isVolatileQualified()) {
2871 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002872 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002873 << AK << 0;
2874 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2875 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002876 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002877 }
2878 return CompleteObject();
2879 }
2880 }
2881
Richard Smith7525ff62013-05-09 07:14:00 +00002882 // During the construction of an object, it is not yet 'const'.
2883 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2884 // and this doesn't do quite the right thing for const subobjects of the
2885 // object under construction.
2886 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2887 BaseType = Info.Ctx.getCanonicalType(BaseType);
2888 BaseType.removeLocalConst();
2889 }
2890
Richard Smith6d4c6582013-11-05 22:18:15 +00002891 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002892 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002893 //
2894 // FIXME: Not all local state is mutable. Allow local constant subobjects
2895 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002896 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2897 Info.EvalStatus.HasSideEffects) ||
2898 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002899 return CompleteObject();
2900
2901 return CompleteObject(BaseVal, BaseType);
2902}
2903
Richard Smith243ef902013-05-05 23:31:59 +00002904/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2905/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2906/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002907///
2908/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002909/// \param Conv - The expression for which we are performing the conversion.
2910/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002911/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2912/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002913/// \param LVal - The glvalue on which we are attempting to perform this action.
2914/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002915static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002916 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002917 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002918 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002919 return false;
2920
Richard Smith3229b742013-05-05 21:17:10 +00002921 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002922 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002923 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002924 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2925 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2926 // initializer until now for such expressions. Such an expression can't be
2927 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00002928 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002929 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002930 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002931 }
Richard Smith3229b742013-05-05 21:17:10 +00002932 APValue Lit;
2933 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2934 return false;
2935 CompleteObject LitObj(&Lit, Base->getType());
2936 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002937 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002938 // We represent a string literal array as an lvalue pointing at the
2939 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002940 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002941 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2942 CompleteObject StrObj(&Str, Base->getType());
2943 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002944 }
Richard Smith11562c52011-10-28 17:51:58 +00002945 }
2946
Richard Smith3229b742013-05-05 21:17:10 +00002947 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2948 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002949}
2950
2951/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002952static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002953 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002954 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002955 return false;
2956
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002957 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002958 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002959 return false;
2960 }
2961
Richard Smith3229b742013-05-05 21:17:10 +00002962 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2963 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002964}
2965
Richard Smith243ef902013-05-05 23:31:59 +00002966static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2967 return T->isSignedIntegerType() &&
2968 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2969}
2970
2971namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002972struct CompoundAssignSubobjectHandler {
2973 EvalInfo &Info;
2974 const Expr *E;
2975 QualType PromotedLHSType;
2976 BinaryOperatorKind Opcode;
2977 const APValue &RHS;
2978
2979 static const AccessKinds AccessKind = AK_Assign;
2980
2981 typedef bool result_type;
2982
2983 bool checkConst(QualType QT) {
2984 // Assigning to a const object has undefined behavior.
2985 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002986 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00002987 return false;
2988 }
2989 return true;
2990 }
2991
2992 bool failed() { return false; }
2993 bool found(APValue &Subobj, QualType SubobjType) {
2994 switch (Subobj.getKind()) {
2995 case APValue::Int:
2996 return found(Subobj.getInt(), SubobjType);
2997 case APValue::Float:
2998 return found(Subobj.getFloat(), SubobjType);
2999 case APValue::ComplexInt:
3000 case APValue::ComplexFloat:
3001 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003002 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003003 return false;
3004 case APValue::LValue:
3005 return foundPointer(Subobj, SubobjType);
3006 default:
3007 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003008 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003009 return false;
3010 }
3011 }
3012 bool found(APSInt &Value, QualType SubobjType) {
3013 if (!checkConst(SubobjType))
3014 return false;
3015
3016 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3017 // We don't support compound assignment on integer-cast-to-pointer
3018 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003019 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003020 return false;
3021 }
3022
3023 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3024 SubobjType, Value);
3025 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3026 return false;
3027 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3028 return true;
3029 }
3030 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003031 return checkConst(SubobjType) &&
3032 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3033 Value) &&
3034 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3035 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003036 }
3037 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3038 if (!checkConst(SubobjType))
3039 return false;
3040
3041 QualType PointeeType;
3042 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3043 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003044
3045 if (PointeeType.isNull() || !RHS.isInt() ||
3046 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003047 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003048 return false;
3049 }
3050
Richard Smith861b5b52013-05-07 23:34:45 +00003051 int64_t Offset = getExtValue(RHS.getInt());
3052 if (Opcode == BO_Sub)
3053 Offset = -Offset;
3054
3055 LValue LVal;
3056 LVal.setFrom(Info.Ctx, Subobj);
3057 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3058 return false;
3059 LVal.moveInto(Subobj);
3060 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003061 }
3062 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3063 llvm_unreachable("shouldn't encounter string elements here");
3064 }
3065};
3066} // end anonymous namespace
3067
3068const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3069
3070/// Perform a compound assignment of LVal <op>= RVal.
3071static bool handleCompoundAssignment(
3072 EvalInfo &Info, const Expr *E,
3073 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3074 BinaryOperatorKind Opcode, const APValue &RVal) {
3075 if (LVal.Designator.Invalid)
3076 return false;
3077
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003078 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003079 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003080 return false;
3081 }
3082
3083 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3084 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3085 RVal };
3086 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3087}
3088
3089namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003090struct IncDecSubobjectHandler {
3091 EvalInfo &Info;
3092 const Expr *E;
3093 AccessKinds AccessKind;
3094 APValue *Old;
3095
3096 typedef bool result_type;
3097
3098 bool checkConst(QualType QT) {
3099 // Assigning to a const object has undefined behavior.
3100 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003101 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003102 return false;
3103 }
3104 return true;
3105 }
3106
3107 bool failed() { return false; }
3108 bool found(APValue &Subobj, QualType SubobjType) {
3109 // Stash the old value. Also clear Old, so we don't clobber it later
3110 // if we're post-incrementing a complex.
3111 if (Old) {
3112 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003113 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003114 }
3115
3116 switch (Subobj.getKind()) {
3117 case APValue::Int:
3118 return found(Subobj.getInt(), SubobjType);
3119 case APValue::Float:
3120 return found(Subobj.getFloat(), SubobjType);
3121 case APValue::ComplexInt:
3122 return found(Subobj.getComplexIntReal(),
3123 SubobjType->castAs<ComplexType>()->getElementType()
3124 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3125 case APValue::ComplexFloat:
3126 return found(Subobj.getComplexFloatReal(),
3127 SubobjType->castAs<ComplexType>()->getElementType()
3128 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3129 case APValue::LValue:
3130 return foundPointer(Subobj, SubobjType);
3131 default:
3132 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003133 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003134 return false;
3135 }
3136 }
3137 bool found(APSInt &Value, QualType SubobjType) {
3138 if (!checkConst(SubobjType))
3139 return false;
3140
3141 if (!SubobjType->isIntegerType()) {
3142 // We don't support increment / decrement on integer-cast-to-pointer
3143 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003144 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003145 return false;
3146 }
3147
3148 if (Old) *Old = APValue(Value);
3149
3150 // bool arithmetic promotes to int, and the conversion back to bool
3151 // doesn't reduce mod 2^n, so special-case it.
3152 if (SubobjType->isBooleanType()) {
3153 if (AccessKind == AK_Increment)
3154 Value = 1;
3155 else
3156 Value = !Value;
3157 return true;
3158 }
3159
3160 bool WasNegative = Value.isNegative();
3161 if (AccessKind == AK_Increment) {
3162 ++Value;
3163
3164 if (!WasNegative && Value.isNegative() &&
3165 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3166 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003167 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003168 }
3169 } else {
3170 --Value;
3171
3172 if (WasNegative && !Value.isNegative() &&
3173 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3174 unsigned BitWidth = Value.getBitWidth();
3175 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3176 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003177 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003178 }
3179 }
3180 return true;
3181 }
3182 bool found(APFloat &Value, QualType SubobjType) {
3183 if (!checkConst(SubobjType))
3184 return false;
3185
3186 if (Old) *Old = APValue(Value);
3187
3188 APFloat One(Value.getSemantics(), 1);
3189 if (AccessKind == AK_Increment)
3190 Value.add(One, APFloat::rmNearestTiesToEven);
3191 else
3192 Value.subtract(One, APFloat::rmNearestTiesToEven);
3193 return true;
3194 }
3195 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3196 if (!checkConst(SubobjType))
3197 return false;
3198
3199 QualType PointeeType;
3200 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3201 PointeeType = PT->getPointeeType();
3202 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003203 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003204 return false;
3205 }
3206
3207 LValue LVal;
3208 LVal.setFrom(Info.Ctx, Subobj);
3209 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3210 AccessKind == AK_Increment ? 1 : -1))
3211 return false;
3212 LVal.moveInto(Subobj);
3213 return true;
3214 }
3215 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3216 llvm_unreachable("shouldn't encounter string elements here");
3217 }
3218};
3219} // end anonymous namespace
3220
3221/// Perform an increment or decrement on LVal.
3222static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3223 QualType LValType, bool IsIncrement, APValue *Old) {
3224 if (LVal.Designator.Invalid)
3225 return false;
3226
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003227 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003228 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003229 return false;
3230 }
3231
3232 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3233 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3234 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3235 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3236}
3237
Richard Smithe97cbd72011-11-11 04:05:33 +00003238/// Build an lvalue for the object argument of a member function call.
3239static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3240 LValue &This) {
3241 if (Object->getType()->isPointerType())
3242 return EvaluatePointer(Object, This, Info);
3243
3244 if (Object->isGLValue())
3245 return EvaluateLValue(Object, This, Info);
3246
Richard Smithd9f663b2013-04-22 15:31:51 +00003247 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003248 return EvaluateTemporary(Object, This, Info);
3249
Faisal Valie690b7a2016-07-02 22:34:24 +00003250 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003251 return false;
3252}
3253
3254/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3255/// lvalue referring to the result.
3256///
3257/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003258/// \param LV - An lvalue referring to the base of the member pointer.
3259/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003260/// \param IncludeMember - Specifies whether the member itself is included in
3261/// the resulting LValue subobject designator. This is not possible when
3262/// creating a bound member function.
3263/// \return The field or method declaration to which the member pointer refers,
3264/// or 0 if evaluation fails.
3265static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003266 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003267 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003268 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003269 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003270 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003271 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003272 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003273
3274 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3275 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003276 if (!MemPtr.getDecl()) {
3277 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003278 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003279 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003280 }
Richard Smith253c2a32012-01-27 01:14:48 +00003281
Richard Smith027bf112011-11-17 22:56:20 +00003282 if (MemPtr.isDerivedMember()) {
3283 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003284 // The end of the derived-to-base path for the base object must match the
3285 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003286 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003287 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003288 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003289 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003290 }
Richard Smith027bf112011-11-17 22:56:20 +00003291 unsigned PathLengthToMember =
3292 LV.Designator.Entries.size() - MemPtr.Path.size();
3293 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3294 const CXXRecordDecl *LVDecl = getAsBaseClass(
3295 LV.Designator.Entries[PathLengthToMember + I]);
3296 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003297 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003298 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003299 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003300 }
Richard Smith027bf112011-11-17 22:56:20 +00003301 }
3302
3303 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003304 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003305 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003306 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003307 } else if (!MemPtr.Path.empty()) {
3308 // Extend the LValue path with the member pointer's path.
3309 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3310 MemPtr.Path.size() + IncludeMember);
3311
3312 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003313 if (const PointerType *PT = LVType->getAs<PointerType>())
3314 LVType = PT->getPointeeType();
3315 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3316 assert(RD && "member pointer access on non-class-type expression");
3317 // The first class in the path is that of the lvalue.
3318 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3319 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003320 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003321 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003322 RD = Base;
3323 }
3324 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003325 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3326 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003327 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003328 }
3329
3330 // Add the member. Note that we cannot build bound member functions here.
3331 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003332 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003333 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003334 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003335 } else if (const IndirectFieldDecl *IFD =
3336 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003337 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003338 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003339 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003340 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003341 }
Richard Smith027bf112011-11-17 22:56:20 +00003342 }
3343
3344 return MemPtr.getDecl();
3345}
3346
Richard Smith84401042013-06-03 05:03:02 +00003347static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3348 const BinaryOperator *BO,
3349 LValue &LV,
3350 bool IncludeMember = true) {
3351 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3352
3353 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003354 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003355 MemberPtr MemPtr;
3356 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3357 }
Craig Topper36250ad2014-05-12 05:36:57 +00003358 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003359 }
3360
3361 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3362 BO->getRHS(), IncludeMember);
3363}
3364
Richard Smith027bf112011-11-17 22:56:20 +00003365/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3366/// the provided lvalue, which currently refers to the base object.
3367static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3368 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003369 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003370 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003371 return false;
3372
Richard Smitha8105bc2012-01-06 16:39:00 +00003373 QualType TargetQT = E->getType();
3374 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3375 TargetQT = PT->getPointeeType();
3376
3377 // Check this cast lands within the final derived-to-base subobject path.
3378 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003379 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003380 << D.MostDerivedType << TargetQT;
3381 return false;
3382 }
3383
Richard Smith027bf112011-11-17 22:56:20 +00003384 // Check the type of the final cast. We don't need to check the path,
3385 // since a cast can only be formed if the path is unique.
3386 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003387 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3388 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003389 if (NewEntriesSize == D.MostDerivedPathLength)
3390 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3391 else
Richard Smith027bf112011-11-17 22:56:20 +00003392 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003393 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003394 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003395 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003396 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003397 }
Richard Smith027bf112011-11-17 22:56:20 +00003398
3399 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003400 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003401}
3402
Mike Stump876387b2009-10-27 22:09:17 +00003403namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003404enum EvalStmtResult {
3405 /// Evaluation failed.
3406 ESR_Failed,
3407 /// Hit a 'return' statement.
3408 ESR_Returned,
3409 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003410 ESR_Succeeded,
3411 /// Hit a 'continue' statement.
3412 ESR_Continue,
3413 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003414 ESR_Break,
3415 /// Still scanning for 'case' or 'default' statement.
3416 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003417};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003418}
Richard Smith254a73d2011-10-28 22:34:42 +00003419
Richard Smith97fcf4b2016-08-14 23:15:52 +00003420static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3421 // We don't need to evaluate the initializer for a static local.
3422 if (!VD->hasLocalStorage())
3423 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003424
Richard Smith97fcf4b2016-08-14 23:15:52 +00003425 LValue Result;
3426 Result.set(VD, Info.CurrentCall->Index);
3427 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003428
Richard Smith97fcf4b2016-08-14 23:15:52 +00003429 const Expr *InitE = VD->getInit();
3430 if (!InitE) {
3431 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3432 << false << VD->getType();
3433 Val = APValue();
3434 return false;
3435 }
Richard Smith51f03172013-06-20 03:00:05 +00003436
Richard Smith97fcf4b2016-08-14 23:15:52 +00003437 if (InitE->isValueDependent())
3438 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003439
Richard Smith97fcf4b2016-08-14 23:15:52 +00003440 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3441 // Wipe out any partially-computed value, to allow tracking that this
3442 // evaluation failed.
3443 Val = APValue();
3444 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003445 }
3446
3447 return true;
3448}
3449
Richard Smith97fcf4b2016-08-14 23:15:52 +00003450static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3451 bool OK = true;
3452
3453 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3454 OK &= EvaluateVarDecl(Info, VD);
3455
3456 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3457 for (auto *BD : DD->bindings())
3458 if (auto *VD = BD->getHoldingVar())
3459 OK &= EvaluateDecl(Info, VD);
3460
3461 return OK;
3462}
3463
3464
Richard Smith4e18ca52013-05-06 05:56:11 +00003465/// Evaluate a condition (either a variable declaration or an expression).
3466static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3467 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003468 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003469 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3470 return false;
3471 return EvaluateAsBooleanCondition(Cond, Result, Info);
3472}
3473
Richard Smith89210072016-04-04 23:29:43 +00003474namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003475/// \brief A location where the result (returned value) of evaluating a
3476/// statement should be stored.
3477struct StmtResult {
3478 /// The APValue that should be filled in with the returned value.
3479 APValue &Value;
3480 /// The location containing the result, if any (used to support RVO).
3481 const LValue *Slot;
3482};
Richard Smith89210072016-04-04 23:29:43 +00003483}
Richard Smith52a980a2015-08-28 02:43:42 +00003484
3485static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003486 const Stmt *S,
3487 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003488
3489/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003490static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003491 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003492 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003493 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003494 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003495 case ESR_Break:
3496 return ESR_Succeeded;
3497 case ESR_Succeeded:
3498 case ESR_Continue:
3499 return ESR_Continue;
3500 case ESR_Failed:
3501 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003502 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003503 return ESR;
3504 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003505 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003506}
3507
Richard Smith496ddcf2013-05-12 17:32:42 +00003508/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003509static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003510 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003511 BlockScopeRAII Scope(Info);
3512
Richard Smith496ddcf2013-05-12 17:32:42 +00003513 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003514 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003515 {
3516 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003517 if (const Stmt *Init = SS->getInit()) {
3518 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3519 if (ESR != ESR_Succeeded)
3520 return ESR;
3521 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 if (SS->getConditionVariable() &&
3523 !EvaluateDecl(Info, SS->getConditionVariable()))
3524 return ESR_Failed;
3525 if (!EvaluateInteger(SS->getCond(), Value, Info))
3526 return ESR_Failed;
3527 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003528
3529 // Find the switch case corresponding to the value of the condition.
3530 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003531 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003532 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3533 SC = SC->getNextSwitchCase()) {
3534 if (isa<DefaultStmt>(SC)) {
3535 Found = SC;
3536 continue;
3537 }
3538
3539 const CaseStmt *CS = cast<CaseStmt>(SC);
3540 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3541 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3542 : LHS;
3543 if (LHS <= Value && Value <= RHS) {
3544 Found = SC;
3545 break;
3546 }
3547 }
3548
3549 if (!Found)
3550 return ESR_Succeeded;
3551
3552 // Search the switch body for the switch case and evaluate it from there.
3553 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3554 case ESR_Break:
3555 return ESR_Succeeded;
3556 case ESR_Succeeded:
3557 case ESR_Continue:
3558 case ESR_Failed:
3559 case ESR_Returned:
3560 return ESR;
3561 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003562 // This can only happen if the switch case is nested within a statement
3563 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003565 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003566 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003567 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003568}
3569
Richard Smith254a73d2011-10-28 22:34:42 +00003570// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003571static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003572 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003573 if (!Info.nextStep(S))
3574 return ESR_Failed;
3575
Richard Smith496ddcf2013-05-12 17:32:42 +00003576 // If we're hunting down a 'case' or 'default' label, recurse through
3577 // substatements until we hit the label.
3578 if (Case) {
3579 // FIXME: We don't start the lifetime of objects whose initialization we
3580 // jump over. However, such objects must be of class type with a trivial
3581 // default constructor that initialize all subobjects, so must be empty,
3582 // so this almost never matters.
3583 switch (S->getStmtClass()) {
3584 case Stmt::CompoundStmtClass:
3585 // FIXME: Precompute which substatement of a compound statement we
3586 // would jump to, and go straight there rather than performing a
3587 // linear scan each time.
3588 case Stmt::LabelStmtClass:
3589 case Stmt::AttributedStmtClass:
3590 case Stmt::DoStmtClass:
3591 break;
3592
3593 case Stmt::CaseStmtClass:
3594 case Stmt::DefaultStmtClass:
3595 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003596 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003597 break;
3598
3599 case Stmt::IfStmtClass: {
3600 // FIXME: Precompute which side of an 'if' we would jump to, and go
3601 // straight there rather than scanning both sides.
3602 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003603
3604 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3605 // preceded by our switch label.
3606 BlockScopeRAII Scope(Info);
3607
Richard Smith496ddcf2013-05-12 17:32:42 +00003608 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3609 if (ESR != ESR_CaseNotFound || !IS->getElse())
3610 return ESR;
3611 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3612 }
3613
3614 case Stmt::WhileStmtClass: {
3615 EvalStmtResult ESR =
3616 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3617 if (ESR != ESR_Continue)
3618 return ESR;
3619 break;
3620 }
3621
3622 case Stmt::ForStmtClass: {
3623 const ForStmt *FS = cast<ForStmt>(S);
3624 EvalStmtResult ESR =
3625 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3626 if (ESR != ESR_Continue)
3627 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003628 if (FS->getInc()) {
3629 FullExpressionRAII IncScope(Info);
3630 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3631 return ESR_Failed;
3632 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003633 break;
3634 }
3635
3636 case Stmt::DeclStmtClass:
3637 // FIXME: If the variable has initialization that can't be jumped over,
3638 // bail out of any immediately-surrounding compound-statement too.
3639 default:
3640 return ESR_CaseNotFound;
3641 }
3642 }
3643
Richard Smith254a73d2011-10-28 22:34:42 +00003644 switch (S->getStmtClass()) {
3645 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003646 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003647 // Don't bother evaluating beyond an expression-statement which couldn't
3648 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003649 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003650 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003651 return ESR_Failed;
3652 return ESR_Succeeded;
3653 }
3654
Faisal Valie690b7a2016-07-02 22:34:24 +00003655 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003656 return ESR_Failed;
3657
3658 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003659 return ESR_Succeeded;
3660
Richard Smithd9f663b2013-04-22 15:31:51 +00003661 case Stmt::DeclStmtClass: {
3662 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003663 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003664 // Each declaration initialization is its own full-expression.
3665 // FIXME: This isn't quite right; if we're performing aggregate
3666 // initialization, each braced subexpression is its own full-expression.
3667 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003668 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003669 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003670 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003671 return ESR_Succeeded;
3672 }
3673
Richard Smith357362d2011-12-13 06:39:58 +00003674 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003675 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003676 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003677 if (RetExpr &&
3678 !(Result.Slot
3679 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3680 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003681 return ESR_Failed;
3682 return ESR_Returned;
3683 }
Richard Smith254a73d2011-10-28 22:34:42 +00003684
3685 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 BlockScopeRAII Scope(Info);
3687
Richard Smith254a73d2011-10-28 22:34:42 +00003688 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003689 for (const auto *BI : CS->body()) {
3690 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003691 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003692 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003693 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003694 return ESR;
3695 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003696 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003697 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003698
3699 case Stmt::IfStmtClass: {
3700 const IfStmt *IS = cast<IfStmt>(S);
3701
3702 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003703 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003704 if (const Stmt *Init = IS->getInit()) {
3705 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3706 if (ESR != ESR_Succeeded)
3707 return ESR;
3708 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003709 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003710 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003711 return ESR_Failed;
3712
3713 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3714 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3715 if (ESR != ESR_Succeeded)
3716 return ESR;
3717 }
3718 return ESR_Succeeded;
3719 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003720
3721 case Stmt::WhileStmtClass: {
3722 const WhileStmt *WS = cast<WhileStmt>(S);
3723 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003724 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003725 bool Continue;
3726 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3727 Continue))
3728 return ESR_Failed;
3729 if (!Continue)
3730 break;
3731
3732 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3733 if (ESR != ESR_Continue)
3734 return ESR;
3735 }
3736 return ESR_Succeeded;
3737 }
3738
3739 case Stmt::DoStmtClass: {
3740 const DoStmt *DS = cast<DoStmt>(S);
3741 bool Continue;
3742 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003743 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003744 if (ESR != ESR_Continue)
3745 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003746 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003747
Richard Smith08d6a2c2013-07-24 07:11:57 +00003748 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003749 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3750 return ESR_Failed;
3751 } while (Continue);
3752 return ESR_Succeeded;
3753 }
3754
3755 case Stmt::ForStmtClass: {
3756 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003757 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003758 if (FS->getInit()) {
3759 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3760 if (ESR != ESR_Succeeded)
3761 return ESR;
3762 }
3763 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003764 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003765 bool Continue = true;
3766 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3767 FS->getCond(), Continue))
3768 return ESR_Failed;
3769 if (!Continue)
3770 break;
3771
3772 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3773 if (ESR != ESR_Continue)
3774 return ESR;
3775
Richard Smith08d6a2c2013-07-24 07:11:57 +00003776 if (FS->getInc()) {
3777 FullExpressionRAII IncScope(Info);
3778 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3779 return ESR_Failed;
3780 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003781 }
3782 return ESR_Succeeded;
3783 }
3784
Richard Smith896e0d72013-05-06 06:51:17 +00003785 case Stmt::CXXForRangeStmtClass: {
3786 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003787 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003788
3789 // Initialize the __range variable.
3790 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3791 if (ESR != ESR_Succeeded)
3792 return ESR;
3793
3794 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003795 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3796 if (ESR != ESR_Succeeded)
3797 return ESR;
3798 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003799 if (ESR != ESR_Succeeded)
3800 return ESR;
3801
3802 while (true) {
3803 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003804 {
3805 bool Continue = true;
3806 FullExpressionRAII CondExpr(Info);
3807 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3808 return ESR_Failed;
3809 if (!Continue)
3810 break;
3811 }
Richard Smith896e0d72013-05-06 06:51:17 +00003812
3813 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003814 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003815 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3816 if (ESR != ESR_Succeeded)
3817 return ESR;
3818
3819 // Loop body.
3820 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3821 if (ESR != ESR_Continue)
3822 return ESR;
3823
3824 // Increment: ++__begin
3825 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3826 return ESR_Failed;
3827 }
3828
3829 return ESR_Succeeded;
3830 }
3831
Richard Smith496ddcf2013-05-12 17:32:42 +00003832 case Stmt::SwitchStmtClass:
3833 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3834
Richard Smith4e18ca52013-05-06 05:56:11 +00003835 case Stmt::ContinueStmtClass:
3836 return ESR_Continue;
3837
3838 case Stmt::BreakStmtClass:
3839 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003840
3841 case Stmt::LabelStmtClass:
3842 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3843
3844 case Stmt::AttributedStmtClass:
3845 // As a general principle, C++11 attributes can be ignored without
3846 // any semantic impact.
3847 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3848 Case);
3849
3850 case Stmt::CaseStmtClass:
3851 case Stmt::DefaultStmtClass:
3852 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003853 }
3854}
3855
Richard Smithcc36f692011-12-22 02:22:31 +00003856/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3857/// default constructor. If so, we'll fold it whether or not it's marked as
3858/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3859/// so we need special handling.
3860static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003861 const CXXConstructorDecl *CD,
3862 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003863 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3864 return false;
3865
Richard Smith66e05fe2012-01-18 05:21:49 +00003866 // Value-initialization does not call a trivial default constructor, so such a
3867 // call is a core constant expression whether or not the constructor is
3868 // constexpr.
3869 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003870 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003871 // FIXME: If DiagDecl is an implicitly-declared special member function,
3872 // we should be much more explicit about why it's not constexpr.
3873 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3874 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3875 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003876 } else {
3877 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3878 }
3879 }
3880 return true;
3881}
3882
Richard Smith357362d2011-12-13 06:39:58 +00003883/// CheckConstexprFunction - Check that a function can be called in a constant
3884/// expression.
3885static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3886 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003887 const FunctionDecl *Definition,
3888 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003889 // Potential constant expressions can contain calls to declared, but not yet
3890 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003891 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003892 Declaration->isConstexpr())
3893 return false;
3894
Richard Smith0838f3a2013-05-14 05:18:44 +00003895 // Bail out with no diagnostic if the function declaration itself is invalid.
3896 // We will have produced a relevant diagnostic while parsing it.
3897 if (Declaration->isInvalidDecl())
3898 return false;
3899
Richard Smith357362d2011-12-13 06:39:58 +00003900 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003901 if (Definition && Definition->isConstexpr() &&
3902 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003903 return true;
3904
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003905 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003906 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003907
Richard Smith5179eb72016-06-28 19:03:57 +00003908 // If this function is not constexpr because it is an inherited
3909 // non-constexpr constructor, diagnose that directly.
3910 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3911 if (CD && CD->isInheritingConstructor()) {
3912 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3913 if (!Inherited->isConstexpr())
3914 DiagDecl = CD = Inherited;
3915 }
3916
3917 // FIXME: If DiagDecl is an implicitly-declared special member function
3918 // or an inheriting constructor, we should be much more explicit about why
3919 // it's not constexpr.
3920 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003921 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003922 << CD->getInheritedConstructor().getConstructor()->getParent();
3923 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003924 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003925 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003926 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3927 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003928 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003929 }
3930 return false;
3931}
3932
Richard Smithbe6dd812014-11-19 21:27:17 +00003933/// Determine if a class has any fields that might need to be copied by a
3934/// trivial copy or move operation.
3935static bool hasFields(const CXXRecordDecl *RD) {
3936 if (!RD || RD->isEmpty())
3937 return false;
3938 for (auto *FD : RD->fields()) {
3939 if (FD->isUnnamedBitfield())
3940 continue;
3941 return true;
3942 }
3943 for (auto &Base : RD->bases())
3944 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3945 return true;
3946 return false;
3947}
3948
Richard Smithd62306a2011-11-10 06:34:14 +00003949namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003950typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003951}
3952
3953/// EvaluateArgs - Evaluate the arguments to a function call.
3954static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3955 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003956 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003957 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003958 I != E; ++I) {
3959 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3960 // If we're checking for a potential constant expression, evaluate all
3961 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003962 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003963 return false;
3964 Success = false;
3965 }
3966 }
3967 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003968}
3969
Richard Smith254a73d2011-10-28 22:34:42 +00003970/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003971static bool HandleFunctionCall(SourceLocation CallLoc,
3972 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003973 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003974 EvalInfo &Info, APValue &Result,
3975 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003976 ArgVector ArgValues(Args.size());
3977 if (!EvaluateArgs(Args, ArgValues, Info))
3978 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003979
Richard Smith253c2a32012-01-27 01:14:48 +00003980 if (!Info.CheckCallLimit(CallLoc))
3981 return false;
3982
3983 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003984
3985 // For a trivial copy or move assignment, perform an APValue copy. This is
3986 // essential for unions, where the operations performed by the assignment
3987 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003988 //
3989 // Skip this for non-union classes with no fields; in that case, the defaulted
3990 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003991 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003992 if (MD && MD->isDefaulted() &&
3993 (MD->getParent()->isUnion() ||
3994 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003995 assert(This &&
3996 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3997 LValue RHS;
3998 RHS.setFrom(Info.Ctx, ArgValues[0]);
3999 APValue RHSValue;
4000 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4001 RHS, RHSValue))
4002 return false;
4003 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4004 RHSValue))
4005 return false;
4006 This->moveInto(Result);
4007 return true;
4008 }
4009
Richard Smith52a980a2015-08-28 02:43:42 +00004010 StmtResult Ret = {Result, ResultSlot};
4011 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004012 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004013 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004014 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004015 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004016 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004017 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004018}
4019
Richard Smithd62306a2011-11-10 06:34:14 +00004020/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004021static bool HandleConstructorCall(const Expr *E, const LValue &This,
4022 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004023 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004024 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004025 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004026 if (!Info.CheckCallLimit(CallLoc))
4027 return false;
4028
Richard Smith3607ffe2012-02-13 03:54:03 +00004029 const CXXRecordDecl *RD = Definition->getParent();
4030 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004031 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004032 return false;
4033 }
4034
Richard Smith5179eb72016-06-28 19:03:57 +00004035 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004036
Richard Smith52a980a2015-08-28 02:43:42 +00004037 // FIXME: Creating an APValue just to hold a nonexistent return value is
4038 // wasteful.
4039 APValue RetVal;
4040 StmtResult Ret = {RetVal, nullptr};
4041
Richard Smith5179eb72016-06-28 19:03:57 +00004042 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004043 if (Definition->isDelegatingConstructor()) {
4044 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004045 {
4046 FullExpressionRAII InitScope(Info);
4047 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4048 return false;
4049 }
Richard Smith52a980a2015-08-28 02:43:42 +00004050 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004051 }
4052
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004053 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004054 // essential for unions (or classes with anonymous union members), where the
4055 // operations performed by the constructor cannot be represented by
4056 // ctor-initializers.
4057 //
4058 // Skip this for empty non-union classes; we should not perform an
4059 // lvalue-to-rvalue conversion on them because their copy constructor does not
4060 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004061 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004062 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004063 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004064 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004065 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004066 return handleLValueToRValueConversion(
4067 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4068 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004069 }
4070
4071 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004072 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004073 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004074 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004075
John McCalld7bca762012-05-01 00:38:49 +00004076 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4078
Richard Smith08d6a2c2013-07-24 07:11:57 +00004079 // A scope for temporaries lifetime-extended by reference members.
4080 BlockScopeRAII LifetimeExtendedScope(Info);
4081
Richard Smith253c2a32012-01-27 01:14:48 +00004082 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004083 unsigned BasesSeen = 0;
4084#ifndef NDEBUG
4085 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4086#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004087 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004088 LValue Subobject = This;
4089 APValue *Value = &Result;
4090
4091 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004092 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004093 if (I->isBaseInitializer()) {
4094 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004095#ifndef NDEBUG
4096 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004097 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004098 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4099 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4100 "base class initializers not in expected order");
4101 ++BaseIt;
4102#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004103 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004104 BaseType->getAsCXXRecordDecl(), &Layout))
4105 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004106 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004107 } else if ((FD = I->getMember())) {
4108 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004109 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004110 if (RD->isUnion()) {
4111 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004112 Value = &Result.getUnionValue();
4113 } else {
4114 Value = &Result.getStructField(FD->getFieldIndex());
4115 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004116 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004117 // Walk the indirect field decl's chain to find the object to initialize,
4118 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004119 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004120 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004121 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4122 // Switch the union field if it differs. This happens if we had
4123 // preceding zero-initialization, and we're now initializing a union
4124 // subobject other than the first.
4125 // FIXME: In this case, the values of the other subobjects are
4126 // specified, since zero-initialization sets all padding bits to zero.
4127 if (Value->isUninit() ||
4128 (Value->isUnion() && Value->getUnionField() != FD)) {
4129 if (CD->isUnion())
4130 *Value = APValue(FD);
4131 else
4132 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004133 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004134 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004135 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004136 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004137 if (CD->isUnion())
4138 Value = &Value->getUnionValue();
4139 else
4140 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004141 }
Richard Smithd62306a2011-11-10 06:34:14 +00004142 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004143 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004144 }
Richard Smith253c2a32012-01-27 01:14:48 +00004145
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004147 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4148 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004149 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004150 // If we're checking for a potential constant expression, evaluate all
4151 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004152 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004153 return false;
4154 Success = false;
4155 }
Richard Smithd62306a2011-11-10 06:34:14 +00004156 }
4157
Richard Smithd9f663b2013-04-22 15:31:51 +00004158 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004159 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004160}
4161
Richard Smith5179eb72016-06-28 19:03:57 +00004162static bool HandleConstructorCall(const Expr *E, const LValue &This,
4163 ArrayRef<const Expr*> Args,
4164 const CXXConstructorDecl *Definition,
4165 EvalInfo &Info, APValue &Result) {
4166 ArgVector ArgValues(Args.size());
4167 if (!EvaluateArgs(Args, ArgValues, Info))
4168 return false;
4169
4170 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4171 Info, Result);
4172}
4173
Eli Friedman9a156e52008-11-12 09:44:48 +00004174//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004175// Generic Evaluation
4176//===----------------------------------------------------------------------===//
4177namespace {
4178
Aaron Ballman68af21c2014-01-03 19:26:43 +00004179template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004180class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004181 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004182private:
Richard Smith52a980a2015-08-28 02:43:42 +00004183 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004184 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004185 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004186 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004187 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004188 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004189 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004190
Richard Smith17100ba2012-02-16 02:46:34 +00004191 // Check whether a conditional operator with a non-constant condition is a
4192 // potential constant expression. If neither arm is a potential constant
4193 // expression, then the conditional operator is not either.
4194 template<typename ConditionalOperator>
4195 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004196 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004197
4198 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004199 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004200 {
Richard Smith17100ba2012-02-16 02:46:34 +00004201 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004202 StmtVisitorTy::Visit(E->getFalseExpr());
4203 if (Diag.empty())
4204 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004205 }
Richard Smith17100ba2012-02-16 02:46:34 +00004206
George Burgess IV8c892b52016-05-25 22:31:54 +00004207 {
4208 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004209 Diag.clear();
4210 StmtVisitorTy::Visit(E->getTrueExpr());
4211 if (Diag.empty())
4212 return;
4213 }
4214
4215 Error(E, diag::note_constexpr_conditional_never_const);
4216 }
4217
4218
4219 template<typename ConditionalOperator>
4220 bool HandleConditionalOperator(const ConditionalOperator *E) {
4221 bool BoolResult;
4222 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004223 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004224 CheckPotentialConstantConditional(E);
4225 return false;
4226 }
4227
4228 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4229 return StmtVisitorTy::Visit(EvalExpr);
4230 }
4231
Peter Collingbournee9200682011-05-13 03:29:01 +00004232protected:
4233 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004234 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004235 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4236
Richard Smith92b1ce02011-12-12 09:28:41 +00004237 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004238 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004239 }
4240
Aaron Ballman68af21c2014-01-03 19:26:43 +00004241 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004242
4243public:
4244 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4245
4246 EvalInfo &getEvalInfo() { return Info; }
4247
Richard Smithf57d8cb2011-12-09 22:58:01 +00004248 /// Report an evaluation error. This should only be called when an error is
4249 /// first discovered. When propagating an error, just return false.
4250 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004251 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004252 return false;
4253 }
4254 bool Error(const Expr *E) {
4255 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4256 }
4257
Aaron Ballman68af21c2014-01-03 19:26:43 +00004258 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004259 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004260 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004261 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004262 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004263 }
4264
Aaron Ballman68af21c2014-01-03 19:26:43 +00004265 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004266 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004267 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004268 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004269 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004270 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004271 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004272 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004273 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004274 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004275 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004276 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004277 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004278 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004279 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004280 // The initializer may not have been parsed yet, or might be erroneous.
4281 if (!E->getExpr())
4282 return Error(E);
4283 return StmtVisitorTy::Visit(E->getExpr());
4284 }
Richard Smith5894a912011-12-19 22:12:41 +00004285 // We cannot create any objects for which cleanups are required, so there is
4286 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004287 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004288 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004289
Aaron Ballman68af21c2014-01-03 19:26:43 +00004290 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004291 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4292 return static_cast<Derived*>(this)->VisitCastExpr(E);
4293 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004294 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004295 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4296 return static_cast<Derived*>(this)->VisitCastExpr(E);
4297 }
4298
Aaron Ballman68af21c2014-01-03 19:26:43 +00004299 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004300 switch (E->getOpcode()) {
4301 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004302 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004303
4304 case BO_Comma:
4305 VisitIgnoredValue(E->getLHS());
4306 return StmtVisitorTy::Visit(E->getRHS());
4307
4308 case BO_PtrMemD:
4309 case BO_PtrMemI: {
4310 LValue Obj;
4311 if (!HandleMemberPointerAccess(Info, E, Obj))
4312 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004313 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004314 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004315 return false;
4316 return DerivedSuccess(Result, E);
4317 }
4318 }
4319 }
4320
Aaron Ballman68af21c2014-01-03 19:26:43 +00004321 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004322 // Evaluate and cache the common expression. We treat it as a temporary,
4323 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004324 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004325 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004326 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004327
Richard Smith17100ba2012-02-16 02:46:34 +00004328 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004329 }
4330
Aaron Ballman68af21c2014-01-03 19:26:43 +00004331 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004332 bool IsBcpCall = false;
4333 // If the condition (ignoring parens) is a __builtin_constant_p call,
4334 // the result is a constant expression if it can be folded without
4335 // side-effects. This is an important GNU extension. See GCC PR38377
4336 // for discussion.
4337 if (const CallExpr *CallCE =
4338 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004339 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004340 IsBcpCall = true;
4341
4342 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4343 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004344 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004345 return false;
4346
Richard Smith6d4c6582013-11-05 22:18:15 +00004347 FoldConstant Fold(Info, IsBcpCall);
4348 if (!HandleConditionalOperator(E)) {
4349 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004350 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004351 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004352
4353 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 }
4355
Aaron Ballman68af21c2014-01-03 19:26:43 +00004356 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004357 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4358 return DerivedSuccess(*Value, E);
4359
4360 const Expr *Source = E->getSourceExpr();
4361 if (!Source)
4362 return Error(E);
4363 if (Source == E) { // sanity checking.
4364 assert(0 && "OpaqueValueExpr recursively refers to itself");
4365 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004366 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004367 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004368 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004369
Aaron Ballman68af21c2014-01-03 19:26:43 +00004370 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004371 APValue Result;
4372 if (!handleCallExpr(E, Result, nullptr))
4373 return false;
4374 return DerivedSuccess(Result, E);
4375 }
4376
4377 bool handleCallExpr(const CallExpr *E, APValue &Result,
4378 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004379 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004380 QualType CalleeType = Callee->getType();
4381
Craig Topper36250ad2014-05-12 05:36:57 +00004382 const FunctionDecl *FD = nullptr;
4383 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004384 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004385 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004386
Richard Smithe97cbd72011-11-11 04:05:33 +00004387 // Extract function decl and 'this' pointer from the callee.
4388 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004389 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004390 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4391 // Explicit bound member calls, such as x.f() or p->g();
4392 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004393 return false;
4394 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004395 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004396 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004397 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4398 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004399 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4400 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004401 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004402 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004403 return Error(Callee);
4404
4405 FD = dyn_cast<FunctionDecl>(Member);
4406 if (!FD)
4407 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004408 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004409 LValue Call;
4410 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004411 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004412
Richard Smitha8105bc2012-01-06 16:39:00 +00004413 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004414 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004415 FD = dyn_cast_or_null<FunctionDecl>(
4416 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004417 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004418 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004419
4420 // Overloaded operator calls to member functions are represented as normal
4421 // calls with '*this' as the first argument.
4422 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4423 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004424 // FIXME: When selecting an implicit conversion for an overloaded
4425 // operator delete, we sometimes try to evaluate calls to conversion
4426 // operators without a 'this' parameter!
4427 if (Args.empty())
4428 return Error(E);
4429
Richard Smithe97cbd72011-11-11 04:05:33 +00004430 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4431 return false;
4432 This = &ThisVal;
4433 Args = Args.slice(1);
4434 }
4435
4436 // Don't call function pointers which have been cast to some other type.
Richard Smithdfe85e22016-12-15 02:35:39 +00004437 // Per DR (no number yet), the caller and callee can differ in noexcept.
4438 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4439 CalleeType->getPointeeType(), FD->getType())) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004440 return Error(E);
Richard Smithdfe85e22016-12-15 02:35:39 +00004441 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004442 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004443 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004444
Richard Smith47b34932012-02-01 02:39:43 +00004445 if (This && !This->checkSubobject(Info, E, CSK_This))
4446 return false;
4447
Richard Smith3607ffe2012-02-13 03:54:03 +00004448 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4449 // calls to such functions in constant expressions.
4450 if (This && !HasQualifier &&
4451 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4452 return Error(E, diag::note_constexpr_virtual_call);
4453
Craig Topper36250ad2014-05-12 05:36:57 +00004454 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004455 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004456
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004457 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004458 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4459 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004460 return false;
4461
Richard Smith52a980a2015-08-28 02:43:42 +00004462 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004463 }
4464
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004466 return StmtVisitorTy::Visit(E->getInitializer());
4467 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004468 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004469 if (E->getNumInits() == 0)
4470 return DerivedZeroInitialization(E);
4471 if (E->getNumInits() == 1)
4472 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004473 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004474 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004475 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004476 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004477 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004478 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004479 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004480 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004481 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004482 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004483 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004484
Richard Smithd62306a2011-11-10 06:34:14 +00004485 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004486 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004487 assert(!E->isArrow() && "missing call to bound member function?");
4488
Richard Smith2e312c82012-03-03 22:46:17 +00004489 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004490 if (!Evaluate(Val, Info, E->getBase()))
4491 return false;
4492
4493 QualType BaseTy = E->getBase()->getType();
4494
4495 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004496 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004497 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004498 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004499 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4500
Richard Smith3229b742013-05-05 21:17:10 +00004501 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004502 SubobjectDesignator Designator(BaseTy);
4503 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004504
Richard Smith3229b742013-05-05 21:17:10 +00004505 APValue Result;
4506 return extractSubobject(Info, E, Obj, Designator, Result) &&
4507 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004508 }
4509
Aaron Ballman68af21c2014-01-03 19:26:43 +00004510 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004511 switch (E->getCastKind()) {
4512 default:
4513 break;
4514
Richard Smitha23ab512013-05-23 00:30:41 +00004515 case CK_AtomicToNonAtomic: {
4516 APValue AtomicVal;
4517 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4518 return false;
4519 return DerivedSuccess(AtomicVal, E);
4520 }
4521
Richard Smith11562c52011-10-28 17:51:58 +00004522 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004523 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004524 return StmtVisitorTy::Visit(E->getSubExpr());
4525
4526 case CK_LValueToRValue: {
4527 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004528 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4529 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004530 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004531 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004532 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004533 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004534 return false;
4535 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004536 }
4537 }
4538
Richard Smithf57d8cb2011-12-09 22:58:01 +00004539 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004540 }
4541
Aaron Ballman68af21c2014-01-03 19:26:43 +00004542 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004543 return VisitUnaryPostIncDec(UO);
4544 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004545 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004546 return VisitUnaryPostIncDec(UO);
4547 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004548 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004549 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004550 return Error(UO);
4551
4552 LValue LVal;
4553 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4554 return false;
4555 APValue RVal;
4556 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4557 UO->isIncrementOp(), &RVal))
4558 return false;
4559 return DerivedSuccess(RVal, UO);
4560 }
4561
Aaron Ballman68af21c2014-01-03 19:26:43 +00004562 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004563 // We will have checked the full-expressions inside the statement expression
4564 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004565 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004566 return Error(E);
4567
Richard Smith08d6a2c2013-07-24 07:11:57 +00004568 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004569 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004570 if (CS->body_empty())
4571 return true;
4572
Richard Smith51f03172013-06-20 03:00:05 +00004573 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4574 BE = CS->body_end();
4575 /**/; ++BI) {
4576 if (BI + 1 == BE) {
4577 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4578 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004579 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004580 diag::note_constexpr_stmt_expr_unsupported);
4581 return false;
4582 }
4583 return this->Visit(FinalExpr);
4584 }
4585
4586 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004587 StmtResult Result = { ReturnValue, nullptr };
4588 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004589 if (ESR != ESR_Succeeded) {
4590 // FIXME: If the statement-expression terminated due to 'return',
4591 // 'break', or 'continue', it would be nice to propagate that to
4592 // the outer statement evaluation rather than bailing out.
4593 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004594 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004595 diag::note_constexpr_stmt_expr_unsupported);
4596 return false;
4597 }
4598 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004599
4600 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004601 }
4602
Richard Smith4a678122011-10-24 18:44:57 +00004603 /// Visit a value which is evaluated, but whose value is ignored.
4604 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004605 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004606 }
David Majnemere9807b22016-02-26 04:23:19 +00004607
4608 /// Potentially visit a MemberExpr's base expression.
4609 void VisitIgnoredBaseExpression(const Expr *E) {
4610 // While MSVC doesn't evaluate the base expression, it does diagnose the
4611 // presence of side-effecting behavior.
4612 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4613 return;
4614 VisitIgnoredValue(E);
4615 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004616};
4617
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004618}
Peter Collingbournee9200682011-05-13 03:29:01 +00004619
4620//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004621// Common base class for lvalue and temporary evaluation.
4622//===----------------------------------------------------------------------===//
4623namespace {
4624template<class Derived>
4625class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004626 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004627protected:
4628 LValue &Result;
4629 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004630 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004631
4632 bool Success(APValue::LValueBase B) {
4633 Result.set(B);
4634 return true;
4635 }
4636
4637public:
4638 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4639 ExprEvaluatorBaseTy(Info), Result(Result) {}
4640
Richard Smith2e312c82012-03-03 22:46:17 +00004641 bool Success(const APValue &V, const Expr *E) {
4642 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004643 return true;
4644 }
Richard Smith027bf112011-11-17 22:56:20 +00004645
Richard Smith027bf112011-11-17 22:56:20 +00004646 bool VisitMemberExpr(const MemberExpr *E) {
4647 // Handle non-static data members.
4648 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004649 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004650 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004651 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004652 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004653 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004654 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004655 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004656 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004657 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004658 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004659 BaseTy = E->getBase()->getType();
4660 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004661 if (!EvalOK) {
4662 if (!this->Info.allowInvalidBaseExpr())
4663 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004664 Result.setInvalid(E);
4665 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004666 }
Richard Smith027bf112011-11-17 22:56:20 +00004667
Richard Smith1b78b3d2012-01-25 22:15:11 +00004668 const ValueDecl *MD = E->getMemberDecl();
4669 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4670 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4671 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4672 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004673 if (!HandleLValueMember(this->Info, E, Result, FD))
4674 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004675 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004676 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4677 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004678 } else
4679 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004680
Richard Smith1b78b3d2012-01-25 22:15:11 +00004681 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004682 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004683 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004684 RefValue))
4685 return false;
4686 return Success(RefValue, E);
4687 }
4688 return true;
4689 }
4690
4691 bool VisitBinaryOperator(const BinaryOperator *E) {
4692 switch (E->getOpcode()) {
4693 default:
4694 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4695
4696 case BO_PtrMemD:
4697 case BO_PtrMemI:
4698 return HandleMemberPointerAccess(this->Info, E, Result);
4699 }
4700 }
4701
4702 bool VisitCastExpr(const CastExpr *E) {
4703 switch (E->getCastKind()) {
4704 default:
4705 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4706
4707 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004708 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004709 if (!this->Visit(E->getSubExpr()))
4710 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004711
4712 // Now figure out the necessary offset to add to the base LV to get from
4713 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004714 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4715 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004716 }
4717 }
4718};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004719}
Richard Smith027bf112011-11-17 22:56:20 +00004720
4721//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004722// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004723//
4724// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4725// function designators (in C), decl references to void objects (in C), and
4726// temporaries (if building with -Wno-address-of-temporary).
4727//
4728// LValue evaluation produces values comprising a base expression of one of the
4729// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004730// - Declarations
4731// * VarDecl
4732// * FunctionDecl
4733// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004734// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004735// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004736// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004737// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004738// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004739// * ObjCEncodeExpr
4740// * AddrLabelExpr
4741// * BlockExpr
4742// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004743// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004744// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004745// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004746// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4747// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004748// * A MaterializeTemporaryExpr that has static storage duration, with no
4749// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004750// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004751//===----------------------------------------------------------------------===//
4752namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004753class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004754 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004755public:
Richard Smith027bf112011-11-17 22:56:20 +00004756 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4757 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004758
Richard Smith11562c52011-10-28 17:51:58 +00004759 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004760 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004761
Peter Collingbournee9200682011-05-13 03:29:01 +00004762 bool VisitDeclRefExpr(const DeclRefExpr *E);
4763 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004764 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004765 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4766 bool VisitMemberExpr(const MemberExpr *E);
4767 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4768 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004769 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004770 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004771 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4772 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004773 bool VisitUnaryReal(const UnaryOperator *E);
4774 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004775 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4776 return VisitUnaryPreIncDec(UO);
4777 }
4778 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4779 return VisitUnaryPreIncDec(UO);
4780 }
Richard Smith3229b742013-05-05 21:17:10 +00004781 bool VisitBinAssign(const BinaryOperator *BO);
4782 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004783
Peter Collingbournee9200682011-05-13 03:29:01 +00004784 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004785 switch (E->getCastKind()) {
4786 default:
Richard Smith027bf112011-11-17 22:56:20 +00004787 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004788
Eli Friedmance3e02a2011-10-11 00:13:24 +00004789 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004790 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004791 if (!Visit(E->getSubExpr()))
4792 return false;
4793 Result.Designator.setInvalid();
4794 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004795
Richard Smith027bf112011-11-17 22:56:20 +00004796 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004797 if (!Visit(E->getSubExpr()))
4798 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004799 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004800 }
4801 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004802};
4803} // end anonymous namespace
4804
Richard Smith11562c52011-10-28 17:51:58 +00004805/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004806/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004807/// * function designators in C, and
4808/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004809/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004810static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4811 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004812 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004813 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004814}
4815
Peter Collingbournee9200682011-05-13 03:29:01 +00004816bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004817 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004818 return Success(FD);
4819 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004820 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004821 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004822 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004823 return Error(E);
4824}
Richard Smith733237d2011-10-24 23:14:33 +00004825
Faisal Vali0528a312016-11-13 06:09:16 +00004826
Richard Smith11562c52011-10-28 17:51:58 +00004827bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004828 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004829 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4830 // Only if a local variable was declared in the function currently being
4831 // evaluated, do we expect to be able to find its value in the current
4832 // frame. (Otherwise it was likely declared in an enclosing context and
4833 // could either have a valid evaluatable value (for e.g. a constexpr
4834 // variable) or be ill-formed (and trigger an appropriate evaluation
4835 // diagnostic)).
4836 if (Info.CurrentCall->Callee &&
4837 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4838 Frame = Info.CurrentCall;
4839 }
4840 }
Richard Smith3229b742013-05-05 21:17:10 +00004841
Richard Smithfec09922011-11-01 16:57:24 +00004842 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004843 if (Frame) {
4844 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004845 return true;
4846 }
Richard Smithce40ad62011-11-12 22:28:03 +00004847 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004848 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004849
Richard Smith3229b742013-05-05 21:17:10 +00004850 APValue *V;
4851 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004852 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004853 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004854 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004855 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004856 return false;
4857 }
Richard Smith3229b742013-05-05 21:17:10 +00004858 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004859}
4860
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004861bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4862 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004863 // Walk through the expression to find the materialized temporary itself.
4864 SmallVector<const Expr *, 2> CommaLHSs;
4865 SmallVector<SubobjectAdjustment, 2> Adjustments;
4866 const Expr *Inner = E->GetTemporaryExpr()->
4867 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004868
Richard Smith84401042013-06-03 05:03:02 +00004869 // If we passed any comma operators, evaluate their LHSs.
4870 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4871 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4872 return false;
4873
Richard Smithe6c01442013-06-05 00:46:14 +00004874 // A materialized temporary with static storage duration can appear within the
4875 // result of a constant expression evaluation, so we need to preserve its
4876 // value for use outside this evaluation.
4877 APValue *Value;
4878 if (E->getStorageDuration() == SD_Static) {
4879 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004880 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004881 Result.set(E);
4882 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004883 Value = &Info.CurrentCall->
4884 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004885 Result.set(E, Info.CurrentCall->Index);
4886 }
4887
Richard Smithea4ad5d2013-06-06 08:19:16 +00004888 QualType Type = Inner->getType();
4889
Richard Smith84401042013-06-03 05:03:02 +00004890 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004891 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4892 (E->getStorageDuration() == SD_Static &&
4893 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4894 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004895 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004896 }
Richard Smith84401042013-06-03 05:03:02 +00004897
4898 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004899 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4900 --I;
4901 switch (Adjustments[I].Kind) {
4902 case SubobjectAdjustment::DerivedToBaseAdjustment:
4903 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4904 Type, Result))
4905 return false;
4906 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4907 break;
4908
4909 case SubobjectAdjustment::FieldAdjustment:
4910 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4911 return false;
4912 Type = Adjustments[I].Field->getType();
4913 break;
4914
4915 case SubobjectAdjustment::MemberPointerAdjustment:
4916 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4917 Adjustments[I].Ptr.RHS))
4918 return false;
4919 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4920 break;
4921 }
4922 }
4923
4924 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004925}
4926
Peter Collingbournee9200682011-05-13 03:29:01 +00004927bool
4928LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00004929 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
4930 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00004931 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4932 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004933 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004934}
4935
Richard Smith6e525142011-12-27 12:18:28 +00004936bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004937 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004938 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004939
Faisal Valie690b7a2016-07-02 22:34:24 +00004940 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004941 << E->getExprOperand()->getType()
4942 << E->getExprOperand()->getSourceRange();
4943 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004944}
4945
Francois Pichet0066db92012-04-16 04:08:35 +00004946bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4947 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004948}
Francois Pichet0066db92012-04-16 04:08:35 +00004949
Peter Collingbournee9200682011-05-13 03:29:01 +00004950bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004951 // Handle static data members.
4952 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004953 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004954 return VisitVarDecl(E, VD);
4955 }
4956
Richard Smith254a73d2011-10-28 22:34:42 +00004957 // Handle static member functions.
4958 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4959 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004960 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004961 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004962 }
4963 }
4964
Richard Smithd62306a2011-11-10 06:34:14 +00004965 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004966 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004967}
4968
Peter Collingbournee9200682011-05-13 03:29:01 +00004969bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004970 // FIXME: Deal with vectors as array subscript bases.
4971 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004972 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004973
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004974 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004975 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004976
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004977 APSInt Index;
4978 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004979 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004980
Richard Smith861b5b52013-05-07 23:34:45 +00004981 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4982 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004983}
Eli Friedman9a156e52008-11-12 09:44:48 +00004984
Peter Collingbournee9200682011-05-13 03:29:01 +00004985bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004986 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004987}
4988
Richard Smith66c96992012-02-18 22:04:06 +00004989bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4990 if (!Visit(E->getSubExpr()))
4991 return false;
4992 // __real is a no-op on scalar lvalues.
4993 if (E->getSubExpr()->getType()->isAnyComplexType())
4994 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4995 return true;
4996}
4997
4998bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4999 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5000 "lvalue __imag__ on scalar?");
5001 if (!Visit(E->getSubExpr()))
5002 return false;
5003 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5004 return true;
5005}
5006
Richard Smith243ef902013-05-05 23:31:59 +00005007bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005008 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005009 return Error(UO);
5010
5011 if (!this->Visit(UO->getSubExpr()))
5012 return false;
5013
Richard Smith243ef902013-05-05 23:31:59 +00005014 return handleIncDec(
5015 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005016 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005017}
5018
5019bool LValueExprEvaluator::VisitCompoundAssignOperator(
5020 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005021 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005022 return Error(CAO);
5023
Richard Smith3229b742013-05-05 21:17:10 +00005024 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005025
5026 // The overall lvalue result is the result of evaluating the LHS.
5027 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005028 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005029 Evaluate(RHS, this->Info, CAO->getRHS());
5030 return false;
5031 }
5032
Richard Smith3229b742013-05-05 21:17:10 +00005033 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5034 return false;
5035
Richard Smith43e77732013-05-07 04:50:00 +00005036 return handleCompoundAssignment(
5037 this->Info, CAO,
5038 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5039 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005040}
5041
5042bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005043 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005044 return Error(E);
5045
Richard Smith3229b742013-05-05 21:17:10 +00005046 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005047
5048 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005049 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005050 Evaluate(NewVal, this->Info, E->getRHS());
5051 return false;
5052 }
5053
Richard Smith3229b742013-05-05 21:17:10 +00005054 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5055 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005056
5057 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005058 NewVal);
5059}
5060
Eli Friedman9a156e52008-11-12 09:44:48 +00005061//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005062// Pointer Evaluation
5063//===----------------------------------------------------------------------===//
5064
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005065namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005066class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005067 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005068 LValue &Result;
5069
Peter Collingbournee9200682011-05-13 03:29:01 +00005070 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005071 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005072 return true;
5073 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005074public:
Mike Stump11289f42009-09-09 15:08:12 +00005075
John McCall45d55e42010-05-07 21:00:08 +00005076 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005077 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005078
Richard Smith2e312c82012-03-03 22:46:17 +00005079 bool Success(const APValue &V, const Expr *E) {
5080 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005081 return true;
5082 }
Richard Smithfddd3842011-12-30 21:15:51 +00005083 bool ZeroInitialization(const Expr *E) {
Nico Weber7849eeb2016-12-14 21:38:18 +00005084 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00005085 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005086
John McCall45d55e42010-05-07 21:00:08 +00005087 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005088 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005089 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005090 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005091 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005092 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005093 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005094 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005095 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005096 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005097 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005098 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005099 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005100 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005101 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005102 }
Richard Smithd62306a2011-11-10 06:34:14 +00005103 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005104 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005105 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005106 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005107 if (!Info.CurrentCall->This) {
5108 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005109 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005110 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005111 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005112 return false;
5113 }
Richard Smithd62306a2011-11-10 06:34:14 +00005114 Result = *Info.CurrentCall->This;
5115 return true;
5116 }
John McCallc07a0c72011-02-17 10:25:35 +00005117
Eli Friedman449fe542009-03-23 04:56:01 +00005118 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005119};
Chris Lattner05706e882008-07-11 18:11:29 +00005120} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005121
John McCall45d55e42010-05-07 21:00:08 +00005122static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005123 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005124 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005125}
5126
John McCall45d55e42010-05-07 21:00:08 +00005127bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005128 if (E->getOpcode() != BO_Add &&
5129 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005130 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005131
Chris Lattner05706e882008-07-11 18:11:29 +00005132 const Expr *PExp = E->getLHS();
5133 const Expr *IExp = E->getRHS();
5134 if (IExp->getType()->isPointerType())
5135 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005136
Richard Smith253c2a32012-01-27 01:14:48 +00005137 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005138 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005139 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005140
John McCall45d55e42010-05-07 21:00:08 +00005141 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005142 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005143 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005144
5145 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005146 if (E->getOpcode() == BO_Sub)
5147 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005148
Ted Kremenek28831752012-08-23 20:46:57 +00005149 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005150 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5151 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005152}
Eli Friedman9a156e52008-11-12 09:44:48 +00005153
John McCall45d55e42010-05-07 21:00:08 +00005154bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5155 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005156}
Mike Stump11289f42009-09-09 15:08:12 +00005157
Peter Collingbournee9200682011-05-13 03:29:01 +00005158bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5159 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005160
Eli Friedman847a2bc2009-12-27 05:43:15 +00005161 switch (E->getCastKind()) {
5162 default:
5163 break;
5164
John McCalle3027922010-08-25 11:45:40 +00005165 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005166 case CK_CPointerToObjCPointerCast:
5167 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005168 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005169 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005170 if (!Visit(SubExpr))
5171 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005172 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5173 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5174 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005175 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005176 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005177 if (SubExpr->getType()->isVoidPointerType())
5178 CCEDiag(E, diag::note_constexpr_invalid_cast)
5179 << 3 << SubExpr->getType();
5180 else
5181 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5182 }
Richard Smith96e0c102011-11-04 02:25:55 +00005183 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005184
Anders Carlsson18275092010-10-31 20:41:46 +00005185 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005186 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005187 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005188 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005189 if (!Result.Base && Result.Offset.isZero())
5190 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005191
Richard Smithd62306a2011-11-10 06:34:14 +00005192 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005193 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005194 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5195 castAs<PointerType>()->getPointeeType(),
5196 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005197
Richard Smith027bf112011-11-17 22:56:20 +00005198 case CK_BaseToDerived:
5199 if (!Visit(E->getSubExpr()))
5200 return false;
5201 if (!Result.Base && Result.Offset.isZero())
5202 return true;
5203 return HandleBaseToDerivedCast(Info, E, Result);
5204
Richard Smith0b0a0b62011-10-29 20:57:55 +00005205 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005206 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005207 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005208
John McCalle3027922010-08-25 11:45:40 +00005209 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005210 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5211
Richard Smith2e312c82012-03-03 22:46:17 +00005212 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005213 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005214 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005215
John McCall45d55e42010-05-07 21:00:08 +00005216 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005217 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5218 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005219 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005220 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005221 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005222 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005223 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005224 return true;
5225 } else {
5226 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005227 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005228 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005229 }
5230 }
John McCalle3027922010-08-25 11:45:40 +00005231 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005232 if (SubExpr->isGLValue()) {
5233 if (!EvaluateLValue(SubExpr, Result, Info))
5234 return false;
5235 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005236 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005237 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005238 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005239 return false;
5240 }
Richard Smith96e0c102011-11-04 02:25:55 +00005241 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005242 if (const ConstantArrayType *CAT
5243 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5244 Result.addArray(Info, E, CAT);
5245 else
5246 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005247 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005248
John McCalle3027922010-08-25 11:45:40 +00005249 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005250 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005251 }
5252
Richard Smith11562c52011-10-28 17:51:58 +00005253 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005254}
Chris Lattner05706e882008-07-11 18:11:29 +00005255
Hal Finkel0dd05d42014-10-03 17:18:37 +00005256static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5257 // C++ [expr.alignof]p3:
5258 // When alignof is applied to a reference type, the result is the
5259 // alignment of the referenced type.
5260 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5261 T = Ref->getPointeeType();
5262
5263 // __alignof is defined to return the preferred alignment.
5264 return Info.Ctx.toCharUnitsFromBits(
5265 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5266}
5267
5268static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5269 E = E->IgnoreParens();
5270
5271 // The kinds of expressions that we have special-case logic here for
5272 // should be kept up to date with the special checks for those
5273 // expressions in Sema.
5274
5275 // alignof decl is always accepted, even if it doesn't make sense: we default
5276 // to 1 in those cases.
5277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5278 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5279 /*RefAsPointee*/true);
5280
5281 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5282 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5283 /*RefAsPointee*/true);
5284
5285 return GetAlignOfType(Info, E->getType());
5286}
5287
Peter Collingbournee9200682011-05-13 03:29:01 +00005288bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005289 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005290 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005291
Richard Smith6328cbd2016-11-16 00:57:23 +00005292 if (unsigned BuiltinOp = E->getBuiltinCallee())
5293 return VisitBuiltinCallExpr(E, BuiltinOp);
5294
5295 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5296}
5297
5298bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5299 unsigned BuiltinOp) {
5300 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005301 case Builtin::BI__builtin_addressof:
5302 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005303 case Builtin::BI__builtin_assume_aligned: {
5304 // We need to be very careful here because: if the pointer does not have the
5305 // asserted alignment, then the behavior is undefined, and undefined
5306 // behavior is non-constant.
5307 if (!EvaluatePointer(E->getArg(0), Result, Info))
5308 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005309
Hal Finkel0dd05d42014-10-03 17:18:37 +00005310 LValue OffsetResult(Result);
5311 APSInt Alignment;
5312 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5313 return false;
5314 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5315
5316 if (E->getNumArgs() > 2) {
5317 APSInt Offset;
5318 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5319 return false;
5320
5321 int64_t AdditionalOffset = -getExtValue(Offset);
5322 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5323 }
5324
5325 // If there is a base object, then it must have the correct alignment.
5326 if (OffsetResult.Base) {
5327 CharUnits BaseAlignment;
5328 if (const ValueDecl *VD =
5329 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5330 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5331 } else {
5332 BaseAlignment =
5333 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5334 }
5335
5336 if (BaseAlignment < Align) {
5337 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005338 // FIXME: Quantities here cast to integers because the plural modifier
5339 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005340 CCEDiag(E->getArg(0),
5341 diag::note_constexpr_baa_insufficient_alignment) << 0
5342 << (int) BaseAlignment.getQuantity()
5343 << (unsigned) getExtValue(Alignment);
5344 return false;
5345 }
5346 }
5347
5348 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005349 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005350 Result.Designator.setInvalid();
5351 APSInt Offset(64, false);
5352 Offset = OffsetResult.Offset.getQuantity();
5353
5354 if (OffsetResult.Base)
5355 CCEDiag(E->getArg(0),
5356 diag::note_constexpr_baa_insufficient_alignment) << 1
5357 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5358 else
5359 CCEDiag(E->getArg(0),
5360 diag::note_constexpr_baa_value_insufficient_alignment)
5361 << Offset << (unsigned) getExtValue(Alignment);
5362
5363 return false;
5364 }
5365
5366 return true;
5367 }
Richard Smithe9507952016-11-12 01:39:56 +00005368
5369 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005370 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005371 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005372 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005373 if (Info.getLangOpts().CPlusPlus11)
5374 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5375 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005376 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005377 else
5378 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5379 // Fall through.
5380 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005381 case Builtin::BI__builtin_wcschr:
5382 case Builtin::BI__builtin_memchr:
5383 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005384 if (!Visit(E->getArg(0)))
5385 return false;
5386 APSInt Desired;
5387 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5388 return false;
5389 uint64_t MaxLength = uint64_t(-1);
5390 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005391 BuiltinOp != Builtin::BIwcschr &&
5392 BuiltinOp != Builtin::BI__builtin_strchr &&
5393 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005394 APSInt N;
5395 if (!EvaluateInteger(E->getArg(2), N, Info))
5396 return false;
5397 MaxLength = N.getExtValue();
5398 }
5399
Richard Smith8110c9d2016-11-29 19:45:17 +00005400 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005401
Richard Smith8110c9d2016-11-29 19:45:17 +00005402 // Figure out what value we're actually looking for (after converting to
5403 // the corresponding unsigned type if necessary).
5404 uint64_t DesiredVal;
5405 bool StopAtNull = false;
5406 switch (BuiltinOp) {
5407 case Builtin::BIstrchr:
5408 case Builtin::BI__builtin_strchr:
5409 // strchr compares directly to the passed integer, and therefore
5410 // always fails if given an int that is not a char.
5411 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5412 E->getArg(1)->getType(),
5413 Desired),
5414 Desired))
5415 return ZeroInitialization(E);
5416 StopAtNull = true;
5417 // Fall through.
5418 case Builtin::BImemchr:
5419 case Builtin::BI__builtin_memchr:
5420 // memchr compares by converting both sides to unsigned char. That's also
5421 // correct for strchr if we get this far (to cope with plain char being
5422 // unsigned in the strchr case).
5423 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5424 break;
Richard Smithe9507952016-11-12 01:39:56 +00005425
Richard Smith8110c9d2016-11-29 19:45:17 +00005426 case Builtin::BIwcschr:
5427 case Builtin::BI__builtin_wcschr:
5428 StopAtNull = true;
5429 // Fall through.
5430 case Builtin::BIwmemchr:
5431 case Builtin::BI__builtin_wmemchr:
5432 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5433 DesiredVal = Desired.getZExtValue();
5434 break;
5435 }
Richard Smithe9507952016-11-12 01:39:56 +00005436
5437 for (; MaxLength; --MaxLength) {
5438 APValue Char;
5439 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5440 !Char.isInt())
5441 return false;
5442 if (Char.getInt().getZExtValue() == DesiredVal)
5443 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005444 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005445 break;
5446 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5447 return false;
5448 }
5449 // Not found: return nullptr.
5450 return ZeroInitialization(E);
5451 }
5452
Richard Smith6cbd65d2013-07-11 02:27:57 +00005453 default:
5454 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5455 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005456}
Chris Lattner05706e882008-07-11 18:11:29 +00005457
5458//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005459// Member Pointer Evaluation
5460//===----------------------------------------------------------------------===//
5461
5462namespace {
5463class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005464 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005465 MemberPtr &Result;
5466
5467 bool Success(const ValueDecl *D) {
5468 Result = MemberPtr(D);
5469 return true;
5470 }
5471public:
5472
5473 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5474 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5475
Richard Smith2e312c82012-03-03 22:46:17 +00005476 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005477 Result.setFrom(V);
5478 return true;
5479 }
Richard Smithfddd3842011-12-30 21:15:51 +00005480 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005481 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005482 }
5483
5484 bool VisitCastExpr(const CastExpr *E);
5485 bool VisitUnaryAddrOf(const UnaryOperator *E);
5486};
5487} // end anonymous namespace
5488
5489static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5490 EvalInfo &Info) {
5491 assert(E->isRValue() && E->getType()->isMemberPointerType());
5492 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5493}
5494
5495bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5496 switch (E->getCastKind()) {
5497 default:
5498 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5499
5500 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005501 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005502 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005503
5504 case CK_BaseToDerivedMemberPointer: {
5505 if (!Visit(E->getSubExpr()))
5506 return false;
5507 if (E->path_empty())
5508 return true;
5509 // Base-to-derived member pointer casts store the path in derived-to-base
5510 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5511 // the wrong end of the derived->base arc, so stagger the path by one class.
5512 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5513 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5514 PathI != PathE; ++PathI) {
5515 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5516 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5517 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005518 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005519 }
5520 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5521 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005522 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005523 return true;
5524 }
5525
5526 case CK_DerivedToBaseMemberPointer:
5527 if (!Visit(E->getSubExpr()))
5528 return false;
5529 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5530 PathE = E->path_end(); PathI != PathE; ++PathI) {
5531 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5532 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5533 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005534 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005535 }
5536 return true;
5537 }
5538}
5539
5540bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5541 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5542 // member can be formed.
5543 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5544}
5545
5546//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005547// Record Evaluation
5548//===----------------------------------------------------------------------===//
5549
5550namespace {
5551 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005552 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005553 const LValue &This;
5554 APValue &Result;
5555 public:
5556
5557 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5558 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5559
Richard Smith2e312c82012-03-03 22:46:17 +00005560 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005561 Result = V;
5562 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005563 }
Richard Smithb8348f52016-05-12 22:16:28 +00005564 bool ZeroInitialization(const Expr *E) {
5565 return ZeroInitialization(E, E->getType());
5566 }
5567 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005568
Richard Smith52a980a2015-08-28 02:43:42 +00005569 bool VisitCallExpr(const CallExpr *E) {
5570 return handleCallExpr(E, Result, &This);
5571 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005572 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005573 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005574 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5575 return VisitCXXConstructExpr(E, E->getType());
5576 }
Richard Smith5179eb72016-06-28 19:03:57 +00005577 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005578 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005579 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005581}
Richard Smithd62306a2011-11-10 06:34:14 +00005582
Richard Smithfddd3842011-12-30 21:15:51 +00005583/// Perform zero-initialization on an object of non-union class type.
5584/// C++11 [dcl.init]p5:
5585/// To zero-initialize an object or reference of type T means:
5586/// [...]
5587/// -- if T is a (possibly cv-qualified) non-union class type,
5588/// each non-static data member and each base-class subobject is
5589/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005590static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5591 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005592 const LValue &This, APValue &Result) {
5593 assert(!RD->isUnion() && "Expected non-union class type");
5594 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5595 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005596 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005597
John McCalld7bca762012-05-01 00:38:49 +00005598 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005599 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5600
5601 if (CD) {
5602 unsigned Index = 0;
5603 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005604 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005605 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5606 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005607 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5608 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005609 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005610 Result.getStructBase(Index)))
5611 return false;
5612 }
5613 }
5614
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005615 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005616 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005617 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005618 continue;
5619
5620 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005621 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005622 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005623
David Blaikie2d7c57e2012-04-30 02:36:29 +00005624 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005625 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005626 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005627 return false;
5628 }
5629
5630 return true;
5631}
5632
Richard Smithb8348f52016-05-12 22:16:28 +00005633bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5634 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005635 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005636 if (RD->isUnion()) {
5637 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5638 // object's first non-static named data member is zero-initialized
5639 RecordDecl::field_iterator I = RD->field_begin();
5640 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005641 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005642 return true;
5643 }
5644
5645 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005646 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005647 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005648 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005649 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005650 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005651 }
5652
Richard Smith5d108602012-02-17 00:44:16 +00005653 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005654 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005655 return false;
5656 }
5657
Richard Smitha8105bc2012-01-06 16:39:00 +00005658 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005659}
5660
Richard Smithe97cbd72011-11-11 04:05:33 +00005661bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5662 switch (E->getCastKind()) {
5663 default:
5664 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5665
5666 case CK_ConstructorConversion:
5667 return Visit(E->getSubExpr());
5668
5669 case CK_DerivedToBase:
5670 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005671 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005672 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005673 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005674 if (!DerivedObject.isStruct())
5675 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005676
5677 // Derived-to-base rvalue conversion: just slice off the derived part.
5678 APValue *Value = &DerivedObject;
5679 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5680 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5681 PathE = E->path_end(); PathI != PathE; ++PathI) {
5682 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5683 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5684 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5685 RD = Base;
5686 }
5687 Result = *Value;
5688 return true;
5689 }
5690 }
5691}
5692
Richard Smithd62306a2011-11-10 06:34:14 +00005693bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005694 if (E->isTransparent())
5695 return Visit(E->getInit(0));
5696
Richard Smithd62306a2011-11-10 06:34:14 +00005697 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005698 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005699 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5700
5701 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005702 const FieldDecl *Field = E->getInitializedFieldInUnion();
5703 Result = APValue(Field);
5704 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005705 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005706
5707 // If the initializer list for a union does not contain any elements, the
5708 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005709 // FIXME: The element should be initialized from an initializer list.
5710 // Is this difference ever observable for initializer lists which
5711 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005712 ImplicitValueInitExpr VIE(Field->getType());
5713 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5714
Richard Smithd62306a2011-11-10 06:34:14 +00005715 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005716 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5717 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005718
5719 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5720 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5721 isa<CXXDefaultInitExpr>(InitExpr));
5722
Richard Smithb228a862012-02-15 02:18:13 +00005723 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005724 }
5725
Richard Smith872307e2016-03-08 22:17:41 +00005726 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005727 if (Result.isUninit())
5728 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5729 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005730 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005731 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005732
5733 // Initialize base classes.
5734 if (CXXRD) {
5735 for (const auto &Base : CXXRD->bases()) {
5736 assert(ElementNo < E->getNumInits() && "missing init for base class");
5737 const Expr *Init = E->getInit(ElementNo);
5738
5739 LValue Subobject = This;
5740 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5741 return false;
5742
5743 APValue &FieldVal = Result.getStructBase(ElementNo);
5744 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005745 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005746 return false;
5747 Success = false;
5748 }
5749 ++ElementNo;
5750 }
5751 }
5752
5753 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005754 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005755 // Anonymous bit-fields are not considered members of the class for
5756 // purposes of aggregate initialization.
5757 if (Field->isUnnamedBitfield())
5758 continue;
5759
5760 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005761
Richard Smith253c2a32012-01-27 01:14:48 +00005762 bool HaveInit = ElementNo < E->getNumInits();
5763
5764 // FIXME: Diagnostics here should point to the end of the initializer
5765 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005766 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005767 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005768 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005769
5770 // Perform an implicit value-initialization for members beyond the end of
5771 // the initializer list.
5772 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005773 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005774
Richard Smith852c9db2013-04-20 22:23:05 +00005775 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5776 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5777 isa<CXXDefaultInitExpr>(Init));
5778
Richard Smith49ca8aa2013-08-06 07:09:20 +00005779 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5780 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5781 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005782 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005783 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005784 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005785 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005786 }
5787 }
5788
Richard Smith253c2a32012-01-27 01:14:48 +00005789 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005790}
5791
Richard Smithb8348f52016-05-12 22:16:28 +00005792bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5793 QualType T) {
5794 // Note that E's type is not necessarily the type of our class here; we might
5795 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005796 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005797 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5798
Richard Smithfddd3842011-12-30 21:15:51 +00005799 bool ZeroInit = E->requiresZeroInitialization();
5800 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005801 // If we've already performed zero-initialization, we're already done.
5802 if (!Result.isUninit())
5803 return true;
5804
Richard Smithda3f4fd2014-03-05 23:32:50 +00005805 // We can get here in two different ways:
5806 // 1) We're performing value-initialization, and should zero-initialize
5807 // the object, or
5808 // 2) We're performing default-initialization of an object with a trivial
5809 // constexpr default constructor, in which case we should start the
5810 // lifetimes of all the base subobjects (there can be no data member
5811 // subobjects in this case) per [basic.life]p1.
5812 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005813 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005814 }
5815
Craig Topper36250ad2014-05-12 05:36:57 +00005816 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005817 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005818
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005819 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005820 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005821
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005822 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005823 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005824 if (const MaterializeTemporaryExpr *ME
5825 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5826 return Visit(ME->GetTemporaryExpr());
5827
Richard Smithb8348f52016-05-12 22:16:28 +00005828 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005829 return false;
5830
Craig Topper5fc8fc22014-08-27 06:28:36 +00005831 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005832 return HandleConstructorCall(E, This, Args,
5833 cast<CXXConstructorDecl>(Definition), Info,
5834 Result);
5835}
5836
5837bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5838 const CXXInheritedCtorInitExpr *E) {
5839 if (!Info.CurrentCall) {
5840 assert(Info.checkingPotentialConstantExpression());
5841 return false;
5842 }
5843
5844 const CXXConstructorDecl *FD = E->getConstructor();
5845 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5846 return false;
5847
5848 const FunctionDecl *Definition = nullptr;
5849 auto Body = FD->getBody(Definition);
5850
5851 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5852 return false;
5853
5854 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005855 cast<CXXConstructorDecl>(Definition), Info,
5856 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005857}
5858
Richard Smithcc1b96d2013-06-12 22:31:48 +00005859bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5860 const CXXStdInitializerListExpr *E) {
5861 const ConstantArrayType *ArrayType =
5862 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5863
5864 LValue Array;
5865 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5866 return false;
5867
5868 // Get a pointer to the first element of the array.
5869 Array.addArray(Info, E, ArrayType);
5870
5871 // FIXME: Perform the checks on the field types in SemaInit.
5872 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5873 RecordDecl::field_iterator Field = Record->field_begin();
5874 if (Field == Record->field_end())
5875 return Error(E);
5876
5877 // Start pointer.
5878 if (!Field->getType()->isPointerType() ||
5879 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5880 ArrayType->getElementType()))
5881 return Error(E);
5882
5883 // FIXME: What if the initializer_list type has base classes, etc?
5884 Result = APValue(APValue::UninitStruct(), 0, 2);
5885 Array.moveInto(Result.getStructField(0));
5886
5887 if (++Field == Record->field_end())
5888 return Error(E);
5889
5890 if (Field->getType()->isPointerType() &&
5891 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5892 ArrayType->getElementType())) {
5893 // End pointer.
5894 if (!HandleLValueArrayAdjustment(Info, E, Array,
5895 ArrayType->getElementType(),
5896 ArrayType->getSize().getZExtValue()))
5897 return false;
5898 Array.moveInto(Result.getStructField(1));
5899 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5900 // Length.
5901 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5902 else
5903 return Error(E);
5904
5905 if (++Field != Record->field_end())
5906 return Error(E);
5907
5908 return true;
5909}
5910
Richard Smithd62306a2011-11-10 06:34:14 +00005911static bool EvaluateRecord(const Expr *E, const LValue &This,
5912 APValue &Result, EvalInfo &Info) {
5913 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005914 "can't evaluate expression as a record rvalue");
5915 return RecordExprEvaluator(Info, This, Result).Visit(E);
5916}
5917
5918//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005919// Temporary Evaluation
5920//
5921// Temporaries are represented in the AST as rvalues, but generally behave like
5922// lvalues. The full-object of which the temporary is a subobject is implicitly
5923// materialized so that a reference can bind to it.
5924//===----------------------------------------------------------------------===//
5925namespace {
5926class TemporaryExprEvaluator
5927 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5928public:
5929 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5930 LValueExprEvaluatorBaseTy(Info, Result) {}
5931
5932 /// Visit an expression which constructs the value of this temporary.
5933 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005934 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005935 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5936 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005937 }
5938
5939 bool VisitCastExpr(const CastExpr *E) {
5940 switch (E->getCastKind()) {
5941 default:
5942 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5943
5944 case CK_ConstructorConversion:
5945 return VisitConstructExpr(E->getSubExpr());
5946 }
5947 }
5948 bool VisitInitListExpr(const InitListExpr *E) {
5949 return VisitConstructExpr(E);
5950 }
5951 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5952 return VisitConstructExpr(E);
5953 }
5954 bool VisitCallExpr(const CallExpr *E) {
5955 return VisitConstructExpr(E);
5956 }
Richard Smith513955c2014-12-17 19:24:30 +00005957 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5958 return VisitConstructExpr(E);
5959 }
Richard Smith027bf112011-11-17 22:56:20 +00005960};
5961} // end anonymous namespace
5962
5963/// Evaluate an expression of record type as a temporary.
5964static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005965 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005966 return TemporaryExprEvaluator(Info, Result).Visit(E);
5967}
5968
5969//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005970// Vector Evaluation
5971//===----------------------------------------------------------------------===//
5972
5973namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005974 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005975 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005976 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005977 public:
Mike Stump11289f42009-09-09 15:08:12 +00005978
Richard Smith2d406342011-10-22 21:10:00 +00005979 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5980 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005981
Craig Topper9798b932015-09-29 04:30:05 +00005982 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005983 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5984 // FIXME: remove this APValue copy.
5985 Result = APValue(V.data(), V.size());
5986 return true;
5987 }
Richard Smith2e312c82012-03-03 22:46:17 +00005988 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005989 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005990 Result = V;
5991 return true;
5992 }
Richard Smithfddd3842011-12-30 21:15:51 +00005993 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005994
Richard Smith2d406342011-10-22 21:10:00 +00005995 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005996 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005997 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005998 bool VisitInitListExpr(const InitListExpr *E);
5999 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006000 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006001 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006002 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006003 };
6004} // end anonymous namespace
6005
6006static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006007 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006008 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006009}
6010
George Burgess IV533ff002015-12-11 00:23:35 +00006011bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006012 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006013 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006014
Richard Smith161f09a2011-12-06 22:44:34 +00006015 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006016 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006017
Eli Friedmanc757de22011-03-25 00:43:55 +00006018 switch (E->getCastKind()) {
6019 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006020 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006021 if (SETy->isIntegerType()) {
6022 APSInt IntResult;
6023 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006024 return false;
6025 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006026 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006027 APFloat FloatResult(0.0);
6028 if (!EvaluateFloat(SE, FloatResult, Info))
6029 return false;
6030 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006031 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006032 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006033 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006034
6035 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006036 SmallVector<APValue, 4> Elts(NElts, Val);
6037 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006038 }
Eli Friedman803acb32011-12-22 03:51:45 +00006039 case CK_BitCast: {
6040 // Evaluate the operand into an APInt we can extract from.
6041 llvm::APInt SValInt;
6042 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6043 return false;
6044 // Extract the elements
6045 QualType EltTy = VTy->getElementType();
6046 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6047 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6048 SmallVector<APValue, 4> Elts;
6049 if (EltTy->isRealFloatingType()) {
6050 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006051 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006052 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006053 FloatEltSize = 80;
6054 for (unsigned i = 0; i < NElts; i++) {
6055 llvm::APInt Elt;
6056 if (BigEndian)
6057 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6058 else
6059 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006060 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006061 }
6062 } else if (EltTy->isIntegerType()) {
6063 for (unsigned i = 0; i < NElts; i++) {
6064 llvm::APInt Elt;
6065 if (BigEndian)
6066 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6067 else
6068 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6069 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6070 }
6071 } else {
6072 return Error(E);
6073 }
6074 return Success(Elts, E);
6075 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006076 default:
Richard Smith11562c52011-10-28 17:51:58 +00006077 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006078 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006079}
6080
Richard Smith2d406342011-10-22 21:10:00 +00006081bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006082VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006083 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006084 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006085 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006086
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006087 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006088 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006089
Eli Friedmanb9c71292012-01-03 23:24:20 +00006090 // The number of initializers can be less than the number of
6091 // vector elements. For OpenCL, this can be due to nested vector
6092 // initialization. For GCC compatibility, missing trailing elements
6093 // should be initialized with zeroes.
6094 unsigned CountInits = 0, CountElts = 0;
6095 while (CountElts < NumElements) {
6096 // Handle nested vector initialization.
6097 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006098 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006099 APValue v;
6100 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6101 return Error(E);
6102 unsigned vlen = v.getVectorLength();
6103 for (unsigned j = 0; j < vlen; j++)
6104 Elements.push_back(v.getVectorElt(j));
6105 CountElts += vlen;
6106 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006107 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006108 if (CountInits < NumInits) {
6109 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006110 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006111 } else // trailing integer zero.
6112 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6113 Elements.push_back(APValue(sInt));
6114 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006115 } else {
6116 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006117 if (CountInits < NumInits) {
6118 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006119 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006120 } else // trailing float zero.
6121 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6122 Elements.push_back(APValue(f));
6123 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006124 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006125 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006126 }
Richard Smith2d406342011-10-22 21:10:00 +00006127 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006128}
6129
Richard Smith2d406342011-10-22 21:10:00 +00006130bool
Richard Smithfddd3842011-12-30 21:15:51 +00006131VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006132 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006133 QualType EltTy = VT->getElementType();
6134 APValue ZeroElement;
6135 if (EltTy->isIntegerType())
6136 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6137 else
6138 ZeroElement =
6139 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6140
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006141 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006142 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006143}
6144
Richard Smith2d406342011-10-22 21:10:00 +00006145bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006146 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006147 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006148}
6149
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006150//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006151// Array Evaluation
6152//===----------------------------------------------------------------------===//
6153
6154namespace {
6155 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006156 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006157 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006158 APValue &Result;
6159 public:
6160
Richard Smithd62306a2011-11-10 06:34:14 +00006161 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6162 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006163
6164 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006165 assert((V.isArray() || V.isLValue()) &&
6166 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006167 Result = V;
6168 return true;
6169 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006170
Richard Smithfddd3842011-12-30 21:15:51 +00006171 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006172 const ConstantArrayType *CAT =
6173 Info.Ctx.getAsConstantArrayType(E->getType());
6174 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006175 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006176
6177 Result = APValue(APValue::UninitArray(), 0,
6178 CAT->getSize().getZExtValue());
6179 if (!Result.hasArrayFiller()) return true;
6180
Richard Smithfddd3842011-12-30 21:15:51 +00006181 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006182 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006183 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006184 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006185 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006186 }
6187
Richard Smith52a980a2015-08-28 02:43:42 +00006188 bool VisitCallExpr(const CallExpr *E) {
6189 return handleCallExpr(E, Result, &This);
6190 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006191 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006192 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006193 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006194 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6195 const LValue &Subobject,
6196 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006197 };
6198} // end anonymous namespace
6199
Richard Smithd62306a2011-11-10 06:34:14 +00006200static bool EvaluateArray(const Expr *E, const LValue &This,
6201 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006202 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006203 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006204}
6205
6206bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6207 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6208 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006209 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006210
Richard Smithca2cfbf2011-12-22 01:07:19 +00006211 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6212 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006213 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006214 LValue LV;
6215 if (!EvaluateLValue(E->getInit(0), LV, Info))
6216 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006217 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006218 LV.moveInto(Val);
6219 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006220 }
6221
Richard Smith253c2a32012-01-27 01:14:48 +00006222 bool Success = true;
6223
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006224 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6225 "zero-initialized array shouldn't have any initialized elts");
6226 APValue Filler;
6227 if (Result.isArray() && Result.hasArrayFiller())
6228 Filler = Result.getArrayFiller();
6229
Richard Smith9543c5e2013-04-22 14:44:29 +00006230 unsigned NumEltsToInit = E->getNumInits();
6231 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006232 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006233
6234 // If the initializer might depend on the array index, run it for each
6235 // array element. For now, just whitelist non-class value-initialization.
6236 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6237 NumEltsToInit = NumElts;
6238
6239 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006240
6241 // If the array was previously zero-initialized, preserve the
6242 // zero-initialized values.
6243 if (!Filler.isUninit()) {
6244 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6245 Result.getArrayInitializedElt(I) = Filler;
6246 if (Result.hasArrayFiller())
6247 Result.getArrayFiller() = Filler;
6248 }
6249
Richard Smithd62306a2011-11-10 06:34:14 +00006250 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006251 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006252 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6253 const Expr *Init =
6254 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006255 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006256 Info, Subobject, Init) ||
6257 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006258 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006259 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006260 return false;
6261 Success = false;
6262 }
Richard Smithd62306a2011-11-10 06:34:14 +00006263 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006264
Richard Smith9543c5e2013-04-22 14:44:29 +00006265 if (!Result.hasArrayFiller())
6266 return Success;
6267
6268 // If we get here, we have a trivial filler, which we can just evaluate
6269 // once and splat over the rest of the array elements.
6270 assert(FillerExpr && "no array filler for incomplete init list");
6271 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6272 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006273}
6274
Richard Smith410306b2016-12-12 02:53:20 +00006275bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6276 if (E->getCommonExpr() &&
6277 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6278 Info, E->getCommonExpr()->getSourceExpr()))
6279 return false;
6280
6281 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6282
6283 uint64_t Elements = CAT->getSize().getZExtValue();
6284 Result = APValue(APValue::UninitArray(), Elements, Elements);
6285
6286 LValue Subobject = This;
6287 Subobject.addArray(Info, E, CAT);
6288
6289 bool Success = true;
6290 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6291 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6292 Info, Subobject, E->getSubExpr()) ||
6293 !HandleLValueArrayAdjustment(Info, E, Subobject,
6294 CAT->getElementType(), 1)) {
6295 if (!Info.noteFailure())
6296 return false;
6297 Success = false;
6298 }
6299 }
6300
6301 return Success;
6302}
6303
Richard Smith027bf112011-11-17 22:56:20 +00006304bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006305 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6306}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006307
Richard Smith9543c5e2013-04-22 14:44:29 +00006308bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6309 const LValue &Subobject,
6310 APValue *Value,
6311 QualType Type) {
6312 bool HadZeroInit = !Value->isUninit();
6313
6314 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6315 unsigned N = CAT->getSize().getZExtValue();
6316
6317 // Preserve the array filler if we had prior zero-initialization.
6318 APValue Filler =
6319 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6320 : APValue();
6321
6322 *Value = APValue(APValue::UninitArray(), N, N);
6323
6324 if (HadZeroInit)
6325 for (unsigned I = 0; I != N; ++I)
6326 Value->getArrayInitializedElt(I) = Filler;
6327
6328 // Initialize the elements.
6329 LValue ArrayElt = Subobject;
6330 ArrayElt.addArray(Info, E, CAT);
6331 for (unsigned I = 0; I != N; ++I)
6332 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6333 CAT->getElementType()) ||
6334 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6335 CAT->getElementType(), 1))
6336 return false;
6337
6338 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006339 }
Richard Smith027bf112011-11-17 22:56:20 +00006340
Richard Smith9543c5e2013-04-22 14:44:29 +00006341 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006342 return Error(E);
6343
Richard Smithb8348f52016-05-12 22:16:28 +00006344 return RecordExprEvaluator(Info, Subobject, *Value)
6345 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006346}
6347
Richard Smithf3e9e432011-11-07 09:22:26 +00006348//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006349// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006350//
6351// As a GNU extension, we support casting pointers to sufficiently-wide integer
6352// types and back in constant folding. Integer values are thus represented
6353// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006354//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006355
6356namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006357class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006358 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006359 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006360public:
Richard Smith2e312c82012-03-03 22:46:17 +00006361 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006362 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006363
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006364 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006365 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006366 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006367 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006368 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006369 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006370 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006371 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006372 return true;
6373 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006374 bool Success(const llvm::APSInt &SI, const Expr *E) {
6375 return Success(SI, E, Result);
6376 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006378 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006379 assert(E->getType()->isIntegralOrEnumerationType() &&
6380 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006381 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006382 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006383 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006384 Result.getInt().setIsUnsigned(
6385 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006386 return true;
6387 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006388 bool Success(const llvm::APInt &I, const Expr *E) {
6389 return Success(I, E, Result);
6390 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006391
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006392 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006393 assert(E->getType()->isIntegralOrEnumerationType() &&
6394 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006395 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006396 return true;
6397 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006398 bool Success(uint64_t Value, const Expr *E) {
6399 return Success(Value, E, Result);
6400 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006401
Ken Dyckdbc01912011-03-11 02:13:43 +00006402 bool Success(CharUnits Size, const Expr *E) {
6403 return Success(Size.getQuantity(), E);
6404 }
6405
Richard Smith2e312c82012-03-03 22:46:17 +00006406 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006407 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006408 Result = V;
6409 return true;
6410 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006411 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006412 }
Mike Stump11289f42009-09-09 15:08:12 +00006413
Richard Smithfddd3842011-12-30 21:15:51 +00006414 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006415
Peter Collingbournee9200682011-05-13 03:29:01 +00006416 //===--------------------------------------------------------------------===//
6417 // Visitor Methods
6418 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006419
Chris Lattner7174bf32008-07-12 00:38:25 +00006420 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006421 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006422 }
6423 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006424 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006425 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006426
6427 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6428 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006429 if (CheckReferencedDecl(E, E->getDecl()))
6430 return true;
6431
6432 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006433 }
6434 bool VisitMemberExpr(const MemberExpr *E) {
6435 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006436 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006437 return true;
6438 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006439
6440 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006441 }
6442
Peter Collingbournee9200682011-05-13 03:29:01 +00006443 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006444 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006445 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006446 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006447 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006448
Peter Collingbournee9200682011-05-13 03:29:01 +00006449 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006450 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006451
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006452 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006453 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455
Ted Kremeneke65b0862012-03-06 20:05:56 +00006456 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6457 return Success(E->getValue(), E);
6458 }
Richard Smith410306b2016-12-12 02:53:20 +00006459
6460 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6461 if (Info.ArrayInitIndex == uint64_t(-1)) {
6462 // We were asked to evaluate this subexpression independent of the
6463 // enclosing ArrayInitLoopExpr. We can't do that.
6464 Info.FFDiag(E);
6465 return false;
6466 }
6467 return Success(Info.ArrayInitIndex, E);
6468 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006469
Richard Smith4ce706a2011-10-11 21:43:33 +00006470 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006471 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006472 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006473 }
6474
Douglas Gregor29c42f22012-02-24 07:38:34 +00006475 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6476 return Success(E->getValue(), E);
6477 }
6478
John Wiegley6242b6a2011-04-28 00:16:57 +00006479 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6480 return Success(E->getValue(), E);
6481 }
6482
John Wiegleyf9f65842011-04-25 06:54:41 +00006483 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6484 return Success(E->getValue(), E);
6485 }
6486
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006487 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006488 bool VisitUnaryImag(const UnaryOperator *E);
6489
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006490 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006491 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006492
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006493private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006494 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006495 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006496};
Chris Lattner05706e882008-07-11 18:11:29 +00006497} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006498
Richard Smith11562c52011-10-28 17:51:58 +00006499/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6500/// produce either the integer value or a pointer.
6501///
6502/// GCC has a heinous extension which folds casts between pointer types and
6503/// pointer-sized integral types. We support this by allowing the evaluation of
6504/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6505/// Some simple arithmetic on such values is supported (they are treated much
6506/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006507static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006508 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006509 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006510 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006511}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006512
Richard Smithf57d8cb2011-12-09 22:58:01 +00006513static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006514 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006515 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006516 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006517 if (!Val.isInt()) {
6518 // FIXME: It would be better to produce the diagnostic for casting
6519 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006520 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006521 return false;
6522 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006523 Result = Val.getInt();
6524 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006525}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006526
Richard Smithf57d8cb2011-12-09 22:58:01 +00006527/// Check whether the given declaration can be directly converted to an integral
6528/// rvalue. If not, no diagnostic is produced; there are other things we can
6529/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006530bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006531 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006532 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006533 // Check for signedness/width mismatches between E type and ECD value.
6534 bool SameSign = (ECD->getInitVal().isSigned()
6535 == E->getType()->isSignedIntegerOrEnumerationType());
6536 bool SameWidth = (ECD->getInitVal().getBitWidth()
6537 == Info.Ctx.getIntWidth(E->getType()));
6538 if (SameSign && SameWidth)
6539 return Success(ECD->getInitVal(), E);
6540 else {
6541 // Get rid of mismatch (otherwise Success assertions will fail)
6542 // by computing a new value matching the type of E.
6543 llvm::APSInt Val = ECD->getInitVal();
6544 if (!SameSign)
6545 Val.setIsSigned(!ECD->getInitVal().isSigned());
6546 if (!SameWidth)
6547 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6548 return Success(Val, E);
6549 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006550 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006551 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006552}
6553
Chris Lattner86ee2862008-10-06 06:40:35 +00006554/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6555/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006556static int EvaluateBuiltinClassifyType(const CallExpr *E,
6557 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006558 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006559 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006560 enum gcc_type_class {
6561 no_type_class = -1,
6562 void_type_class, integer_type_class, char_type_class,
6563 enumeral_type_class, boolean_type_class,
6564 pointer_type_class, reference_type_class, offset_type_class,
6565 real_type_class, complex_type_class,
6566 function_type_class, method_type_class,
6567 record_type_class, union_type_class,
6568 array_type_class, string_type_class,
6569 lang_type_class
6570 };
Mike Stump11289f42009-09-09 15:08:12 +00006571
6572 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006573 // ideal, however it is what gcc does.
6574 if (E->getNumArgs() == 0)
6575 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006576
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006577 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6578 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6579
6580 switch (CanTy->getTypeClass()) {
6581#define TYPE(ID, BASE)
6582#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6583#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6584#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6585#include "clang/AST/TypeNodes.def"
6586 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6587
6588 case Type::Builtin:
6589 switch (BT->getKind()) {
6590#define BUILTIN_TYPE(ID, SINGLETON_ID)
6591#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6592#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6593#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6594#include "clang/AST/BuiltinTypes.def"
6595 case BuiltinType::Void:
6596 return void_type_class;
6597
6598 case BuiltinType::Bool:
6599 return boolean_type_class;
6600
6601 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6602 case BuiltinType::UChar:
6603 case BuiltinType::UShort:
6604 case BuiltinType::UInt:
6605 case BuiltinType::ULong:
6606 case BuiltinType::ULongLong:
6607 case BuiltinType::UInt128:
6608 return integer_type_class;
6609
6610 case BuiltinType::NullPtr:
6611 return pointer_type_class;
6612
6613 case BuiltinType::WChar_U:
6614 case BuiltinType::Char16:
6615 case BuiltinType::Char32:
6616 case BuiltinType::ObjCId:
6617 case BuiltinType::ObjCClass:
6618 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006619#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6620 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006621#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006622 case BuiltinType::OCLSampler:
6623 case BuiltinType::OCLEvent:
6624 case BuiltinType::OCLClkEvent:
6625 case BuiltinType::OCLQueue:
6626 case BuiltinType::OCLNDRange:
6627 case BuiltinType::OCLReserveID:
6628 case BuiltinType::Dependent:
6629 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6630 };
6631
6632 case Type::Enum:
6633 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6634 break;
6635
6636 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006637 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006638 break;
6639
6640 case Type::MemberPointer:
6641 if (CanTy->isMemberDataPointerType())
6642 return offset_type_class;
6643 else {
6644 // We expect member pointers to be either data or function pointers,
6645 // nothing else.
6646 assert(CanTy->isMemberFunctionPointerType());
6647 return method_type_class;
6648 }
6649
6650 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006651 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006652
6653 case Type::FunctionNoProto:
6654 case Type::FunctionProto:
6655 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6656
6657 case Type::Record:
6658 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6659 switch (RT->getDecl()->getTagKind()) {
6660 case TagTypeKind::TTK_Struct:
6661 case TagTypeKind::TTK_Class:
6662 case TagTypeKind::TTK_Interface:
6663 return record_type_class;
6664
6665 case TagTypeKind::TTK_Enum:
6666 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6667
6668 case TagTypeKind::TTK_Union:
6669 return union_type_class;
6670 }
6671 }
David Blaikie83d382b2011-09-23 05:06:16 +00006672 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006673
6674 case Type::ConstantArray:
6675 case Type::VariableArray:
6676 case Type::IncompleteArray:
6677 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6678
6679 case Type::BlockPointer:
6680 case Type::LValueReference:
6681 case Type::RValueReference:
6682 case Type::Vector:
6683 case Type::ExtVector:
6684 case Type::Auto:
6685 case Type::ObjCObject:
6686 case Type::ObjCInterface:
6687 case Type::ObjCObjectPointer:
6688 case Type::Pipe:
6689 case Type::Atomic:
6690 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6691 }
6692
6693 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006694}
6695
Richard Smith5fab0c92011-12-28 19:48:30 +00006696/// EvaluateBuiltinConstantPForLValue - Determine the result of
6697/// __builtin_constant_p when applied to the given lvalue.
6698///
6699/// An lvalue is only "constant" if it is a pointer or reference to the first
6700/// character of a string literal.
6701template<typename LValue>
6702static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006703 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006704 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6705}
6706
6707/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6708/// GCC as we can manage.
6709static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6710 QualType ArgType = Arg->getType();
6711
6712 // __builtin_constant_p always has one operand. The rules which gcc follows
6713 // are not precisely documented, but are as follows:
6714 //
6715 // - If the operand is of integral, floating, complex or enumeration type,
6716 // and can be folded to a known value of that type, it returns 1.
6717 // - If the operand and can be folded to a pointer to the first character
6718 // of a string literal (or such a pointer cast to an integral type), it
6719 // returns 1.
6720 //
6721 // Otherwise, it returns 0.
6722 //
6723 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6724 // its support for this does not currently work.
6725 if (ArgType->isIntegralOrEnumerationType()) {
6726 Expr::EvalResult Result;
6727 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6728 return false;
6729
6730 APValue &V = Result.Val;
6731 if (V.getKind() == APValue::Int)
6732 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006733 if (V.getKind() == APValue::LValue)
6734 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006735 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6736 return Arg->isEvaluatable(Ctx);
6737 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6738 LValue LV;
6739 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006740 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006741 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6742 : EvaluatePointer(Arg, LV, Info)) &&
6743 !Status.HasSideEffects)
6744 return EvaluateBuiltinConstantPForLValue(LV);
6745 }
6746
6747 // Anything else isn't considered to be sufficiently constant.
6748 return false;
6749}
6750
John McCall95007602010-05-10 23:27:23 +00006751/// Retrieves the "underlying object type" of the given expression,
6752/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006753static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006754 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6755 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006756 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006757 } else if (const Expr *E = B.get<const Expr*>()) {
6758 if (isa<CompoundLiteralExpr>(E))
6759 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006760 }
6761
6762 return QualType();
6763}
6764
George Burgess IV3a03fab2015-09-04 21:28:13 +00006765/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006766/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6767/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006768/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6769///
6770/// Always returns an RValue with a pointer representation.
6771static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6772 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6773
6774 auto *NoParens = E->IgnoreParens();
6775 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006776 if (Cast == nullptr)
6777 return NoParens;
6778
6779 // We only conservatively allow a few kinds of casts, because this code is
6780 // inherently a simple solution that seeks to support the common case.
6781 auto CastKind = Cast->getCastKind();
6782 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6783 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006784 return NoParens;
6785
6786 auto *SubExpr = Cast->getSubExpr();
6787 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6788 return NoParens;
6789 return ignorePointerCastsAndParens(SubExpr);
6790}
6791
George Burgess IVa51c4072015-10-16 01:49:01 +00006792/// Checks to see if the given LValue's Designator is at the end of the LValue's
6793/// record layout. e.g.
6794/// struct { struct { int a, b; } fst, snd; } obj;
6795/// obj.fst // no
6796/// obj.snd // yes
6797/// obj.fst.a // no
6798/// obj.fst.b // no
6799/// obj.snd.a // no
6800/// obj.snd.b // yes
6801///
6802/// Please note: this function is specialized for how __builtin_object_size
6803/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006804///
6805/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006806static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6807 assert(!LVal.Designator.Invalid);
6808
George Burgess IV4168d752016-06-27 19:40:41 +00006809 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6810 const RecordDecl *Parent = FD->getParent();
6811 Invalid = Parent->isInvalidDecl();
6812 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006813 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006814 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006815 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6816 };
6817
6818 auto &Base = LVal.getLValueBase();
6819 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6820 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006821 bool Invalid;
6822 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6823 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006824 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006825 for (auto *FD : IFD->chain()) {
6826 bool Invalid;
6827 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6828 return Invalid;
6829 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006830 }
6831 }
6832
6833 QualType BaseType = getType(Base);
6834 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6835 if (BaseType->isArrayType()) {
6836 // Because __builtin_object_size treats arrays as objects, we can ignore
6837 // the index iff this is the last array in the Designator.
6838 if (I + 1 == E)
6839 return true;
6840 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6841 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6842 if (Index + 1 != CAT->getSize())
6843 return false;
6844 BaseType = CAT->getElementType();
6845 } else if (BaseType->isAnyComplexType()) {
6846 auto *CT = BaseType->castAs<ComplexType>();
6847 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6848 if (Index != 1)
6849 return false;
6850 BaseType = CT->getElementType();
6851 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006852 bool Invalid;
6853 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6854 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006855 BaseType = FD->getType();
6856 } else {
6857 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6858 "Expecting cast to a base class");
6859 return false;
6860 }
6861 }
6862 return true;
6863}
6864
6865/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6866static bool refersToCompleteObject(const LValue &LVal) {
6867 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6868 return false;
6869
6870 if (!LVal.InvalidBase)
6871 return true;
6872
6873 auto *E = LVal.Base.dyn_cast<const Expr *>();
6874 (void)E;
6875 assert(E != nullptr && isa<MemberExpr>(E));
6876 return false;
6877}
6878
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006879/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6880/// true and stores the result in @p Size.
6881///
6882/// If @p WasError is non-null, this will report whether the failure to evaluate
6883/// is to be treated as an Error in IntExprEvaluator.
6884static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6885 EvalInfo &Info, uint64_t &Size,
6886 bool *WasError = nullptr) {
6887 if (WasError != nullptr)
6888 *WasError = false;
6889
6890 auto Error = [&](const Expr *E) {
6891 if (WasError != nullptr)
6892 *WasError = true;
6893 return false;
6894 };
6895
6896 auto Success = [&](uint64_t S, const Expr *E) {
6897 Size = S;
6898 return true;
6899 };
6900
George Burgess IVbdb5b262015-08-19 02:19:07 +00006901 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006902 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006903 {
6904 // The operand of __builtin_object_size is never evaluated for side-effects.
6905 // If there are any, but we can determine the pointed-to object anyway, then
6906 // ignore the side-effects.
6907 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006908 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006909
6910 if (E->isGLValue()) {
6911 // It's possible for us to be given GLValues if we're called via
6912 // Expr::tryEvaluateObjectSize.
6913 APValue RVal;
6914 if (!EvaluateAsRValue(Info, E, RVal))
6915 return false;
6916 Base.setFrom(Info.Ctx, RVal);
6917 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006918 return false;
6919 }
John McCall95007602010-05-10 23:27:23 +00006920
George Burgess IVbdb5b262015-08-19 02:19:07 +00006921 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006922 // If we point to before the start of the object, there are no accessible
6923 // bytes.
6924 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006925 return Success(0, E);
6926
George Burgess IV3a03fab2015-09-04 21:28:13 +00006927 // In the case where we're not dealing with a subobject, we discard the
6928 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006929 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006930
6931 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6932 // exist. If we can't verify the base, then we can't do that.
6933 //
6934 // As a special case, we produce a valid object size for an unknown object
6935 // with a known designator if Type & 1 is 1. For instance:
6936 //
6937 // extern struct X { char buff[32]; int a, b, c; } *p;
6938 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6939 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6940 //
6941 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006942 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006943 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006944
George Burgess IVa51c4072015-10-16 01:49:01 +00006945 // If we're not examining only the subobject, then we reset to a complete
6946 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006947 //
6948 // If Type is 1 and we've lost track of the subobject, just find the complete
6949 // object instead. (If Type is 3, that's not correct behavior and we should
6950 // return 0 instead.)
6951 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006952 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006953 QualType T = getObjectType(End.getLValueBase());
6954 if (T.isNull())
6955 End.Designator.setInvalid();
6956 else {
6957 End.Designator = SubobjectDesignator(T);
6958 End.Offset = CharUnits::Zero();
6959 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006960 }
John McCall95007602010-05-10 23:27:23 +00006961
George Burgess IVbdb5b262015-08-19 02:19:07 +00006962 // If it is not possible to determine which objects ptr points to at compile
6963 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6964 // and (size_t) 0 for type 2 or 3.
6965 if (End.Designator.Invalid)
6966 return false;
6967
6968 // According to the GCC documentation, we want the size of the subobject
6969 // denoted by the pointer. But that's not quite right -- what we actually
6970 // want is the size of the immediately-enclosing array, if there is one.
6971 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006972 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006973 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6974 // We got a pointer to an array. Step to its end.
6975 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006976 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006977 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006978 // We're already pointing at the end of the object.
6979 AmountToAdd = 0;
6980 }
6981
George Burgess IV3a03fab2015-09-04 21:28:13 +00006982 QualType PointeeType = End.Designator.MostDerivedType;
6983 assert(!PointeeType.isNull());
6984 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006985 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006986
George Burgess IVbdb5b262015-08-19 02:19:07 +00006987 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6988 AmountToAdd))
6989 return false;
John McCall95007602010-05-10 23:27:23 +00006990
George Burgess IVbdb5b262015-08-19 02:19:07 +00006991 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006992
6993 // The following is a moderately common idiom in C:
6994 //
6995 // struct Foo { int a; char c[1]; };
6996 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6997 // strcpy(&F->c[0], Bar);
6998 //
George Burgess IVf8f63242016-09-12 23:50:35 +00006999 // So, if we see that we're examining an array at the end of a struct with an
7000 // unknown base, we give up instead of breaking code that behaves this way.
7001 // Note that we only do this when Type=1, because Type=3 is a lower bound, so
7002 // answering conservatively is fine.
7003 //
7004 // We used to be a bit more aggressive here; we'd only be conservative if the
7005 // array at the end was flexible, or if it had 0 or 1 elements. This broke
7006 // some common standard library extensions (PR30346), but was otherwise
7007 // seemingly fine. It may be useful to reintroduce this behavior with some
7008 // sort of whitelist. OTOH, it seems that GCC is always conservative with the
7009 // last element in structs (if it's an array), so our current behavior is more
7010 // compatible than a whitelisting approach would be.
George Burgess IVa51c4072015-10-16 01:49:01 +00007011 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
7012 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
7013 End.Designator.MostDerivedIsArrayElement &&
George Burgess IVa51c4072015-10-16 01:49:01 +00007014 isDesignatorAtObjectEnd(Info.Ctx, End))
7015 return false;
7016
George Burgess IVbdb5b262015-08-19 02:19:07 +00007017 if (BaseOffset > EndOffset)
7018 return Success(0, E);
7019
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007020 return Success((EndOffset - BaseOffset).getQuantity(), E);
7021}
7022
7023bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
7024 unsigned Type) {
7025 uint64_t Size;
7026 bool WasError;
7027 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
7028 return Success(Size, E);
7029 if (WasError)
7030 return Error(E);
7031 return false;
John McCall95007602010-05-10 23:27:23 +00007032}
7033
Peter Collingbournee9200682011-05-13 03:29:01 +00007034bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007035 if (unsigned BuiltinOp = E->getBuiltinCallee())
7036 return VisitBuiltinCallExpr(E, BuiltinOp);
7037
7038 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7039}
7040
7041bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7042 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007043 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007044 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007045 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007046
7047 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007048 // The type was checked when we built the expression.
7049 unsigned Type =
7050 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7051 assert(Type <= 3 && "unexpected type");
7052
7053 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00007054 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00007055
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007056 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007057 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007058
Richard Smith01ade172012-05-23 04:13:20 +00007059 // Expression had no side effects, but we couldn't statically determine the
7060 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007061 switch (Info.EvalMode) {
7062 case EvalInfo::EM_ConstantExpression:
7063 case EvalInfo::EM_PotentialConstantExpression:
7064 case EvalInfo::EM_ConstantFold:
7065 case EvalInfo::EM_EvaluateForOverflow:
7066 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00007067 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007068 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007069 return Error(E);
7070 case EvalInfo::EM_ConstantExpressionUnevaluated:
7071 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007072 // Reduce it to a constant now.
7073 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007074 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007075
7076 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007077 }
7078
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007079 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007080 case Builtin::BI__builtin_bswap32:
7081 case Builtin::BI__builtin_bswap64: {
7082 APSInt Val;
7083 if (!EvaluateInteger(E->getArg(0), Val, Info))
7084 return false;
7085
7086 return Success(Val.byteSwap(), E);
7087 }
7088
Richard Smith8889a3d2013-06-13 06:26:32 +00007089 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007090 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007091
7092 // FIXME: BI__builtin_clrsb
7093 // FIXME: BI__builtin_clrsbl
7094 // FIXME: BI__builtin_clrsbll
7095
Richard Smith80b3c8e2013-06-13 05:04:16 +00007096 case Builtin::BI__builtin_clz:
7097 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007098 case Builtin::BI__builtin_clzll:
7099 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007100 APSInt Val;
7101 if (!EvaluateInteger(E->getArg(0), Val, Info))
7102 return false;
7103 if (!Val)
7104 return Error(E);
7105
7106 return Success(Val.countLeadingZeros(), E);
7107 }
7108
Richard Smith8889a3d2013-06-13 06:26:32 +00007109 case Builtin::BI__builtin_constant_p:
7110 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7111
Richard Smith80b3c8e2013-06-13 05:04:16 +00007112 case Builtin::BI__builtin_ctz:
7113 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007114 case Builtin::BI__builtin_ctzll:
7115 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007116 APSInt Val;
7117 if (!EvaluateInteger(E->getArg(0), Val, Info))
7118 return false;
7119 if (!Val)
7120 return Error(E);
7121
7122 return Success(Val.countTrailingZeros(), E);
7123 }
7124
Richard Smith8889a3d2013-06-13 06:26:32 +00007125 case Builtin::BI__builtin_eh_return_data_regno: {
7126 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7127 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7128 return Success(Operand, E);
7129 }
7130
7131 case Builtin::BI__builtin_expect:
7132 return Visit(E->getArg(0));
7133
7134 case Builtin::BI__builtin_ffs:
7135 case Builtin::BI__builtin_ffsl:
7136 case Builtin::BI__builtin_ffsll: {
7137 APSInt Val;
7138 if (!EvaluateInteger(E->getArg(0), Val, Info))
7139 return false;
7140
7141 unsigned N = Val.countTrailingZeros();
7142 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7143 }
7144
7145 case Builtin::BI__builtin_fpclassify: {
7146 APFloat Val(0.0);
7147 if (!EvaluateFloat(E->getArg(5), Val, Info))
7148 return false;
7149 unsigned Arg;
7150 switch (Val.getCategory()) {
7151 case APFloat::fcNaN: Arg = 0; break;
7152 case APFloat::fcInfinity: Arg = 1; break;
7153 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7154 case APFloat::fcZero: Arg = 4; break;
7155 }
7156 return Visit(E->getArg(Arg));
7157 }
7158
7159 case Builtin::BI__builtin_isinf_sign: {
7160 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007161 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007162 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7163 }
7164
Richard Smithea3019d2013-10-15 19:07:14 +00007165 case Builtin::BI__builtin_isinf: {
7166 APFloat Val(0.0);
7167 return EvaluateFloat(E->getArg(0), Val, Info) &&
7168 Success(Val.isInfinity() ? 1 : 0, E);
7169 }
7170
7171 case Builtin::BI__builtin_isfinite: {
7172 APFloat Val(0.0);
7173 return EvaluateFloat(E->getArg(0), Val, Info) &&
7174 Success(Val.isFinite() ? 1 : 0, E);
7175 }
7176
7177 case Builtin::BI__builtin_isnan: {
7178 APFloat Val(0.0);
7179 return EvaluateFloat(E->getArg(0), Val, Info) &&
7180 Success(Val.isNaN() ? 1 : 0, E);
7181 }
7182
7183 case Builtin::BI__builtin_isnormal: {
7184 APFloat Val(0.0);
7185 return EvaluateFloat(E->getArg(0), Val, Info) &&
7186 Success(Val.isNormal() ? 1 : 0, E);
7187 }
7188
Richard Smith8889a3d2013-06-13 06:26:32 +00007189 case Builtin::BI__builtin_parity:
7190 case Builtin::BI__builtin_parityl:
7191 case Builtin::BI__builtin_parityll: {
7192 APSInt Val;
7193 if (!EvaluateInteger(E->getArg(0), Val, Info))
7194 return false;
7195
7196 return Success(Val.countPopulation() % 2, E);
7197 }
7198
Richard Smith80b3c8e2013-06-13 05:04:16 +00007199 case Builtin::BI__builtin_popcount:
7200 case Builtin::BI__builtin_popcountl:
7201 case Builtin::BI__builtin_popcountll: {
7202 APSInt Val;
7203 if (!EvaluateInteger(E->getArg(0), Val, Info))
7204 return false;
7205
7206 return Success(Val.countPopulation(), E);
7207 }
7208
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007209 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007210 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007211 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007212 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007213 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007214 << /*isConstexpr*/0 << /*isConstructor*/0
7215 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007216 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007217 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007218 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007219 case Builtin::BI__builtin_strlen:
7220 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007221 // As an extension, we support __builtin_strlen() as a constant expression,
7222 // and support folding strlen() to a constant.
7223 LValue String;
7224 if (!EvaluatePointer(E->getArg(0), String, Info))
7225 return false;
7226
Richard Smith8110c9d2016-11-29 19:45:17 +00007227 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7228
Richard Smithe6c19f22013-11-15 02:10:04 +00007229 // Fast path: if it's a string literal, search the string value.
7230 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7231 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007232 // The string literal may have embedded null characters. Find the first
7233 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007234 StringRef Str = S->getBytes();
7235 int64_t Off = String.Offset.getQuantity();
7236 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007237 S->getCharByteWidth() == 1 &&
7238 // FIXME: Add fast-path for wchar_t too.
7239 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007240 Str = Str.substr(Off);
7241
7242 StringRef::size_type Pos = Str.find(0);
7243 if (Pos != StringRef::npos)
7244 Str = Str.substr(0, Pos);
7245
7246 return Success(Str.size(), E);
7247 }
7248
7249 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007250 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007251
7252 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007253 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7254 APValue Char;
7255 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7256 !Char.isInt())
7257 return false;
7258 if (!Char.getInt())
7259 return Success(Strlen, E);
7260 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7261 return false;
7262 }
7263 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007264
Richard Smithe151bab2016-11-11 23:43:35 +00007265 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007266 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007267 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007268 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007269 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007270 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007271 // A call to strlen is not a constant expression.
7272 if (Info.getLangOpts().CPlusPlus11)
7273 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7274 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007275 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007276 else
7277 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7278 // Fall through.
7279 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007280 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007281 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007282 case Builtin::BI__builtin_wcsncmp:
7283 case Builtin::BI__builtin_memcmp:
7284 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007285 LValue String1, String2;
7286 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7287 !EvaluatePointer(E->getArg(1), String2, Info))
7288 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007289
7290 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7291
Richard Smithe151bab2016-11-11 23:43:35 +00007292 uint64_t MaxLength = uint64_t(-1);
7293 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007294 BuiltinOp != Builtin::BIwcscmp &&
7295 BuiltinOp != Builtin::BI__builtin_strcmp &&
7296 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007297 APSInt N;
7298 if (!EvaluateInteger(E->getArg(2), N, Info))
7299 return false;
7300 MaxLength = N.getExtValue();
7301 }
7302 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007303 BuiltinOp != Builtin::BIwmemcmp &&
7304 BuiltinOp != Builtin::BI__builtin_memcmp &&
7305 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007306 for (; MaxLength; --MaxLength) {
7307 APValue Char1, Char2;
7308 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7309 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7310 !Char1.isInt() || !Char2.isInt())
7311 return false;
7312 if (Char1.getInt() != Char2.getInt())
7313 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7314 if (StopAtNull && !Char1.getInt())
7315 return Success(0, E);
7316 assert(!(StopAtNull && !Char2.getInt()));
7317 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7318 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7319 return false;
7320 }
7321 // We hit the strncmp / memcmp limit.
7322 return Success(0, E);
7323 }
7324
Richard Smith01ba47d2012-04-13 00:45:38 +00007325 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007326 case Builtin::BI__atomic_is_lock_free:
7327 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007328 APSInt SizeVal;
7329 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7330 return false;
7331
7332 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7333 // of two less than the maximum inline atomic width, we know it is
7334 // lock-free. If the size isn't a power of two, or greater than the
7335 // maximum alignment where we promote atomics, we know it is not lock-free
7336 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7337 // the answer can only be determined at runtime; for example, 16-byte
7338 // atomics have lock-free implementations on some, but not all,
7339 // x86-64 processors.
7340
7341 // Check power-of-two.
7342 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007343 if (Size.isPowerOfTwo()) {
7344 // Check against inlining width.
7345 unsigned InlineWidthBits =
7346 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7347 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7348 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7349 Size == CharUnits::One() ||
7350 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7351 Expr::NPC_NeverValueDependent))
7352 // OK, we will inline appropriately-aligned operations of this size,
7353 // and _Atomic(T) is appropriately-aligned.
7354 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007355
Richard Smith01ba47d2012-04-13 00:45:38 +00007356 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7357 castAs<PointerType>()->getPointeeType();
7358 if (!PointeeType->isIncompleteType() &&
7359 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7360 // OK, we will inline operations on this object.
7361 return Success(1, E);
7362 }
7363 }
7364 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007365
Richard Smith01ba47d2012-04-13 00:45:38 +00007366 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7367 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007368 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007369 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007370}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007371
Richard Smith8b3497e2011-10-31 01:37:14 +00007372static bool HasSameBase(const LValue &A, const LValue &B) {
7373 if (!A.getLValueBase())
7374 return !B.getLValueBase();
7375 if (!B.getLValueBase())
7376 return false;
7377
Richard Smithce40ad62011-11-12 22:28:03 +00007378 if (A.getLValueBase().getOpaqueValue() !=
7379 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007380 const Decl *ADecl = GetLValueBaseDecl(A);
7381 if (!ADecl)
7382 return false;
7383 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007384 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007385 return false;
7386 }
7387
7388 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007389 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007390}
7391
Richard Smithd20f1e62014-10-21 23:01:04 +00007392/// \brief Determine whether this is a pointer past the end of the complete
7393/// object referred to by the lvalue.
7394static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7395 const LValue &LV) {
7396 // A null pointer can be viewed as being "past the end" but we don't
7397 // choose to look at it that way here.
7398 if (!LV.getLValueBase())
7399 return false;
7400
7401 // If the designator is valid and refers to a subobject, we're not pointing
7402 // past the end.
7403 if (!LV.getLValueDesignator().Invalid &&
7404 !LV.getLValueDesignator().isOnePastTheEnd())
7405 return false;
7406
David Majnemerc378ca52015-08-29 08:32:55 +00007407 // A pointer to an incomplete type might be past-the-end if the type's size is
7408 // zero. We cannot tell because the type is incomplete.
7409 QualType Ty = getType(LV.getLValueBase());
7410 if (Ty->isIncompleteType())
7411 return true;
7412
Richard Smithd20f1e62014-10-21 23:01:04 +00007413 // We're a past-the-end pointer if we point to the byte after the object,
7414 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007415 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007416 return LV.getLValueOffset() == Size;
7417}
7418
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007419namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007420
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007421/// \brief Data recursive integer evaluator of certain binary operators.
7422///
7423/// We use a data recursive algorithm for binary operators so that we are able
7424/// to handle extreme cases of chained binary operators without causing stack
7425/// overflow.
7426class DataRecursiveIntBinOpEvaluator {
7427 struct EvalResult {
7428 APValue Val;
7429 bool Failed;
7430
7431 EvalResult() : Failed(false) { }
7432
7433 void swap(EvalResult &RHS) {
7434 Val.swap(RHS.Val);
7435 Failed = RHS.Failed;
7436 RHS.Failed = false;
7437 }
7438 };
7439
7440 struct Job {
7441 const Expr *E;
7442 EvalResult LHSResult; // meaningful only for binary operator expression.
7443 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007444
David Blaikie73726062015-08-12 23:09:24 +00007445 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007446 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007447
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007448 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007449 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007450 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007451
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007452 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007453 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007454 };
7455
7456 SmallVector<Job, 16> Queue;
7457
7458 IntExprEvaluator &IntEval;
7459 EvalInfo &Info;
7460 APValue &FinalResult;
7461
7462public:
7463 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7464 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7465
7466 /// \brief True if \param E is a binary operator that we are going to handle
7467 /// data recursively.
7468 /// We handle binary operators that are comma, logical, or that have operands
7469 /// with integral or enumeration type.
7470 static bool shouldEnqueue(const BinaryOperator *E) {
7471 return E->getOpcode() == BO_Comma ||
7472 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007473 (E->isRValue() &&
7474 E->getType()->isIntegralOrEnumerationType() &&
7475 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007476 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007477 }
7478
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007479 bool Traverse(const BinaryOperator *E) {
7480 enqueue(E);
7481 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007482 while (!Queue.empty())
7483 process(PrevResult);
7484
7485 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007486
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007487 FinalResult.swap(PrevResult.Val);
7488 return true;
7489 }
7490
7491private:
7492 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7493 return IntEval.Success(Value, E, Result);
7494 }
7495 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7496 return IntEval.Success(Value, E, Result);
7497 }
7498 bool Error(const Expr *E) {
7499 return IntEval.Error(E);
7500 }
7501 bool Error(const Expr *E, diag::kind D) {
7502 return IntEval.Error(E, D);
7503 }
7504
7505 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7506 return Info.CCEDiag(E, D);
7507 }
7508
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007509 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7510 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007511 bool &SuppressRHSDiags);
7512
7513 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7514 const BinaryOperator *E, APValue &Result);
7515
7516 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7517 Result.Failed = !Evaluate(Result.Val, Info, E);
7518 if (Result.Failed)
7519 Result.Val = APValue();
7520 }
7521
Richard Trieuba4d0872012-03-21 23:30:30 +00007522 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007523
7524 void enqueue(const Expr *E) {
7525 E = E->IgnoreParens();
7526 Queue.resize(Queue.size()+1);
7527 Queue.back().E = E;
7528 Queue.back().Kind = Job::AnyExprKind;
7529 }
7530};
7531
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007532}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007533
7534bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007535 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007536 bool &SuppressRHSDiags) {
7537 if (E->getOpcode() == BO_Comma) {
7538 // Ignore LHS but note if we could not evaluate it.
7539 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007540 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007541 return true;
7542 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007543
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007544 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007545 bool LHSAsBool;
7546 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007547 // We were able to evaluate the LHS, see if we can get away with not
7548 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007549 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7550 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007551 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007552 }
7553 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007554 LHSResult.Failed = true;
7555
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007556 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007557 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007558 if (!Info.noteSideEffect())
7559 return false;
7560
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007561 // We can't evaluate the LHS; however, sometimes the result
7562 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7563 // Don't ignore RHS and suppress diagnostics from this arm.
7564 SuppressRHSDiags = true;
7565 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007566
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007567 return true;
7568 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007569
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007570 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7571 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007572
George Burgess IVa145e252016-05-25 22:38:36 +00007573 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007574 return false; // Ignore RHS;
7575
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007576 return true;
7577}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007578
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007579bool DataRecursiveIntBinOpEvaluator::
7580 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7581 const BinaryOperator *E, APValue &Result) {
7582 if (E->getOpcode() == BO_Comma) {
7583 if (RHSResult.Failed)
7584 return false;
7585 Result = RHSResult.Val;
7586 return true;
7587 }
7588
7589 if (E->isLogicalOp()) {
7590 bool lhsResult, rhsResult;
7591 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7592 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7593
7594 if (LHSIsOK) {
7595 if (RHSIsOK) {
7596 if (E->getOpcode() == BO_LOr)
7597 return Success(lhsResult || rhsResult, E, Result);
7598 else
7599 return Success(lhsResult && rhsResult, E, Result);
7600 }
7601 } else {
7602 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007603 // We can't evaluate the LHS; however, sometimes the result
7604 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7605 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007606 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007607 }
7608 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007609
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007610 return false;
7611 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007612
7613 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7614 E->getRHS()->getType()->isIntegralOrEnumerationType());
7615
7616 if (LHSResult.Failed || RHSResult.Failed)
7617 return false;
7618
7619 const APValue &LHSVal = LHSResult.Val;
7620 const APValue &RHSVal = RHSResult.Val;
7621
7622 // Handle cases like (unsigned long)&a + 4.
7623 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7624 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007625 CharUnits AdditionalOffset =
7626 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007627 if (E->getOpcode() == BO_Add)
7628 Result.getLValueOffset() += AdditionalOffset;
7629 else
7630 Result.getLValueOffset() -= AdditionalOffset;
7631 return true;
7632 }
7633
7634 // Handle cases like 4 + (unsigned long)&a
7635 if (E->getOpcode() == BO_Add &&
7636 RHSVal.isLValue() && LHSVal.isInt()) {
7637 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007638 Result.getLValueOffset() +=
7639 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007640 return true;
7641 }
7642
7643 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7644 // Handle (intptr_t)&&A - (intptr_t)&&B.
7645 if (!LHSVal.getLValueOffset().isZero() ||
7646 !RHSVal.getLValueOffset().isZero())
7647 return false;
7648 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7649 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7650 if (!LHSExpr || !RHSExpr)
7651 return false;
7652 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7653 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7654 if (!LHSAddrExpr || !RHSAddrExpr)
7655 return false;
7656 // Make sure both labels come from the same function.
7657 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7658 RHSAddrExpr->getLabel()->getDeclContext())
7659 return false;
7660 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7661 return true;
7662 }
Richard Smith43e77732013-05-07 04:50:00 +00007663
7664 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007665 if (!LHSVal.isInt() || !RHSVal.isInt())
7666 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007667
7668 // Set up the width and signedness manually, in case it can't be deduced
7669 // from the operation we're performing.
7670 // FIXME: Don't do this in the cases where we can deduce it.
7671 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7672 E->getType()->isUnsignedIntegerOrEnumerationType());
7673 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7674 RHSVal.getInt(), Value))
7675 return false;
7676 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007677}
7678
Richard Trieuba4d0872012-03-21 23:30:30 +00007679void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007680 Job &job = Queue.back();
7681
7682 switch (job.Kind) {
7683 case Job::AnyExprKind: {
7684 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7685 if (shouldEnqueue(Bop)) {
7686 job.Kind = Job::BinOpKind;
7687 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007688 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007689 }
7690 }
7691
7692 EvaluateExpr(job.E, Result);
7693 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007694 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007695 }
7696
7697 case Job::BinOpKind: {
7698 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007699 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007700 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007701 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007702 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007703 }
7704 if (SuppressRHSDiags)
7705 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007706 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007707 job.Kind = Job::BinOpVisitedLHSKind;
7708 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007709 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007710 }
7711
7712 case Job::BinOpVisitedLHSKind: {
7713 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7714 EvalResult RHS;
7715 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007716 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007717 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007718 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007719 }
7720 }
7721
7722 llvm_unreachable("Invalid Job::Kind!");
7723}
7724
George Burgess IV8c892b52016-05-25 22:31:54 +00007725namespace {
7726/// Used when we determine that we should fail, but can keep evaluating prior to
7727/// noting that we had a failure.
7728class DelayedNoteFailureRAII {
7729 EvalInfo &Info;
7730 bool NoteFailure;
7731
7732public:
7733 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7734 : Info(Info), NoteFailure(NoteFailure) {}
7735 ~DelayedNoteFailureRAII() {
7736 if (NoteFailure) {
7737 bool ContinueAfterFailure = Info.noteFailure();
7738 (void)ContinueAfterFailure;
7739 assert(ContinueAfterFailure &&
7740 "Shouldn't have kept evaluating on failure.");
7741 }
7742 }
7743};
7744}
7745
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007746bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007747 // We don't call noteFailure immediately because the assignment happens after
7748 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007749 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007750 return Error(E);
7751
George Burgess IV8c892b52016-05-25 22:31:54 +00007752 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007753 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7754 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007755
Anders Carlssonacc79812008-11-16 07:17:21 +00007756 QualType LHSTy = E->getLHS()->getType();
7757 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007758
Chandler Carruthb29a7432014-10-11 11:03:30 +00007759 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007760 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007761 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007762 if (E->isAssignmentOp()) {
7763 LValue LV;
7764 EvaluateLValue(E->getLHS(), LV, Info);
7765 LHSOK = false;
7766 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007767 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7768 if (LHSOK) {
7769 LHS.makeComplexFloat();
7770 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7771 }
7772 } else {
7773 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7774 }
George Burgess IVa145e252016-05-25 22:38:36 +00007775 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007776 return false;
7777
Chandler Carruthb29a7432014-10-11 11:03:30 +00007778 if (E->getRHS()->getType()->isRealFloatingType()) {
7779 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7780 return false;
7781 RHS.makeComplexFloat();
7782 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7783 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007784 return false;
7785
7786 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007787 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007788 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007789 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007790 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7791
John McCalle3027922010-08-25 11:45:40 +00007792 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007793 return Success((CR_r == APFloat::cmpEqual &&
7794 CR_i == APFloat::cmpEqual), E);
7795 else {
John McCalle3027922010-08-25 11:45:40 +00007796 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007797 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007798 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007799 CR_r == APFloat::cmpLessThan ||
7800 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007801 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007802 CR_i == APFloat::cmpLessThan ||
7803 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007804 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007805 } else {
John McCalle3027922010-08-25 11:45:40 +00007806 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007807 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7808 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7809 else {
John McCalle3027922010-08-25 11:45:40 +00007810 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007811 "Invalid compex comparison.");
7812 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7813 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7814 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007815 }
7816 }
Mike Stump11289f42009-09-09 15:08:12 +00007817
Anders Carlssonacc79812008-11-16 07:17:21 +00007818 if (LHSTy->isRealFloatingType() &&
7819 RHSTy->isRealFloatingType()) {
7820 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007821
Richard Smith253c2a32012-01-27 01:14:48 +00007822 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007823 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007825
Richard Smith253c2a32012-01-27 01:14:48 +00007826 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007827 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007828
Anders Carlssonacc79812008-11-16 07:17:21 +00007829 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007830
Anders Carlssonacc79812008-11-16 07:17:21 +00007831 switch (E->getOpcode()) {
7832 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007833 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007834 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007835 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007836 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007837 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007838 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007839 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007840 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007841 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007842 E);
John McCalle3027922010-08-25 11:45:40 +00007843 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007844 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007845 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007846 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007847 || CR == APFloat::cmpLessThan
7848 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007849 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007850 }
Mike Stump11289f42009-09-09 15:08:12 +00007851
Eli Friedmana38da572009-04-28 19:17:36 +00007852 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007853 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007854 LValue LHSValue, RHSValue;
7855
7856 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007857 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007858 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007859
Richard Smith253c2a32012-01-27 01:14:48 +00007860 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007861 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007862
Richard Smith8b3497e2011-10-31 01:37:14 +00007863 // Reject differing bases from the normal codepath; we special-case
7864 // comparisons to null.
7865 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007866 if (E->getOpcode() == BO_Sub) {
7867 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007868 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007869 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007870 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007871 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007872 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007873 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007874 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7875 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7876 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007877 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007878 // Make sure both labels come from the same function.
7879 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7880 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007881 return Error(E);
7882 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007883 }
Richard Smith83c68212011-10-31 05:11:32 +00007884 // Inequalities and subtractions between unrelated pointers have
7885 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007886 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007887 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007888 // A constant address may compare equal to the address of a symbol.
7889 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007890 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007891 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7892 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007893 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007894 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007895 // distinct addresses. In clang, the result of such a comparison is
7896 // unspecified, so it is not a constant expression. However, we do know
7897 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007898 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7899 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007900 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007901 // We can't tell whether weak symbols will end up pointing to the same
7902 // object.
7903 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007904 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007905 // We can't compare the address of the start of one object with the
7906 // past-the-end address of another object, per C++ DR1652.
7907 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7908 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7909 (RHSValue.Base && RHSValue.Offset.isZero() &&
7910 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7911 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007912 // We can't tell whether an object is at the same address as another
7913 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007914 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7915 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007916 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007917 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007918 // (Note that clang defaults to -fmerge-all-constants, which can
7919 // lead to inconsistent results for comparisons involving the address
7920 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007921 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007922 }
Eli Friedman64004332009-03-23 04:38:34 +00007923
Richard Smith1b470412012-02-01 08:10:20 +00007924 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7925 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7926
Richard Smith84f6dcf2012-02-02 01:16:57 +00007927 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7928 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7929
John McCalle3027922010-08-25 11:45:40 +00007930 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007931 // C++11 [expr.add]p6:
7932 // Unless both pointers point to elements of the same array object, or
7933 // one past the last element of the array object, the behavior is
7934 // undefined.
7935 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7936 !AreElementsOfSameArray(getType(LHSValue.Base),
7937 LHSDesignator, RHSDesignator))
7938 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7939
Chris Lattner882bdf22010-04-20 17:13:14 +00007940 QualType Type = E->getLHS()->getType();
7941 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007942
Richard Smithd62306a2011-11-10 06:34:14 +00007943 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007944 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007945 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007946
Richard Smith84c6b3d2013-09-10 21:34:14 +00007947 // As an extension, a type may have zero size (empty struct or union in
7948 // C, array of zero length). Pointer subtraction in such cases has
7949 // undefined behavior, so is not constant.
7950 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007951 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007952 << ElementType;
7953 return false;
7954 }
7955
Richard Smith1b470412012-02-01 08:10:20 +00007956 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7957 // and produce incorrect results when it overflows. Such behavior
7958 // appears to be non-conforming, but is common, so perhaps we should
7959 // assume the standard intended for such cases to be undefined behavior
7960 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007961
Richard Smith1b470412012-02-01 08:10:20 +00007962 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7963 // overflow in the final conversion to ptrdiff_t.
7964 APSInt LHS(
7965 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7966 APSInt RHS(
7967 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7968 APSInt ElemSize(
7969 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7970 APSInt TrueResult = (LHS - RHS) / ElemSize;
7971 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7972
Richard Smith0c6124b2015-12-03 01:36:22 +00007973 if (Result.extend(65) != TrueResult &&
7974 !HandleOverflow(Info, E, TrueResult, E->getType()))
7975 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007976 return Success(Result, E);
7977 }
Richard Smithde21b242012-01-31 06:41:30 +00007978
7979 // C++11 [expr.rel]p3:
7980 // Pointers to void (after pointer conversions) can be compared, with a
7981 // result defined as follows: If both pointers represent the same
7982 // address or are both the null pointer value, the result is true if the
7983 // operator is <= or >= and false otherwise; otherwise the result is
7984 // unspecified.
7985 // We interpret this as applying to pointers to *cv* void.
7986 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007987 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007988 CCEDiag(E, diag::note_constexpr_void_comparison);
7989
Richard Smith84f6dcf2012-02-02 01:16:57 +00007990 // C++11 [expr.rel]p2:
7991 // - If two pointers point to non-static data members of the same object,
7992 // or to subobjects or array elements fo such members, recursively, the
7993 // pointer to the later declared member compares greater provided the
7994 // two members have the same access control and provided their class is
7995 // not a union.
7996 // [...]
7997 // - Otherwise pointer comparisons are unspecified.
7998 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7999 E->isRelationalOp()) {
8000 bool WasArrayIndex;
8001 unsigned Mismatch =
8002 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8003 RHSDesignator, WasArrayIndex);
8004 // At the point where the designators diverge, the comparison has a
8005 // specified value if:
8006 // - we are comparing array indices
8007 // - we are comparing fields of a union, or fields with the same access
8008 // Otherwise, the result is unspecified and thus the comparison is not a
8009 // constant expression.
8010 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8011 Mismatch < RHSDesignator.Entries.size()) {
8012 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8013 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8014 if (!LF && !RF)
8015 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8016 else if (!LF)
8017 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8018 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8019 << RF->getParent() << RF;
8020 else if (!RF)
8021 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8022 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8023 << LF->getParent() << LF;
8024 else if (!LF->getParent()->isUnion() &&
8025 LF->getAccess() != RF->getAccess())
8026 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8027 << LF << LF->getAccess() << RF << RF->getAccess()
8028 << LF->getParent();
8029 }
8030 }
8031
Eli Friedman6c31cb42012-04-16 04:30:08 +00008032 // The comparison here must be unsigned, and performed with the same
8033 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008034 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8035 uint64_t CompareLHS = LHSOffset.getQuantity();
8036 uint64_t CompareRHS = RHSOffset.getQuantity();
8037 assert(PtrSize <= 64 && "Unexpected pointer width");
8038 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8039 CompareLHS &= Mask;
8040 CompareRHS &= Mask;
8041
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008042 // If there is a base and this is a relational operator, we can only
8043 // compare pointers within the object in question; otherwise, the result
8044 // depends on where the object is located in memory.
8045 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8046 QualType BaseTy = getType(LHSValue.Base);
8047 if (BaseTy->isIncompleteType())
8048 return Error(E);
8049 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8050 uint64_t OffsetLimit = Size.getQuantity();
8051 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8052 return Error(E);
8053 }
8054
Richard Smith8b3497e2011-10-31 01:37:14 +00008055 switch (E->getOpcode()) {
8056 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008057 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8058 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8059 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8060 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8061 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8062 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008063 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008064 }
8065 }
Richard Smith7bb00672012-02-01 01:42:44 +00008066
8067 if (LHSTy->isMemberPointerType()) {
8068 assert(E->isEqualityOp() && "unexpected member pointer operation");
8069 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8070
8071 MemberPtr LHSValue, RHSValue;
8072
8073 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008074 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008075 return false;
8076
8077 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8078 return false;
8079
8080 // C++11 [expr.eq]p2:
8081 // If both operands are null, they compare equal. Otherwise if only one is
8082 // null, they compare unequal.
8083 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8084 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8085 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8086 }
8087
8088 // Otherwise if either is a pointer to a virtual member function, the
8089 // result is unspecified.
8090 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8091 if (MD->isVirtual())
8092 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8093 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8094 if (MD->isVirtual())
8095 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8096
8097 // Otherwise they compare equal if and only if they would refer to the
8098 // same member of the same most derived object or the same subobject if
8099 // they were dereferenced with a hypothetical object of the associated
8100 // class type.
8101 bool Equal = LHSValue == RHSValue;
8102 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8103 }
8104
Richard Smithab44d9b2012-02-14 22:35:28 +00008105 if (LHSTy->isNullPtrType()) {
8106 assert(E->isComparisonOp() && "unexpected nullptr operation");
8107 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8108 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8109 // are compared, the result is true of the operator is <=, >= or ==, and
8110 // false otherwise.
8111 BinaryOperator::Opcode Opcode = E->getOpcode();
8112 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8113 }
8114
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008115 assert((!LHSTy->isIntegralOrEnumerationType() ||
8116 !RHSTy->isIntegralOrEnumerationType()) &&
8117 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8118 // We can't continue from here for non-integral types.
8119 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008120}
8121
Peter Collingbournee190dee2011-03-11 19:24:49 +00008122/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8123/// a result as the expression's type.
8124bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8125 const UnaryExprOrTypeTraitExpr *E) {
8126 switch(E->getKind()) {
8127 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008128 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008129 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008130 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008131 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008132 }
Eli Friedman64004332009-03-23 04:38:34 +00008133
Peter Collingbournee190dee2011-03-11 19:24:49 +00008134 case UETT_VecStep: {
8135 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008136
Peter Collingbournee190dee2011-03-11 19:24:49 +00008137 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008138 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008139
Peter Collingbournee190dee2011-03-11 19:24:49 +00008140 // The vec_step built-in functions that take a 3-component
8141 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8142 if (n == 3)
8143 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008144
Peter Collingbournee190dee2011-03-11 19:24:49 +00008145 return Success(n, E);
8146 } else
8147 return Success(1, E);
8148 }
8149
8150 case UETT_SizeOf: {
8151 QualType SrcTy = E->getTypeOfArgument();
8152 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8153 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008154 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8155 SrcTy = Ref->getPointeeType();
8156
Richard Smithd62306a2011-11-10 06:34:14 +00008157 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008158 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008159 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008160 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008161 }
Alexey Bataev00396512015-07-02 03:40:19 +00008162 case UETT_OpenMPRequiredSimdAlign:
8163 assert(E->isArgumentType());
8164 return Success(
8165 Info.Ctx.toCharUnitsFromBits(
8166 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8167 .getQuantity(),
8168 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008169 }
8170
8171 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008172}
8173
Peter Collingbournee9200682011-05-13 03:29:01 +00008174bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008175 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008176 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008177 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008178 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008179 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008180 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008181 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008182 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008183 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008184 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008185 APSInt IdxResult;
8186 if (!EvaluateInteger(Idx, IdxResult, Info))
8187 return false;
8188 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8189 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008190 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008191 CurrentType = AT->getElementType();
8192 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8193 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008194 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008195 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008196
James Y Knight7281c352015-12-29 22:31:18 +00008197 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008198 FieldDecl *MemberDecl = ON.getField();
8199 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008200 if (!RT)
8201 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008202 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008203 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008204 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008205 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008206 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008207 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008208 CurrentType = MemberDecl->getType().getNonReferenceType();
8209 break;
8210 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008211
James Y Knight7281c352015-12-29 22:31:18 +00008212 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008213 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008214
James Y Knight7281c352015-12-29 22:31:18 +00008215 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008216 CXXBaseSpecifier *BaseSpec = ON.getBase();
8217 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008218 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008219
8220 // Find the layout of the class whose base we are looking into.
8221 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008222 if (!RT)
8223 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008224 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008225 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008226 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8227
8228 // Find the base class itself.
8229 CurrentType = BaseSpec->getType();
8230 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8231 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008232 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008233
8234 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008235 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008236 break;
8237 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008238 }
8239 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008240 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008241}
8242
Chris Lattnere13042c2008-07-11 19:10:17 +00008243bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008244 switch (E->getOpcode()) {
8245 default:
8246 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8247 // See C99 6.6p3.
8248 return Error(E);
8249 case UO_Extension:
8250 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8251 // If so, we could clear the diagnostic ID.
8252 return Visit(E->getSubExpr());
8253 case UO_Plus:
8254 // The result is just the value.
8255 return Visit(E->getSubExpr());
8256 case UO_Minus: {
8257 if (!Visit(E->getSubExpr()))
8258 return false;
8259 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008260 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008261 if (Value.isSigned() && Value.isMinSignedValue() &&
8262 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8263 E->getType()))
8264 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008265 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008266 }
8267 case UO_Not: {
8268 if (!Visit(E->getSubExpr()))
8269 return false;
8270 if (!Result.isInt()) return Error(E);
8271 return Success(~Result.getInt(), E);
8272 }
8273 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008274 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008275 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008276 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008277 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008278 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008279 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008280}
Mike Stump11289f42009-09-09 15:08:12 +00008281
Chris Lattner477c4be2008-07-12 01:15:53 +00008282/// HandleCast - This is used to evaluate implicit or explicit casts where the
8283/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008284bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8285 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008286 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008287 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008288
Eli Friedmanc757de22011-03-25 00:43:55 +00008289 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008290 case CK_BaseToDerived:
8291 case CK_DerivedToBase:
8292 case CK_UncheckedDerivedToBase:
8293 case CK_Dynamic:
8294 case CK_ToUnion:
8295 case CK_ArrayToPointerDecay:
8296 case CK_FunctionToPointerDecay:
8297 case CK_NullToPointer:
8298 case CK_NullToMemberPointer:
8299 case CK_BaseToDerivedMemberPointer:
8300 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008301 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008302 case CK_ConstructorConversion:
8303 case CK_IntegralToPointer:
8304 case CK_ToVoid:
8305 case CK_VectorSplat:
8306 case CK_IntegralToFloating:
8307 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008308 case CK_CPointerToObjCPointerCast:
8309 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008310 case CK_AnyPointerToBlockPointerCast:
8311 case CK_ObjCObjectLValueCast:
8312 case CK_FloatingRealToComplex:
8313 case CK_FloatingComplexToReal:
8314 case CK_FloatingComplexCast:
8315 case CK_FloatingComplexToIntegralComplex:
8316 case CK_IntegralRealToComplex:
8317 case CK_IntegralComplexCast:
8318 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008319 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008320 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008321 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008322 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008323 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008324 llvm_unreachable("invalid cast kind for integral value");
8325
Eli Friedman9faf2f92011-03-25 19:07:11 +00008326 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008327 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008328 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008329 case CK_ARCProduceObject:
8330 case CK_ARCConsumeObject:
8331 case CK_ARCReclaimReturnedObject:
8332 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008333 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008334 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008335
Richard Smith4ef685b2012-01-17 21:17:26 +00008336 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008337 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008338 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008339 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008340 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008341
8342 case CK_MemberPointerToBoolean:
8343 case CK_PointerToBoolean:
8344 case CK_IntegralToBoolean:
8345 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008346 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008347 case CK_FloatingComplexToBoolean:
8348 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008349 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008350 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008351 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008352 uint64_t IntResult = BoolResult;
8353 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8354 IntResult = (uint64_t)-1;
8355 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008356 }
8357
Eli Friedmanc757de22011-03-25 00:43:55 +00008358 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008359 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008360 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008361
Eli Friedman742421e2009-02-20 01:15:07 +00008362 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008363 // Allow casts of address-of-label differences if they are no-ops
8364 // or narrowing. (The narrowing case isn't actually guaranteed to
8365 // be constant-evaluatable except in some narrow cases which are hard
8366 // to detect here. We let it through on the assumption the user knows
8367 // what they are doing.)
8368 if (Result.isAddrLabelDiff())
8369 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008370 // Only allow casts of lvalues if they are lossless.
8371 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8372 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008373
Richard Smith911e1422012-01-30 22:27:01 +00008374 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8375 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008376 }
Mike Stump11289f42009-09-09 15:08:12 +00008377
Eli Friedmanc757de22011-03-25 00:43:55 +00008378 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008379 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8380
John McCall45d55e42010-05-07 21:00:08 +00008381 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008382 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008383 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008384
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008385 if (LV.getLValueBase()) {
8386 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008387 // FIXME: Allow a larger integer size than the pointer size, and allow
8388 // narrowing back down to pointer width in subsequent integral casts.
8389 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008390 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008391 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008392
Richard Smithcf74da72011-11-16 07:18:12 +00008393 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008394 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008395 return true;
8396 }
8397
Nico Weber7849eeb2016-12-14 21:38:18 +00008398 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8399 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008400 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008401 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008402
Eli Friedmanc757de22011-03-25 00:43:55 +00008403 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008404 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008405 if (!EvaluateComplex(SubExpr, C, Info))
8406 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008407 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008408 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008409
Eli Friedmanc757de22011-03-25 00:43:55 +00008410 case CK_FloatingToIntegral: {
8411 APFloat F(0.0);
8412 if (!EvaluateFloat(SubExpr, F, Info))
8413 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008414
Richard Smith357362d2011-12-13 06:39:58 +00008415 APSInt Value;
8416 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8417 return false;
8418 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008419 }
8420 }
Mike Stump11289f42009-09-09 15:08:12 +00008421
Eli Friedmanc757de22011-03-25 00:43:55 +00008422 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008423}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008424
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008425bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8426 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008427 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008428 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8429 return false;
8430 if (!LV.isComplexInt())
8431 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008432 return Success(LV.getComplexIntReal(), E);
8433 }
8434
8435 return Visit(E->getSubExpr());
8436}
8437
Eli Friedman4e7a2412009-02-27 04:45:43 +00008438bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008439 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008440 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008441 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8442 return false;
8443 if (!LV.isComplexInt())
8444 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008445 return Success(LV.getComplexIntImag(), E);
8446 }
8447
Richard Smith4a678122011-10-24 18:44:57 +00008448 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008449 return Success(0, E);
8450}
8451
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008452bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8453 return Success(E->getPackLength(), E);
8454}
8455
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008456bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8457 return Success(E->getValue(), E);
8458}
8459
Chris Lattner05706e882008-07-11 18:11:29 +00008460//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008461// Float Evaluation
8462//===----------------------------------------------------------------------===//
8463
8464namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008465class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008466 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008467 APFloat &Result;
8468public:
8469 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008470 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008471
Richard Smith2e312c82012-03-03 22:46:17 +00008472 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008473 Result = V.getFloat();
8474 return true;
8475 }
Eli Friedman24c01542008-08-22 00:06:13 +00008476
Richard Smithfddd3842011-12-30 21:15:51 +00008477 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008478 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8479 return true;
8480 }
8481
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008482 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008483
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008484 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008485 bool VisitBinaryOperator(const BinaryOperator *E);
8486 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008487 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008488
John McCallb1fb0d32010-05-07 22:08:54 +00008489 bool VisitUnaryReal(const UnaryOperator *E);
8490 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008491
Richard Smithfddd3842011-12-30 21:15:51 +00008492 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008493};
8494} // end anonymous namespace
8495
8496static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008497 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008498 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008499}
8500
Jay Foad39c79802011-01-12 09:06:06 +00008501static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008502 QualType ResultTy,
8503 const Expr *Arg,
8504 bool SNaN,
8505 llvm::APFloat &Result) {
8506 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8507 if (!S) return false;
8508
8509 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8510
8511 llvm::APInt fill;
8512
8513 // Treat empty strings as if they were zero.
8514 if (S->getString().empty())
8515 fill = llvm::APInt(32, 0);
8516 else if (S->getString().getAsInteger(0, fill))
8517 return false;
8518
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008519 if (Context.getTargetInfo().isNan2008()) {
8520 if (SNaN)
8521 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8522 else
8523 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8524 } else {
8525 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8526 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8527 // a different encoding to what became a standard in 2008, and for pre-
8528 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8529 // sNaN. This is now known as "legacy NaN" encoding.
8530 if (SNaN)
8531 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8532 else
8533 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8534 }
8535
John McCall16291492010-02-28 13:00:19 +00008536 return true;
8537}
8538
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008539bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008540 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008541 default:
8542 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8543
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008544 case Builtin::BI__builtin_huge_val:
8545 case Builtin::BI__builtin_huge_valf:
8546 case Builtin::BI__builtin_huge_vall:
8547 case Builtin::BI__builtin_inf:
8548 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008549 case Builtin::BI__builtin_infl: {
8550 const llvm::fltSemantics &Sem =
8551 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008552 Result = llvm::APFloat::getInf(Sem);
8553 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008554 }
Mike Stump11289f42009-09-09 15:08:12 +00008555
John McCall16291492010-02-28 13:00:19 +00008556 case Builtin::BI__builtin_nans:
8557 case Builtin::BI__builtin_nansf:
8558 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008559 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8560 true, Result))
8561 return Error(E);
8562 return true;
John McCall16291492010-02-28 13:00:19 +00008563
Chris Lattner0b7282e2008-10-06 06:31:58 +00008564 case Builtin::BI__builtin_nan:
8565 case Builtin::BI__builtin_nanf:
8566 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008567 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008568 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008569 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8570 false, Result))
8571 return Error(E);
8572 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008573
8574 case Builtin::BI__builtin_fabs:
8575 case Builtin::BI__builtin_fabsf:
8576 case Builtin::BI__builtin_fabsl:
8577 if (!EvaluateFloat(E->getArg(0), Result, Info))
8578 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008579
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008580 if (Result.isNegative())
8581 Result.changeSign();
8582 return true;
8583
Richard Smith8889a3d2013-06-13 06:26:32 +00008584 // FIXME: Builtin::BI__builtin_powi
8585 // FIXME: Builtin::BI__builtin_powif
8586 // FIXME: Builtin::BI__builtin_powil
8587
Mike Stump11289f42009-09-09 15:08:12 +00008588 case Builtin::BI__builtin_copysign:
8589 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008590 case Builtin::BI__builtin_copysignl: {
8591 APFloat RHS(0.);
8592 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8593 !EvaluateFloat(E->getArg(1), RHS, Info))
8594 return false;
8595 Result.copySign(RHS);
8596 return true;
8597 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008598 }
8599}
8600
John McCallb1fb0d32010-05-07 22:08:54 +00008601bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008602 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8603 ComplexValue CV;
8604 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8605 return false;
8606 Result = CV.FloatReal;
8607 return true;
8608 }
8609
8610 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008611}
8612
8613bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008614 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8615 ComplexValue CV;
8616 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8617 return false;
8618 Result = CV.FloatImag;
8619 return true;
8620 }
8621
Richard Smith4a678122011-10-24 18:44:57 +00008622 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008623 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8624 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008625 return true;
8626}
8627
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008628bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008629 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008630 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008631 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008632 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008633 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008634 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8635 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008636 Result.changeSign();
8637 return true;
8638 }
8639}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008640
Eli Friedman24c01542008-08-22 00:06:13 +00008641bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008642 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8643 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008644
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008645 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008646 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008647 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008648 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008649 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8650 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008651}
8652
8653bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8654 Result = E->getValue();
8655 return true;
8656}
8657
Peter Collingbournee9200682011-05-13 03:29:01 +00008658bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8659 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008660
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008661 switch (E->getCastKind()) {
8662 default:
Richard Smith11562c52011-10-28 17:51:58 +00008663 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008664
8665 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008666 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008667 return EvaluateInteger(SubExpr, IntResult, Info) &&
8668 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8669 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008670 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008671
8672 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008673 if (!Visit(SubExpr))
8674 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008675 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8676 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008677 }
John McCalld7646252010-11-14 08:17:51 +00008678
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008679 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008680 ComplexValue V;
8681 if (!EvaluateComplex(SubExpr, V, Info))
8682 return false;
8683 Result = V.getComplexFloatReal();
8684 return true;
8685 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008686 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008687}
8688
Eli Friedman24c01542008-08-22 00:06:13 +00008689//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008690// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008691//===----------------------------------------------------------------------===//
8692
8693namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008694class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008695 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008696 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008697
Anders Carlsson537969c2008-11-16 20:27:53 +00008698public:
John McCall93d91dc2010-05-07 17:22:02 +00008699 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008700 : ExprEvaluatorBaseTy(info), Result(Result) {}
8701
Richard Smith2e312c82012-03-03 22:46:17 +00008702 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008703 Result.setFrom(V);
8704 return true;
8705 }
Mike Stump11289f42009-09-09 15:08:12 +00008706
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008707 bool ZeroInitialization(const Expr *E);
8708
Anders Carlsson537969c2008-11-16 20:27:53 +00008709 //===--------------------------------------------------------------------===//
8710 // Visitor Methods
8711 //===--------------------------------------------------------------------===//
8712
Peter Collingbournee9200682011-05-13 03:29:01 +00008713 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008714 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008715 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008716 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008717 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008718};
8719} // end anonymous namespace
8720
John McCall93d91dc2010-05-07 17:22:02 +00008721static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8722 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008723 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008724 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008725}
8726
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008727bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008728 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008729 if (ElemTy->isRealFloatingType()) {
8730 Result.makeComplexFloat();
8731 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8732 Result.FloatReal = Zero;
8733 Result.FloatImag = Zero;
8734 } else {
8735 Result.makeComplexInt();
8736 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8737 Result.IntReal = Zero;
8738 Result.IntImag = Zero;
8739 }
8740 return true;
8741}
8742
Peter Collingbournee9200682011-05-13 03:29:01 +00008743bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8744 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008745
8746 if (SubExpr->getType()->isRealFloatingType()) {
8747 Result.makeComplexFloat();
8748 APFloat &Imag = Result.FloatImag;
8749 if (!EvaluateFloat(SubExpr, Imag, Info))
8750 return false;
8751
8752 Result.FloatReal = APFloat(Imag.getSemantics());
8753 return true;
8754 } else {
8755 assert(SubExpr->getType()->isIntegerType() &&
8756 "Unexpected imaginary literal.");
8757
8758 Result.makeComplexInt();
8759 APSInt &Imag = Result.IntImag;
8760 if (!EvaluateInteger(SubExpr, Imag, Info))
8761 return false;
8762
8763 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8764 return true;
8765 }
8766}
8767
Peter Collingbournee9200682011-05-13 03:29:01 +00008768bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008769
John McCallfcef3cf2010-12-14 17:51:41 +00008770 switch (E->getCastKind()) {
8771 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008772 case CK_BaseToDerived:
8773 case CK_DerivedToBase:
8774 case CK_UncheckedDerivedToBase:
8775 case CK_Dynamic:
8776 case CK_ToUnion:
8777 case CK_ArrayToPointerDecay:
8778 case CK_FunctionToPointerDecay:
8779 case CK_NullToPointer:
8780 case CK_NullToMemberPointer:
8781 case CK_BaseToDerivedMemberPointer:
8782 case CK_DerivedToBaseMemberPointer:
8783 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008784 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008785 case CK_ConstructorConversion:
8786 case CK_IntegralToPointer:
8787 case CK_PointerToIntegral:
8788 case CK_PointerToBoolean:
8789 case CK_ToVoid:
8790 case CK_VectorSplat:
8791 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008792 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008793 case CK_IntegralToBoolean:
8794 case CK_IntegralToFloating:
8795 case CK_FloatingToIntegral:
8796 case CK_FloatingToBoolean:
8797 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008798 case CK_CPointerToObjCPointerCast:
8799 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008800 case CK_AnyPointerToBlockPointerCast:
8801 case CK_ObjCObjectLValueCast:
8802 case CK_FloatingComplexToReal:
8803 case CK_FloatingComplexToBoolean:
8804 case CK_IntegralComplexToReal:
8805 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008806 case CK_ARCProduceObject:
8807 case CK_ARCConsumeObject:
8808 case CK_ARCReclaimReturnedObject:
8809 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008810 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008811 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008812 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008813 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008814 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008815 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00008816 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008817
John McCallfcef3cf2010-12-14 17:51:41 +00008818 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008819 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008820 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008821 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008822
8823 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008824 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008825 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008826 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008827
8828 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008829 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008830 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008831 return false;
8832
John McCallfcef3cf2010-12-14 17:51:41 +00008833 Result.makeComplexFloat();
8834 Result.FloatImag = APFloat(Real.getSemantics());
8835 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008836 }
8837
John McCallfcef3cf2010-12-14 17:51:41 +00008838 case CK_FloatingComplexCast: {
8839 if (!Visit(E->getSubExpr()))
8840 return false;
8841
8842 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8843 QualType From
8844 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8845
Richard Smith357362d2011-12-13 06:39:58 +00008846 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8847 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008848 }
8849
8850 case CK_FloatingComplexToIntegralComplex: {
8851 if (!Visit(E->getSubExpr()))
8852 return false;
8853
8854 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8855 QualType From
8856 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8857 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008858 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8859 To, Result.IntReal) &&
8860 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8861 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008862 }
8863
8864 case CK_IntegralRealToComplex: {
8865 APSInt &Real = Result.IntReal;
8866 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8867 return false;
8868
8869 Result.makeComplexInt();
8870 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8871 return true;
8872 }
8873
8874 case CK_IntegralComplexCast: {
8875 if (!Visit(E->getSubExpr()))
8876 return false;
8877
8878 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8879 QualType From
8880 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8881
Richard Smith911e1422012-01-30 22:27:01 +00008882 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8883 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008884 return true;
8885 }
8886
8887 case CK_IntegralComplexToFloatingComplex: {
8888 if (!Visit(E->getSubExpr()))
8889 return false;
8890
Ted Kremenek28831752012-08-23 20:46:57 +00008891 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008892 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008893 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008894 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008895 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8896 To, Result.FloatReal) &&
8897 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8898 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008899 }
8900 }
8901
8902 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008903}
8904
John McCall93d91dc2010-05-07 17:22:02 +00008905bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008906 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008907 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8908
Chandler Carrutha216cad2014-10-11 00:57:18 +00008909 // Track whether the LHS or RHS is real at the type system level. When this is
8910 // the case we can simplify our evaluation strategy.
8911 bool LHSReal = false, RHSReal = false;
8912
8913 bool LHSOK;
8914 if (E->getLHS()->getType()->isRealFloatingType()) {
8915 LHSReal = true;
8916 APFloat &Real = Result.FloatReal;
8917 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8918 if (LHSOK) {
8919 Result.makeComplexFloat();
8920 Result.FloatImag = APFloat(Real.getSemantics());
8921 }
8922 } else {
8923 LHSOK = Visit(E->getLHS());
8924 }
George Burgess IVa145e252016-05-25 22:38:36 +00008925 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008926 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008927
John McCall93d91dc2010-05-07 17:22:02 +00008928 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008929 if (E->getRHS()->getType()->isRealFloatingType()) {
8930 RHSReal = true;
8931 APFloat &Real = RHS.FloatReal;
8932 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8933 return false;
8934 RHS.makeComplexFloat();
8935 RHS.FloatImag = APFloat(Real.getSemantics());
8936 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008937 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008938
Chandler Carrutha216cad2014-10-11 00:57:18 +00008939 assert(!(LHSReal && RHSReal) &&
8940 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008941 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008942 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008943 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008944 if (Result.isComplexFloat()) {
8945 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8946 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008947 if (LHSReal)
8948 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8949 else if (!RHSReal)
8950 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8951 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008952 } else {
8953 Result.getComplexIntReal() += RHS.getComplexIntReal();
8954 Result.getComplexIntImag() += RHS.getComplexIntImag();
8955 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008956 break;
John McCalle3027922010-08-25 11:45:40 +00008957 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008958 if (Result.isComplexFloat()) {
8959 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8960 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008961 if (LHSReal) {
8962 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8963 Result.getComplexFloatImag().changeSign();
8964 } else if (!RHSReal) {
8965 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8966 APFloat::rmNearestTiesToEven);
8967 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008968 } else {
8969 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8970 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8971 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008972 break;
John McCalle3027922010-08-25 11:45:40 +00008973 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008974 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008975 // This is an implementation of complex multiplication according to the
8976 // constraints laid out in C11 Annex G. The implemantion uses the
8977 // following naming scheme:
8978 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008979 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008980 APFloat &A = LHS.getComplexFloatReal();
8981 APFloat &B = LHS.getComplexFloatImag();
8982 APFloat &C = RHS.getComplexFloatReal();
8983 APFloat &D = RHS.getComplexFloatImag();
8984 APFloat &ResR = Result.getComplexFloatReal();
8985 APFloat &ResI = Result.getComplexFloatImag();
8986 if (LHSReal) {
8987 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8988 ResR = A * C;
8989 ResI = A * D;
8990 } else if (RHSReal) {
8991 ResR = C * A;
8992 ResI = C * B;
8993 } else {
8994 // In the fully general case, we need to handle NaNs and infinities
8995 // robustly.
8996 APFloat AC = A * C;
8997 APFloat BD = B * D;
8998 APFloat AD = A * D;
8999 APFloat BC = B * C;
9000 ResR = AC - BD;
9001 ResI = AD + BC;
9002 if (ResR.isNaN() && ResI.isNaN()) {
9003 bool Recalc = false;
9004 if (A.isInfinity() || B.isInfinity()) {
9005 A = APFloat::copySign(
9006 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9007 B = APFloat::copySign(
9008 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9009 if (C.isNaN())
9010 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9011 if (D.isNaN())
9012 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9013 Recalc = true;
9014 }
9015 if (C.isInfinity() || D.isInfinity()) {
9016 C = APFloat::copySign(
9017 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9018 D = APFloat::copySign(
9019 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9020 if (A.isNaN())
9021 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9022 if (B.isNaN())
9023 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9024 Recalc = true;
9025 }
9026 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9027 AD.isInfinity() || BC.isInfinity())) {
9028 if (A.isNaN())
9029 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9030 if (B.isNaN())
9031 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9032 if (C.isNaN())
9033 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9034 if (D.isNaN())
9035 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9036 Recalc = true;
9037 }
9038 if (Recalc) {
9039 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9040 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9041 }
9042 }
9043 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009044 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009045 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009046 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009047 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9048 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009049 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009050 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9051 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9052 }
9053 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009054 case BO_Div:
9055 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009056 // This is an implementation of complex division according to the
9057 // constraints laid out in C11 Annex G. The implemantion uses the
9058 // following naming scheme:
9059 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009060 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009061 APFloat &A = LHS.getComplexFloatReal();
9062 APFloat &B = LHS.getComplexFloatImag();
9063 APFloat &C = RHS.getComplexFloatReal();
9064 APFloat &D = RHS.getComplexFloatImag();
9065 APFloat &ResR = Result.getComplexFloatReal();
9066 APFloat &ResI = Result.getComplexFloatImag();
9067 if (RHSReal) {
9068 ResR = A / C;
9069 ResI = B / C;
9070 } else {
9071 if (LHSReal) {
9072 // No real optimizations we can do here, stub out with zero.
9073 B = APFloat::getZero(A.getSemantics());
9074 }
9075 int DenomLogB = 0;
9076 APFloat MaxCD = maxnum(abs(C), abs(D));
9077 if (MaxCD.isFinite()) {
9078 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009079 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9080 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009081 }
9082 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009083 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9084 APFloat::rmNearestTiesToEven);
9085 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9086 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009087 if (ResR.isNaN() && ResI.isNaN()) {
9088 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9089 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9090 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9091 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9092 D.isFinite()) {
9093 A = APFloat::copySign(
9094 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9095 B = APFloat::copySign(
9096 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9097 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9098 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9099 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9100 C = APFloat::copySign(
9101 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9102 D = APFloat::copySign(
9103 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9104 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9105 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9106 }
9107 }
9108 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009109 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009110 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9111 return Error(E, diag::note_expr_divide_by_zero);
9112
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009113 ComplexValue LHS = Result;
9114 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9115 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9116 Result.getComplexIntReal() =
9117 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9118 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9119 Result.getComplexIntImag() =
9120 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9121 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9122 }
9123 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009124 }
9125
John McCall93d91dc2010-05-07 17:22:02 +00009126 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009127}
9128
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009129bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9130 // Get the operand value into 'Result'.
9131 if (!Visit(E->getSubExpr()))
9132 return false;
9133
9134 switch (E->getOpcode()) {
9135 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009136 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009137 case UO_Extension:
9138 return true;
9139 case UO_Plus:
9140 // The result is always just the subexpr.
9141 return true;
9142 case UO_Minus:
9143 if (Result.isComplexFloat()) {
9144 Result.getComplexFloatReal().changeSign();
9145 Result.getComplexFloatImag().changeSign();
9146 }
9147 else {
9148 Result.getComplexIntReal() = -Result.getComplexIntReal();
9149 Result.getComplexIntImag() = -Result.getComplexIntImag();
9150 }
9151 return true;
9152 case UO_Not:
9153 if (Result.isComplexFloat())
9154 Result.getComplexFloatImag().changeSign();
9155 else
9156 Result.getComplexIntImag() = -Result.getComplexIntImag();
9157 return true;
9158 }
9159}
9160
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009161bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9162 if (E->getNumInits() == 2) {
9163 if (E->getType()->isComplexType()) {
9164 Result.makeComplexFloat();
9165 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9166 return false;
9167 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9168 return false;
9169 } else {
9170 Result.makeComplexInt();
9171 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9172 return false;
9173 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9174 return false;
9175 }
9176 return true;
9177 }
9178 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9179}
9180
Anders Carlsson537969c2008-11-16 20:27:53 +00009181//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009182// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9183// implicit conversion.
9184//===----------------------------------------------------------------------===//
9185
9186namespace {
9187class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009188 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009189 APValue &Result;
9190public:
9191 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9192 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9193
9194 bool Success(const APValue &V, const Expr *E) {
9195 Result = V;
9196 return true;
9197 }
9198
9199 bool ZeroInitialization(const Expr *E) {
9200 ImplicitValueInitExpr VIE(
9201 E->getType()->castAs<AtomicType>()->getValueType());
9202 return Evaluate(Result, Info, &VIE);
9203 }
9204
9205 bool VisitCastExpr(const CastExpr *E) {
9206 switch (E->getCastKind()) {
9207 default:
9208 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9209 case CK_NonAtomicToAtomic:
9210 return Evaluate(Result, Info, E->getSubExpr());
9211 }
9212 }
9213};
9214} // end anonymous namespace
9215
9216static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9217 assert(E->isRValue() && E->getType()->isAtomicType());
9218 return AtomicExprEvaluator(Info, Result).Visit(E);
9219}
9220
9221//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009222// Void expression evaluation, primarily for a cast to void on the LHS of a
9223// comma operator
9224//===----------------------------------------------------------------------===//
9225
9226namespace {
9227class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009228 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009229public:
9230 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9231
Richard Smith2e312c82012-03-03 22:46:17 +00009232 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009233
9234 bool VisitCastExpr(const CastExpr *E) {
9235 switch (E->getCastKind()) {
9236 default:
9237 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9238 case CK_ToVoid:
9239 VisitIgnoredValue(E->getSubExpr());
9240 return true;
9241 }
9242 }
Hal Finkela8443c32014-07-17 14:49:58 +00009243
9244 bool VisitCallExpr(const CallExpr *E) {
9245 switch (E->getBuiltinCallee()) {
9246 default:
9247 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9248 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009249 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009250 // The argument is not evaluated!
9251 return true;
9252 }
9253 }
Richard Smith42d3af92011-12-07 00:43:50 +00009254};
9255} // end anonymous namespace
9256
9257static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9258 assert(E->isRValue() && E->getType()->isVoidType());
9259 return VoidExprEvaluator(Info).Visit(E);
9260}
9261
9262//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009263// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009264//===----------------------------------------------------------------------===//
9265
Richard Smith2e312c82012-03-03 22:46:17 +00009266static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009267 // In C, function designators are not lvalues, but we evaluate them as if they
9268 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009269 QualType T = E->getType();
9270 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009271 LValue LV;
9272 if (!EvaluateLValue(E, LV, Info))
9273 return false;
9274 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009275 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009276 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009277 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009278 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009279 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009280 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009281 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009282 LValue LV;
9283 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009284 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009285 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009286 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009287 llvm::APFloat F(0.0);
9288 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009289 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009290 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009291 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009292 ComplexValue C;
9293 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009294 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009295 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009296 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009297 MemberPtr P;
9298 if (!EvaluateMemberPointer(E, P, Info))
9299 return false;
9300 P.moveInto(Result);
9301 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009302 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009303 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009304 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009305 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9306 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009307 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009308 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009309 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009310 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009311 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009312 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9313 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009314 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009315 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009316 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009317 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009318 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009319 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009320 if (!EvaluateVoid(E, Info))
9321 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009322 } else if (T->isAtomicType()) {
9323 if (!EvaluateAtomic(E, Result, Info))
9324 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009325 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009326 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009327 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009328 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009329 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009330 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009331 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009332
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009333 return true;
9334}
9335
Richard Smithb228a862012-02-15 02:18:13 +00009336/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9337/// cases, the in-place evaluation is essential, since later initializers for
9338/// an object can indirectly refer to subobjects which were initialized earlier.
9339static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009340 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009341 assert(!E->isValueDependent());
9342
Richard Smith7525ff62013-05-09 07:14:00 +00009343 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009344 return false;
9345
9346 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009347 // Evaluate arrays and record types in-place, so that later initializers can
9348 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009349 if (E->getType()->isArrayType())
9350 return EvaluateArray(E, This, Result, Info);
9351 else if (E->getType()->isRecordType())
9352 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009353 }
9354
9355 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009356 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009357}
9358
Richard Smithf57d8cb2011-12-09 22:58:01 +00009359/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9360/// lvalue-to-rvalue cast if it is an lvalue.
9361static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009362 if (E->getType().isNull())
9363 return false;
9364
Richard Smithfddd3842011-12-30 21:15:51 +00009365 if (!CheckLiteralType(Info, E))
9366 return false;
9367
Richard Smith2e312c82012-03-03 22:46:17 +00009368 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009369 return false;
9370
9371 if (E->isGLValue()) {
9372 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009373 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009374 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009375 return false;
9376 }
9377
Richard Smith2e312c82012-03-03 22:46:17 +00009378 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009379 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009380}
Richard Smith11562c52011-10-28 17:51:58 +00009381
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009382static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9383 const ASTContext &Ctx, bool &IsConst) {
9384 // Fast-path evaluations of integer literals, since we sometimes see files
9385 // containing vast quantities of these.
9386 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9387 Result.Val = APValue(APSInt(L->getValue(),
9388 L->getType()->isUnsignedIntegerType()));
9389 IsConst = true;
9390 return true;
9391 }
James Dennett0492ef02014-03-14 17:44:10 +00009392
9393 // This case should be rare, but we need to check it before we check on
9394 // the type below.
9395 if (Exp->getType().isNull()) {
9396 IsConst = false;
9397 return true;
9398 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009399
9400 // FIXME: Evaluating values of large array and record types can cause
9401 // performance problems. Only do so in C++11 for now.
9402 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9403 Exp->getType()->isRecordType()) &&
9404 !Ctx.getLangOpts().CPlusPlus11) {
9405 IsConst = false;
9406 return true;
9407 }
9408 return false;
9409}
9410
9411
Richard Smith7b553f12011-10-29 00:50:52 +00009412/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009413/// any crazy technique (that has nothing to do with language standards) that
9414/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009415/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9416/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009417bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009418 bool IsConst;
9419 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9420 return IsConst;
9421
Richard Smith6d4c6582013-11-05 22:18:15 +00009422 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009423 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009424}
9425
Jay Foad39c79802011-01-12 09:06:06 +00009426bool Expr::EvaluateAsBooleanCondition(bool &Result,
9427 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009428 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009429 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009430 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009431}
9432
Richard Smithce8eca52015-12-08 03:21:47 +00009433static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9434 Expr::SideEffectsKind SEK) {
9435 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9436 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9437}
9438
Richard Smith5fab0c92011-12-28 19:48:30 +00009439bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9440 SideEffectsKind AllowSideEffects) const {
9441 if (!getType()->isIntegralOrEnumerationType())
9442 return false;
9443
Richard Smith11562c52011-10-28 17:51:58 +00009444 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009445 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009446 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009447 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009448
Richard Smith11562c52011-10-28 17:51:58 +00009449 Result = ExprResult.Val.getInt();
9450 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009451}
9452
Richard Trieube234c32016-04-21 21:04:55 +00009453bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9454 SideEffectsKind AllowSideEffects) const {
9455 if (!getType()->isRealFloatingType())
9456 return false;
9457
9458 EvalResult ExprResult;
9459 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9460 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9461 return false;
9462
9463 Result = ExprResult.Val.getFloat();
9464 return true;
9465}
9466
Jay Foad39c79802011-01-12 09:06:06 +00009467bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009468 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009469
John McCall45d55e42010-05-07 21:00:08 +00009470 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009471 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9472 !CheckLValueConstantExpression(Info, getExprLoc(),
9473 Ctx.getLValueReferenceType(getType()), LV))
9474 return false;
9475
Richard Smith2e312c82012-03-03 22:46:17 +00009476 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009477 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009478}
9479
Richard Smithd0b4dd62011-12-19 06:19:21 +00009480bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9481 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009482 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009483 // FIXME: Evaluating initializers for large array and record types can cause
9484 // performance problems. Only do so in C++11 for now.
9485 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009486 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009487 return false;
9488
Richard Smithd0b4dd62011-12-19 06:19:21 +00009489 Expr::EvalStatus EStatus;
9490 EStatus.Diag = &Notes;
9491
Richard Smith0c6124b2015-12-03 01:36:22 +00009492 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9493 ? EvalInfo::EM_ConstantExpression
9494 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009495 InitInfo.setEvaluatingDecl(VD, Value);
9496
9497 LValue LVal;
9498 LVal.set(VD);
9499
Richard Smithfddd3842011-12-30 21:15:51 +00009500 // C++11 [basic.start.init]p2:
9501 // Variables with static storage duration or thread storage duration shall be
9502 // zero-initialized before any other initialization takes place.
9503 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009504 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009505 !VD->getType()->isReferenceType()) {
9506 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009507 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009508 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009509 return false;
9510 }
9511
Richard Smith7525ff62013-05-09 07:14:00 +00009512 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9513 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009514 EStatus.HasSideEffects)
9515 return false;
9516
9517 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9518 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009519}
9520
Richard Smith7b553f12011-10-29 00:50:52 +00009521/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9522/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009523bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009524 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009525 return EvaluateAsRValue(Result, Ctx) &&
9526 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009527}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009528
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009529APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009530 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009531 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009532 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009533 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009534 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009535 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009536 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009537
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009538 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009539}
John McCall864e3962010-05-07 05:32:02 +00009540
Richard Smithe9ff7702013-11-05 22:23:30 +00009541void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009542 bool IsConst;
9543 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009544 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009545 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009546 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9547 }
9548}
9549
Richard Smithe6c01442013-06-05 00:46:14 +00009550bool Expr::EvalResult::isGlobalLValue() const {
9551 assert(Val.isLValue());
9552 return IsGlobalLValue(Val.getLValueBase());
9553}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009554
9555
John McCall864e3962010-05-07 05:32:02 +00009556/// isIntegerConstantExpr - this recursive routine will test if an expression is
9557/// an integer constant expression.
9558
9559/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9560/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009561
9562// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009563// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9564// and a (possibly null) SourceLocation indicating the location of the problem.
9565//
John McCall864e3962010-05-07 05:32:02 +00009566// Note that to reduce code duplication, this helper does no evaluation
9567// itself; the caller checks whether the expression is evaluatable, and
9568// in the rare cases where CheckICE actually cares about the evaluated
9569// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009570
Dan Gohman28ade552010-07-26 21:25:24 +00009571namespace {
9572
Richard Smith9e575da2012-12-28 13:25:52 +00009573enum ICEKind {
9574 /// This expression is an ICE.
9575 IK_ICE,
9576 /// This expression is not an ICE, but if it isn't evaluated, it's
9577 /// a legal subexpression for an ICE. This return value is used to handle
9578 /// the comma operator in C99 mode, and non-constant subexpressions.
9579 IK_ICEIfUnevaluated,
9580 /// This expression is not an ICE, and is not a legal subexpression for one.
9581 IK_NotICE
9582};
9583
John McCall864e3962010-05-07 05:32:02 +00009584struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009585 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009586 SourceLocation Loc;
9587
Richard Smith9e575da2012-12-28 13:25:52 +00009588 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009589};
9590
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009591}
Dan Gohman28ade552010-07-26 21:25:24 +00009592
Richard Smith9e575da2012-12-28 13:25:52 +00009593static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9594
9595static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009596
Craig Toppera31a8822013-08-22 07:09:37 +00009597static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009598 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009599 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009600 !EVResult.Val.isInt())
9601 return ICEDiag(IK_NotICE, E->getLocStart());
9602
John McCall864e3962010-05-07 05:32:02 +00009603 return NoDiag();
9604}
9605
Craig Toppera31a8822013-08-22 07:09:37 +00009606static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009607 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009608 if (!E->getType()->isIntegralOrEnumerationType())
9609 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009610
9611 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009612#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009613#define STMT(Node, Base) case Expr::Node##Class:
9614#define EXPR(Node, Base)
9615#include "clang/AST/StmtNodes.inc"
9616 case Expr::PredefinedExprClass:
9617 case Expr::FloatingLiteralClass:
9618 case Expr::ImaginaryLiteralClass:
9619 case Expr::StringLiteralClass:
9620 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009621 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009622 case Expr::MemberExprClass:
9623 case Expr::CompoundAssignOperatorClass:
9624 case Expr::CompoundLiteralExprClass:
9625 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009626 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009627 case Expr::ArrayInitLoopExprClass:
9628 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009629 case Expr::NoInitExprClass:
9630 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009631 case Expr::ImplicitValueInitExprClass:
9632 case Expr::ParenListExprClass:
9633 case Expr::VAArgExprClass:
9634 case Expr::AddrLabelExprClass:
9635 case Expr::StmtExprClass:
9636 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009637 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009638 case Expr::CXXDynamicCastExprClass:
9639 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009640 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009641 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009642 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009643 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009644 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009645 case Expr::CXXThisExprClass:
9646 case Expr::CXXThrowExprClass:
9647 case Expr::CXXNewExprClass:
9648 case Expr::CXXDeleteExprClass:
9649 case Expr::CXXPseudoDestructorExprClass:
9650 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009651 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009652 case Expr::DependentScopeDeclRefExprClass:
9653 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009654 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009655 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009656 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009657 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009658 case Expr::CXXTemporaryObjectExprClass:
9659 case Expr::CXXUnresolvedConstructExprClass:
9660 case Expr::CXXDependentScopeMemberExprClass:
9661 case Expr::UnresolvedMemberExprClass:
9662 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009663 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009664 case Expr::ObjCArrayLiteralClass:
9665 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009666 case Expr::ObjCEncodeExprClass:
9667 case Expr::ObjCMessageExprClass:
9668 case Expr::ObjCSelectorExprClass:
9669 case Expr::ObjCProtocolExprClass:
9670 case Expr::ObjCIvarRefExprClass:
9671 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009672 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009673 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009674 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009675 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009676 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009677 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009678 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009679 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009680 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009681 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009682 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009683 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009684 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009685 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009686 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009687 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009688 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009689 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009690 case Expr::CoawaitExprClass:
9691 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009692 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009693
Richard Smithf137f932014-01-25 20:50:08 +00009694 case Expr::InitListExprClass: {
9695 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9696 // form "T x = { a };" is equivalent to "T x = a;".
9697 // Unless we're initializing a reference, T is a scalar as it is known to be
9698 // of integral or enumeration type.
9699 if (E->isRValue())
9700 if (cast<InitListExpr>(E)->getNumInits() == 1)
9701 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9702 return ICEDiag(IK_NotICE, E->getLocStart());
9703 }
9704
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009705 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009706 case Expr::GNUNullExprClass:
9707 // GCC considers the GNU __null value to be an integral constant expression.
9708 return NoDiag();
9709
John McCall7c454bb2011-07-15 05:09:51 +00009710 case Expr::SubstNonTypeTemplateParmExprClass:
9711 return
9712 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9713
John McCall864e3962010-05-07 05:32:02 +00009714 case Expr::ParenExprClass:
9715 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009716 case Expr::GenericSelectionExprClass:
9717 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009718 case Expr::IntegerLiteralClass:
9719 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009720 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009721 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009722 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009723 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009724 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009725 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009726 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009727 return NoDiag();
9728 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009729 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009730 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9731 // constant expressions, but they can never be ICEs because an ICE cannot
9732 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009733 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009734 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009735 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009736 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009737 }
Richard Smith6365c912012-02-24 22:12:32 +00009738 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009739 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9740 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009741 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009742 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009743 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009744 // Parameter variables are never constants. Without this check,
9745 // getAnyInitializer() can find a default argument, which leads
9746 // to chaos.
9747 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009748 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009749
9750 // C++ 7.1.5.1p2
9751 // A variable of non-volatile const-qualified integral or enumeration
9752 // type initialized by an ICE can be used in ICEs.
9753 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009754 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009755 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009756
Richard Smithd0b4dd62011-12-19 06:19:21 +00009757 const VarDecl *VD;
9758 // Look for a declaration of this variable that has an initializer, and
9759 // check whether it is an ICE.
9760 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9761 return NoDiag();
9762 else
Richard Smith9e575da2012-12-28 13:25:52 +00009763 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009764 }
9765 }
Richard Smith9e575da2012-12-28 13:25:52 +00009766 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009767 }
John McCall864e3962010-05-07 05:32:02 +00009768 case Expr::UnaryOperatorClass: {
9769 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9770 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009771 case UO_PostInc:
9772 case UO_PostDec:
9773 case UO_PreInc:
9774 case UO_PreDec:
9775 case UO_AddrOf:
9776 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009777 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009778 // C99 6.6/3 allows increment and decrement within unevaluated
9779 // subexpressions of constant expressions, but they can never be ICEs
9780 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009781 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009782 case UO_Extension:
9783 case UO_LNot:
9784 case UO_Plus:
9785 case UO_Minus:
9786 case UO_Not:
9787 case UO_Real:
9788 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009789 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009790 }
Richard Smith9e575da2012-12-28 13:25:52 +00009791
John McCall864e3962010-05-07 05:32:02 +00009792 // OffsetOf falls through here.
9793 }
9794 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009795 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9796 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9797 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9798 // compliance: we should warn earlier for offsetof expressions with
9799 // array subscripts that aren't ICEs, and if the array subscripts
9800 // are ICEs, the value of the offsetof must be an integer constant.
9801 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009802 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009803 case Expr::UnaryExprOrTypeTraitExprClass: {
9804 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9805 if ((Exp->getKind() == UETT_SizeOf) &&
9806 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009807 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009808 return NoDiag();
9809 }
9810 case Expr::BinaryOperatorClass: {
9811 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9812 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009813 case BO_PtrMemD:
9814 case BO_PtrMemI:
9815 case BO_Assign:
9816 case BO_MulAssign:
9817 case BO_DivAssign:
9818 case BO_RemAssign:
9819 case BO_AddAssign:
9820 case BO_SubAssign:
9821 case BO_ShlAssign:
9822 case BO_ShrAssign:
9823 case BO_AndAssign:
9824 case BO_XorAssign:
9825 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009826 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9827 // constant expressions, but they can never be ICEs because an ICE cannot
9828 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009829 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009830
John McCalle3027922010-08-25 11:45:40 +00009831 case BO_Mul:
9832 case BO_Div:
9833 case BO_Rem:
9834 case BO_Add:
9835 case BO_Sub:
9836 case BO_Shl:
9837 case BO_Shr:
9838 case BO_LT:
9839 case BO_GT:
9840 case BO_LE:
9841 case BO_GE:
9842 case BO_EQ:
9843 case BO_NE:
9844 case BO_And:
9845 case BO_Xor:
9846 case BO_Or:
9847 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009848 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9849 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009850 if (Exp->getOpcode() == BO_Div ||
9851 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009852 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009853 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009854 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009855 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009856 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009857 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009858 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009859 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009860 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009861 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009862 }
9863 }
9864 }
John McCalle3027922010-08-25 11:45:40 +00009865 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009866 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009867 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9868 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009869 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9870 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009871 } else {
9872 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009873 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009874 }
9875 }
Richard Smith9e575da2012-12-28 13:25:52 +00009876 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009877 }
John McCalle3027922010-08-25 11:45:40 +00009878 case BO_LAnd:
9879 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009880 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9881 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009882 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009883 // Rare case where the RHS has a comma "side-effect"; we need
9884 // to actually check the condition to see whether the side
9885 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009886 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009887 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009888 return RHSResult;
9889 return NoDiag();
9890 }
9891
Richard Smith9e575da2012-12-28 13:25:52 +00009892 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009893 }
9894 }
9895 }
9896 case Expr::ImplicitCastExprClass:
9897 case Expr::CStyleCastExprClass:
9898 case Expr::CXXFunctionalCastExprClass:
9899 case Expr::CXXStaticCastExprClass:
9900 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009901 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009902 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009903 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009904 if (isa<ExplicitCastExpr>(E)) {
9905 if (const FloatingLiteral *FL
9906 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9907 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9908 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9909 APSInt IgnoredVal(DestWidth, !DestSigned);
9910 bool Ignored;
9911 // If the value does not fit in the destination type, the behavior is
9912 // undefined, so we are not required to treat it as a constant
9913 // expression.
9914 if (FL->getValue().convertToInteger(IgnoredVal,
9915 llvm::APFloat::rmTowardZero,
9916 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009917 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009918 return NoDiag();
9919 }
9920 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009921 switch (cast<CastExpr>(E)->getCastKind()) {
9922 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009923 case CK_AtomicToNonAtomic:
9924 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009925 case CK_NoOp:
9926 case CK_IntegralToBoolean:
9927 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009928 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009929 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009930 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009931 }
John McCall864e3962010-05-07 05:32:02 +00009932 }
John McCallc07a0c72011-02-17 10:25:35 +00009933 case Expr::BinaryConditionalOperatorClass: {
9934 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9935 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009936 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009937 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009938 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9939 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9940 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009941 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009942 return FalseResult;
9943 }
John McCall864e3962010-05-07 05:32:02 +00009944 case Expr::ConditionalOperatorClass: {
9945 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9946 // If the condition (ignoring parens) is a __builtin_constant_p call,
9947 // then only the true side is actually considered in an integer constant
9948 // expression, and it is fully evaluated. This is an important GNU
9949 // extension. See GCC PR38377 for discussion.
9950 if (const CallExpr *CallCE
9951 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009952 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009953 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009954 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009955 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009956 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009957
Richard Smithf57d8cb2011-12-09 22:58:01 +00009958 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9959 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009960
Richard Smith9e575da2012-12-28 13:25:52 +00009961 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009962 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009963 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009964 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009965 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009966 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009967 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009968 return NoDiag();
9969 // Rare case where the diagnostics depend on which side is evaluated
9970 // Note that if we get here, CondResult is 0, and at least one of
9971 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009972 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009973 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009974 return TrueResult;
9975 }
9976 case Expr::CXXDefaultArgExprClass:
9977 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009978 case Expr::CXXDefaultInitExprClass:
9979 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009980 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009981 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009982 }
9983 }
9984
David Blaikiee4d798f2012-01-20 21:50:17 +00009985 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009986}
9987
Richard Smithf57d8cb2011-12-09 22:58:01 +00009988/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009989static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009990 const Expr *E,
9991 llvm::APSInt *Value,
9992 SourceLocation *Loc) {
9993 if (!E->getType()->isIntegralOrEnumerationType()) {
9994 if (Loc) *Loc = E->getExprLoc();
9995 return false;
9996 }
9997
Richard Smith66e05fe2012-01-18 05:21:49 +00009998 APValue Result;
9999 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010000 return false;
10001
Richard Smith98710fc2014-11-13 23:03:19 +000010002 if (!Result.isInt()) {
10003 if (Loc) *Loc = E->getExprLoc();
10004 return false;
10005 }
10006
Richard Smith66e05fe2012-01-18 05:21:49 +000010007 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010008 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010009}
10010
Craig Toppera31a8822013-08-22 07:09:37 +000010011bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10012 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010013 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010014 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010015
Richard Smith9e575da2012-12-28 13:25:52 +000010016 ICEDiag D = CheckICE(this, Ctx);
10017 if (D.Kind != IK_ICE) {
10018 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010019 return false;
10020 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010021 return true;
10022}
10023
Craig Toppera31a8822013-08-22 07:09:37 +000010024bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010025 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010026 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010027 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10028
10029 if (!isIntegerConstantExpr(Ctx, Loc))
10030 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010031 // The only possible side-effects here are due to UB discovered in the
10032 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10033 // required to treat the expression as an ICE, so we produce the folded
10034 // value.
10035 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010036 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010037 return true;
10038}
Richard Smith66e05fe2012-01-18 05:21:49 +000010039
Craig Toppera31a8822013-08-22 07:09:37 +000010040bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010041 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010042}
10043
Craig Toppera31a8822013-08-22 07:09:37 +000010044bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010045 SourceLocation *Loc) const {
10046 // We support this checking in C++98 mode in order to diagnose compatibility
10047 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010048 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010049
Richard Smith98a0a492012-02-14 21:38:30 +000010050 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010051 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010052 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010053 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010054 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010055
10056 APValue Scratch;
10057 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10058
10059 if (!Diags.empty()) {
10060 IsConstExpr = false;
10061 if (Loc) *Loc = Diags[0].first;
10062 } else if (!IsConstExpr) {
10063 // FIXME: This shouldn't happen.
10064 if (Loc) *Loc = getExprLoc();
10065 }
10066
10067 return IsConstExpr;
10068}
Richard Smith253c2a32012-01-27 01:14:48 +000010069
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010070bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10071 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010072 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010073 Expr::EvalStatus Status;
10074 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10075
10076 ArgVector ArgValues(Args.size());
10077 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10078 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010079 if ((*I)->isValueDependent() ||
10080 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010081 // If evaluation fails, throw away the argument entirely.
10082 ArgValues[I - Args.begin()] = APValue();
10083 if (Info.EvalStatus.HasSideEffects)
10084 return false;
10085 }
10086
10087 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010088 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010089 ArgValues.data());
10090 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10091}
10092
Richard Smith253c2a32012-01-27 01:14:48 +000010093bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010094 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010095 PartialDiagnosticAt> &Diags) {
10096 // FIXME: It would be useful to check constexpr function templates, but at the
10097 // moment the constant expression evaluator cannot cope with the non-rigorous
10098 // ASTs which we build for dependent expressions.
10099 if (FD->isDependentContext())
10100 return true;
10101
10102 Expr::EvalStatus Status;
10103 Status.Diag = &Diags;
10104
Richard Smith6d4c6582013-11-05 22:18:15 +000010105 EvalInfo Info(FD->getASTContext(), Status,
10106 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010107
10108 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010109 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010110
Richard Smith7525ff62013-05-09 07:14:00 +000010111 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010112 // is a temporary being used as the 'this' pointer.
10113 LValue This;
10114 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010115 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010116
Richard Smith253c2a32012-01-27 01:14:48 +000010117 ArrayRef<const Expr*> Args;
10118
Richard Smith2e312c82012-03-03 22:46:17 +000010119 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010120 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10121 // Evaluate the call as a constant initializer, to allow the construction
10122 // of objects of non-literal types.
10123 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010124 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10125 } else {
10126 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010127 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010128 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010129 }
Richard Smith253c2a32012-01-27 01:14:48 +000010130
10131 return Diags.empty();
10132}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010133
10134bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10135 const FunctionDecl *FD,
10136 SmallVectorImpl<
10137 PartialDiagnosticAt> &Diags) {
10138 Expr::EvalStatus Status;
10139 Status.Diag = &Diags;
10140
10141 EvalInfo Info(FD->getASTContext(), Status,
10142 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10143
10144 // Fabricate a call stack frame to give the arguments a plausible cover story.
10145 ArrayRef<const Expr*> Args;
10146 ArgVector ArgValues(0);
10147 bool Success = EvaluateArgs(Args, ArgValues, Info);
10148 (void)Success;
10149 assert(Success &&
10150 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010151 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010152
10153 APValue ResultScratch;
10154 Evaluate(ResultScratch, Info, E);
10155 return Diags.empty();
10156}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010157
10158bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10159 unsigned Type) const {
10160 if (!getType()->isPointerType())
10161 return false;
10162
10163 Expr::EvalStatus Status;
10164 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10165 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10166}