blob: d80f466d99f5ea779eae96b21ee480a82ae49124 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
160 bool Invalid : 1;
161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
163 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
166 bool MostDerivedIsArrayElement : 1;
167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smithb228a862012-02-15 02:18:13 +0000319 /// Index - The call index of this call.
320 unsigned Index;
321
Richard Smithd62306a2011-11-10 06:34:14 +0000322 /// This - The binding for the this pointer in this call, if any.
323 const LValue *This;
324
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000325 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000326 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000327 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000328
Eli Friedman4830ec82012-06-25 21:21:08 +0000329 // Note that we intentionally use std::map here so that references to
330 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000331 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000436 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith357362d2011-12-13 06:39:58 +0000472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
475
Richard Smith0c6124b2015-12-03 01:36:22 +0000476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
477 /// fold (not just why it's not strictly a constant expression)?
478 bool HasFoldFailureDiagnostic;
479
Richard Smith6d4c6582013-11-05 22:18:15 +0000480 enum EvaluationMode {
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression.
483 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000484
Richard Smith6d4c6582013-11-05 22:18:15 +0000485 /// Evaluate as a potential constant expression. Keep going if we hit a
486 /// construct that we can't evaluate yet (because we don't yet know the
487 /// value of something) but stop if we hit something that could never be
488 /// a constant expression.
489 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000490
Richard Smith6d4c6582013-11-05 22:18:15 +0000491 /// Fold the expression to a constant. Stop if we hit a side-effect that
492 /// we can't model.
493 EM_ConstantFold,
494
495 /// Evaluate the expression looking for integer overflow and similar
496 /// issues. Don't worry about side-effects, and try to visit all
497 /// subexpressions.
498 EM_EvaluateForOverflow,
499
500 /// Evaluate in any way we know how. Don't worry about side-effects that
501 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000502 EM_IgnoreSideEffects,
503
504 /// Evaluate as a constant expression. Stop if we find that the expression
505 /// is not a constant expression. Some expressions can be retried in the
506 /// optimizer if we don't constant fold them here, but in an unevaluated
507 /// context we try to fold them immediately since the optimizer never
508 /// gets a chance to look at it.
509 EM_ConstantExpressionUnevaluated,
510
511 /// Evaluate as a potential constant expression. Keep going if we hit a
512 /// construct that we can't evaluate yet (because we don't yet know the
513 /// value of something) but stop if we hit something that could never be
514 /// a constant expression. Some expressions can be retried in the
515 /// optimizer if we don't constant fold them here, but in an unevaluated
516 /// context we try to fold them immediately since the optimizer never
517 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000518 EM_PotentialConstantExpressionUnevaluated,
519
520 /// Evaluate as a constant expression. Continue evaluating if we find a
521 /// MemberExpr with a base that can't be evaluated.
522 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000523 } EvalMode;
524
525 /// Are we checking whether the expression is a potential constant
526 /// expression?
527 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000528 return EvalMode == EM_PotentialConstantExpression ||
529 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000530 }
531
532 /// Are we checking an expression for overflow?
533 // FIXME: We should check for any kind of undefined or suspicious behavior
534 // in such constructs, not just overflow.
535 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
536
537 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000538 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000539 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000540 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000541 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
542 EvaluatingDecl((const ValueDecl *)nullptr),
543 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith0c6124b2015-12-03 01:36:22 +0000544 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000545
Richard Smith7525ff62013-05-09 07:14:00 +0000546 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
547 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000548 EvaluatingDeclValue = &Value;
549 }
550
David Blaikiebbafb8a2012-03-11 07:00:24 +0000551 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000552
Richard Smith357362d2011-12-13 06:39:58 +0000553 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000554 // Don't perform any constexpr calls (other than the call we're checking)
555 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000556 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000557 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000558 if (NextCallIndex == 0) {
559 // NextCallIndex has wrapped around.
560 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
561 return false;
562 }
Richard Smith357362d2011-12-13 06:39:58 +0000563 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
564 return true;
565 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
566 << getLangOpts().ConstexprCallDepth;
567 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000568 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000569
Richard Smithb228a862012-02-15 02:18:13 +0000570 CallStackFrame *getCallFrame(unsigned CallIndex) {
571 assert(CallIndex && "no call index in getCallFrame");
572 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
573 // be null in this loop.
574 CallStackFrame *Frame = CurrentCall;
575 while (Frame->Index > CallIndex)
576 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000577 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000578 }
579
Richard Smitha3d3bd22013-05-08 02:12:03 +0000580 bool nextStep(const Stmt *S) {
581 if (!StepsLeft) {
582 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
583 return false;
584 }
585 --StepsLeft;
586 return true;
587 }
588
Richard Smith357362d2011-12-13 06:39:58 +0000589 private:
590 /// Add a diagnostic to the diagnostics list.
591 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
592 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
593 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
594 return EvalStatus.Diag->back().second;
595 }
596
Richard Smithf6f003a2011-12-16 19:06:07 +0000597 /// Add notes containing a call stack to the current point of evaluation.
598 void addCallStack(unsigned Limit);
599
Richard Smith357362d2011-12-13 06:39:58 +0000600 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000601 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000602 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
603 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000604 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000605 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000606 // If we have a prior diagnostic, it will be noting that the expression
607 // isn't a constant expression. This diagnostic is more important,
608 // unless we require this evaluation to produce a constant expression.
609 //
610 // FIXME: We might want to show both diagnostics to the user in
611 // EM_ConstantFold mode.
612 if (!EvalStatus.Diag->empty()) {
613 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000614 case EM_ConstantFold:
615 case EM_IgnoreSideEffects:
616 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000617 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000618 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000619 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000620 case EM_ConstantExpression:
621 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000622 case EM_ConstantExpressionUnevaluated:
623 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000624 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000625 HasActiveDiagnostic = false;
626 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 }
628 }
629
Richard Smithf6f003a2011-12-16 19:06:07 +0000630 unsigned CallStackNotes = CallStackDepth - 1;
631 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
632 if (Limit)
633 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000634 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000635 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000636
Richard Smith357362d2011-12-13 06:39:58 +0000637 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000638 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000639 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000640 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
641 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000643 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000644 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000647 return OptionalDiagnostic();
648 }
649
Richard Smithce1ec5e2012-03-15 04:53:45 +0000650 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
651 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000652 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000653 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000654 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000655 HasActiveDiagnostic = false;
656 return OptionalDiagnostic();
657 }
658
Richard Smith92b1ce02011-12-12 09:28:41 +0000659 /// Diagnose that the evaluation does not produce a C++11 core constant
660 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000661 ///
662 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
663 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000664 template<typename LocArg>
665 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000666 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000667 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000668 // Don't override a previous diagnostic. Don't bother collecting
669 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000670 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000671 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000672 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000673 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000674 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000675 }
676
677 /// Add a note to a prior diagnostic.
678 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
679 if (!HasActiveDiagnostic)
680 return OptionalDiagnostic();
681 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000682 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000683
684 /// Add a stack of notes to a prior diagnostic.
685 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
686 if (HasActiveDiagnostic) {
687 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
688 Diags.begin(), Diags.end());
689 }
690 }
Richard Smith253c2a32012-01-27 01:14:48 +0000691
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 /// Should we continue evaluation after encountering a side-effect that we
693 /// couldn't model?
694 bool keepEvaluatingAfterSideEffect() {
695 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000696 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_EvaluateForOverflow:
699 case EM_IgnoreSideEffects:
700 return true;
701
Richard Smith6d4c6582013-11-05 22:18:15 +0000702 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000703 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000705 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000706 return false;
707 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000708 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 }
710
711 /// Note that we have had a side-effect, and determine whether we should
712 /// keep evaluating.
713 bool noteSideEffect() {
714 EvalStatus.HasSideEffects = true;
715 return keepEvaluatingAfterSideEffect();
716 }
717
Richard Smith253c2a32012-01-27 01:14:48 +0000718 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000719 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000720 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000721 if (!StepsLeft)
722 return false;
723
724 switch (EvalMode) {
725 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000726 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 case EM_EvaluateForOverflow:
728 return true;
729
730 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000731 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000732 case EM_ConstantFold:
733 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000734 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 return false;
736 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000737 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000738 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000739
740 bool allowInvalidBaseExpr() const {
741 return EvalMode == EM_DesignatorFold;
742 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000743 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000744
745 /// Object used to treat all foldable expressions as constant expressions.
746 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000748 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000749 bool HadNoPriorDiags;
750 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000751
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 explicit FoldConstant(EvalInfo &Info, bool Enabled)
753 : Info(Info),
754 Enabled(Enabled),
755 HadNoPriorDiags(Info.EvalStatus.Diag &&
756 Info.EvalStatus.Diag->empty() &&
757 !Info.EvalStatus.HasSideEffects),
758 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000759 if (Enabled &&
760 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
761 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000763 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000764 void keepDiagnostics() { Enabled = false; }
765 ~FoldConstant() {
766 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000767 !Info.EvalStatus.HasSideEffects)
768 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000769 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000770 }
771 };
Richard Smith17100ba2012-02-16 02:46:34 +0000772
George Burgess IV3a03fab2015-09-04 21:28:13 +0000773 /// RAII object used to treat the current evaluation as the correct pointer
774 /// offset fold for the current EvalMode
775 struct FoldOffsetRAII {
776 EvalInfo &Info;
777 EvalInfo::EvaluationMode OldMode;
778 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
779 : Info(Info), OldMode(Info.EvalMode) {
780 if (!Info.checkingPotentialConstantExpression())
781 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
782 : EvalInfo::EM_ConstantFold;
783 }
784
785 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
786 };
787
Richard Smith17100ba2012-02-16 02:46:34 +0000788 /// RAII object used to suppress diagnostics and side-effects from a
789 /// speculative evaluation.
790 class SpeculativeEvaluationRAII {
791 EvalInfo &Info;
792 Expr::EvalStatus Old;
793
794 public:
795 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000796 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000797 : Info(Info), Old(Info.EvalStatus) {
798 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000799 // If we're speculatively evaluating, we may have skipped over some
800 // evaluations and missed out a side effect.
801 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000802 }
803 ~SpeculativeEvaluationRAII() {
804 Info.EvalStatus = Old;
805 }
806 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000807
808 /// RAII object wrapping a full-expression or block scope, and handling
809 /// the ending of the lifetime of temporaries created within it.
810 template<bool IsFullExpression>
811 class ScopeRAII {
812 EvalInfo &Info;
813 unsigned OldStackSize;
814 public:
815 ScopeRAII(EvalInfo &Info)
816 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
817 ~ScopeRAII() {
818 // Body moved to a static method to encourage the compiler to inline away
819 // instances of this class.
820 cleanup(Info, OldStackSize);
821 }
822 private:
823 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
824 unsigned NewEnd = OldStackSize;
825 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
826 I != N; ++I) {
827 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
828 // Full-expression cleanup of a lifetime-extended temporary: nothing
829 // to do, just move this cleanup to the right place in the stack.
830 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
831 ++NewEnd;
832 } else {
833 // End the lifetime of the object.
834 Info.CleanupStack[I].endLifetime();
835 }
836 }
837 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
838 Info.CleanupStack.end());
839 }
840 };
841 typedef ScopeRAII<false> BlockScopeRAII;
842 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000843}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000844
Richard Smitha8105bc2012-01-06 16:39:00 +0000845bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
846 CheckSubobjectKind CSK) {
847 if (Invalid)
848 return false;
849 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000850 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000851 << CSK;
852 setInvalid();
853 return false;
854 }
855 return true;
856}
857
858void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
859 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000860 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000861 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000862 << static_cast<int>(N) << /*array*/ 0
863 << static_cast<unsigned>(MostDerivedArraySize);
864 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000865 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000866 << static_cast<int>(N) << /*non-array*/ 1;
867 setInvalid();
868}
869
Richard Smithf6f003a2011-12-16 19:06:07 +0000870CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
871 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000872 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000873 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000874 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000875 Info.CurrentCall = this;
876 ++Info.CallStackDepth;
877}
878
879CallStackFrame::~CallStackFrame() {
880 assert(Info.CurrentCall == this && "calls retired out of order");
881 --Info.CallStackDepth;
882 Info.CurrentCall = Caller;
883}
884
Richard Smith08d6a2c2013-07-24 07:11:57 +0000885APValue &CallStackFrame::createTemporary(const void *Key,
886 bool IsLifetimeExtended) {
887 APValue &Result = Temporaries[Key];
888 assert(Result.isUninit() && "temporary created multiple times");
889 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
890 return Result;
891}
892
Richard Smith84401042013-06-03 05:03:02 +0000893static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000894
895void EvalInfo::addCallStack(unsigned Limit) {
896 // Determine which calls to skip, if any.
897 unsigned ActiveCalls = CallStackDepth - 1;
898 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
899 if (Limit && Limit < ActiveCalls) {
900 SkipStart = Limit / 2 + Limit % 2;
901 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000902 }
903
Richard Smithf6f003a2011-12-16 19:06:07 +0000904 // Walk the call stack and add the diagnostics.
905 unsigned CallIdx = 0;
906 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
907 Frame = Frame->Caller, ++CallIdx) {
908 // Skip this call?
909 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
910 if (CallIdx == SkipStart) {
911 // Note that we're skipping calls.
912 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
913 << unsigned(ActiveCalls - Limit);
914 }
915 continue;
916 }
917
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000918 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000919 llvm::raw_svector_ostream Out(Buffer);
920 describeCall(Frame, Out);
921 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
922 }
923}
924
925namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000926 struct ComplexValue {
927 private:
928 bool IsInt;
929
930 public:
931 APSInt IntReal, IntImag;
932 APFloat FloatReal, FloatImag;
933
934 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
935
936 void makeComplexFloat() { IsInt = false; }
937 bool isComplexFloat() const { return !IsInt; }
938 APFloat &getComplexFloatReal() { return FloatReal; }
939 APFloat &getComplexFloatImag() { return FloatImag; }
940
941 void makeComplexInt() { IsInt = true; }
942 bool isComplexInt() const { return IsInt; }
943 APSInt &getComplexIntReal() { return IntReal; }
944 APSInt &getComplexIntImag() { return IntImag; }
945
Richard Smith2e312c82012-03-03 22:46:17 +0000946 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000947 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000948 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000949 else
Richard Smith2e312c82012-03-03 22:46:17 +0000950 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000951 }
Richard Smith2e312c82012-03-03 22:46:17 +0000952 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000953 assert(v.isComplexFloat() || v.isComplexInt());
954 if (v.isComplexFloat()) {
955 makeComplexFloat();
956 FloatReal = v.getComplexFloatReal();
957 FloatImag = v.getComplexFloatImag();
958 } else {
959 makeComplexInt();
960 IntReal = v.getComplexIntReal();
961 IntImag = v.getComplexIntImag();
962 }
963 }
John McCall93d91dc2010-05-07 17:22:02 +0000964 };
John McCall45d55e42010-05-07 21:00:08 +0000965
966 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000967 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000968 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000969 bool InvalidBase : 1;
970 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000971 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000972
Richard Smithce40ad62011-11-12 22:28:03 +0000973 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000974 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000975 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000976 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000977 SubobjectDesignator &getLValueDesignator() { return Designator; }
978 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000979
Richard Smith2e312c82012-03-03 22:46:17 +0000980 void moveInto(APValue &V) const {
981 if (Designator.Invalid)
982 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
983 else
984 V = APValue(Base, Offset, Designator.Entries,
985 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000986 }
Richard Smith2e312c82012-03-03 22:46:17 +0000987 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000988 assert(V.isLValue());
989 Base = V.getLValueBase();
990 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000991 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +0000992 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000993 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000994 }
995
George Burgess IV3a03fab2015-09-04 21:28:13 +0000996 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +0000997 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000998 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000999 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001000 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001001 Designator = SubobjectDesignator(getType(B));
1002 }
1003
George Burgess IV3a03fab2015-09-04 21:28:13 +00001004 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1005 set(B, I, true);
1006 }
1007
Richard Smitha8105bc2012-01-06 16:39:00 +00001008 // Check that this LValue is not based on a null pointer. If it is, produce
1009 // a diagnostic and mark the designator as invalid.
1010 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1011 CheckSubobjectKind CSK) {
1012 if (Designator.Invalid)
1013 return false;
1014 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001015 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001016 << CSK;
1017 Designator.setInvalid();
1018 return false;
1019 }
1020 return true;
1021 }
1022
1023 // Check this LValue refers to an object. If not, set the designator to be
1024 // invalid and emit a diagnostic.
1025 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001026 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001027 Designator.checkSubobject(Info, E, CSK);
1028 }
1029
1030 void addDecl(EvalInfo &Info, const Expr *E,
1031 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001032 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1033 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001034 }
1035 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001036 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1037 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001038 }
Richard Smith66c96992012-02-18 22:04:06 +00001039 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001040 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1041 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001042 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001043 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001044 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001045 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001046 }
John McCall45d55e42010-05-07 21:00:08 +00001047 };
Richard Smith027bf112011-11-17 22:56:20 +00001048
1049 struct MemberPtr {
1050 MemberPtr() {}
1051 explicit MemberPtr(const ValueDecl *Decl) :
1052 DeclAndIsDerivedMember(Decl, false), Path() {}
1053
1054 /// The member or (direct or indirect) field referred to by this member
1055 /// pointer, or 0 if this is a null member pointer.
1056 const ValueDecl *getDecl() const {
1057 return DeclAndIsDerivedMember.getPointer();
1058 }
1059 /// Is this actually a member of some type derived from the relevant class?
1060 bool isDerivedMember() const {
1061 return DeclAndIsDerivedMember.getInt();
1062 }
1063 /// Get the class which the declaration actually lives in.
1064 const CXXRecordDecl *getContainingRecord() const {
1065 return cast<CXXRecordDecl>(
1066 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1067 }
1068
Richard Smith2e312c82012-03-03 22:46:17 +00001069 void moveInto(APValue &V) const {
1070 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001071 }
Richard Smith2e312c82012-03-03 22:46:17 +00001072 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001073 assert(V.isMemberPointer());
1074 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1075 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1076 Path.clear();
1077 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1078 Path.insert(Path.end(), P.begin(), P.end());
1079 }
1080
1081 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1082 /// whether the member is a member of some class derived from the class type
1083 /// of the member pointer.
1084 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1085 /// Path - The path of base/derived classes from the member declaration's
1086 /// class (exclusive) to the class type of the member pointer (inclusive).
1087 SmallVector<const CXXRecordDecl*, 4> Path;
1088
1089 /// Perform a cast towards the class of the Decl (either up or down the
1090 /// hierarchy).
1091 bool castBack(const CXXRecordDecl *Class) {
1092 assert(!Path.empty());
1093 const CXXRecordDecl *Expected;
1094 if (Path.size() >= 2)
1095 Expected = Path[Path.size() - 2];
1096 else
1097 Expected = getContainingRecord();
1098 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1099 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1100 // if B does not contain the original member and is not a base or
1101 // derived class of the class containing the original member, the result
1102 // of the cast is undefined.
1103 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1104 // (D::*). We consider that to be a language defect.
1105 return false;
1106 }
1107 Path.pop_back();
1108 return true;
1109 }
1110 /// Perform a base-to-derived member pointer cast.
1111 bool castToDerived(const CXXRecordDecl *Derived) {
1112 if (!getDecl())
1113 return true;
1114 if (!isDerivedMember()) {
1115 Path.push_back(Derived);
1116 return true;
1117 }
1118 if (!castBack(Derived))
1119 return false;
1120 if (Path.empty())
1121 DeclAndIsDerivedMember.setInt(false);
1122 return true;
1123 }
1124 /// Perform a derived-to-base member pointer cast.
1125 bool castToBase(const CXXRecordDecl *Base) {
1126 if (!getDecl())
1127 return true;
1128 if (Path.empty())
1129 DeclAndIsDerivedMember.setInt(true);
1130 if (isDerivedMember()) {
1131 Path.push_back(Base);
1132 return true;
1133 }
1134 return castBack(Base);
1135 }
1136 };
Richard Smith357362d2011-12-13 06:39:58 +00001137
Richard Smith7bb00672012-02-01 01:42:44 +00001138 /// Compare two member pointers, which are assumed to be of the same type.
1139 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1140 if (!LHS.getDecl() || !RHS.getDecl())
1141 return !LHS.getDecl() && !RHS.getDecl();
1142 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1143 return false;
1144 return LHS.Path == RHS.Path;
1145 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001146}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001147
Richard Smith2e312c82012-03-03 22:46:17 +00001148static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001149static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1150 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001151 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001152static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1153static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001154static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1155 EvalInfo &Info);
1156static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001157static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001158static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001159 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001160static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001161static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001162static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001163static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001164
1165//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001166// Misc utilities
1167//===----------------------------------------------------------------------===//
1168
Richard Smith84401042013-06-03 05:03:02 +00001169/// Produce a string describing the given constexpr call.
1170static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1171 unsigned ArgIndex = 0;
1172 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1173 !isa<CXXConstructorDecl>(Frame->Callee) &&
1174 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1175
1176 if (!IsMemberCall)
1177 Out << *Frame->Callee << '(';
1178
1179 if (Frame->This && IsMemberCall) {
1180 APValue Val;
1181 Frame->This->moveInto(Val);
1182 Val.printPretty(Out, Frame->Info.Ctx,
1183 Frame->This->Designator.MostDerivedType);
1184 // FIXME: Add parens around Val if needed.
1185 Out << "->" << *Frame->Callee << '(';
1186 IsMemberCall = false;
1187 }
1188
1189 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1190 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1191 if (ArgIndex > (unsigned)IsMemberCall)
1192 Out << ", ";
1193
1194 const ParmVarDecl *Param = *I;
1195 const APValue &Arg = Frame->Arguments[ArgIndex];
1196 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1197
1198 if (ArgIndex == 0 && IsMemberCall)
1199 Out << "->" << *Frame->Callee << '(';
1200 }
1201
1202 Out << ')';
1203}
1204
Richard Smithd9f663b2013-04-22 15:31:51 +00001205/// Evaluate an expression to see if it had side-effects, and discard its
1206/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001207/// \return \c true if the caller should keep evaluating.
1208static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001209 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001210 if (!Evaluate(Scratch, Info, E))
1211 // We don't need the value, but we might have skipped a side effect here.
1212 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001213 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001214}
1215
Richard Smith861b5b52013-05-07 23:34:45 +00001216/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1217/// return its existing value.
1218static int64_t getExtValue(const APSInt &Value) {
1219 return Value.isSigned() ? Value.getSExtValue()
1220 : static_cast<int64_t>(Value.getZExtValue());
1221}
1222
Richard Smithd62306a2011-11-10 06:34:14 +00001223/// Should this call expression be treated as a string literal?
1224static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001225 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001226 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1227 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1228}
1229
Richard Smithce40ad62011-11-12 22:28:03 +00001230static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001231 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1232 // constant expression of pointer type that evaluates to...
1233
1234 // ... a null pointer value, or a prvalue core constant expression of type
1235 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001236 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001237
Richard Smithce40ad62011-11-12 22:28:03 +00001238 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1239 // ... the address of an object with static storage duration,
1240 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1241 return VD->hasGlobalStorage();
1242 // ... the address of a function,
1243 return isa<FunctionDecl>(D);
1244 }
1245
1246 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001247 switch (E->getStmtClass()) {
1248 default:
1249 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001250 case Expr::CompoundLiteralExprClass: {
1251 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1252 return CLE->isFileScope() && CLE->isLValue();
1253 }
Richard Smithe6c01442013-06-05 00:46:14 +00001254 case Expr::MaterializeTemporaryExprClass:
1255 // A materialized temporary might have been lifetime-extended to static
1256 // storage duration.
1257 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001258 // A string literal has static storage duration.
1259 case Expr::StringLiteralClass:
1260 case Expr::PredefinedExprClass:
1261 case Expr::ObjCStringLiteralClass:
1262 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001263 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001264 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001265 return true;
1266 case Expr::CallExprClass:
1267 return IsStringLiteralCall(cast<CallExpr>(E));
1268 // For GCC compatibility, &&label has static storage duration.
1269 case Expr::AddrLabelExprClass:
1270 return true;
1271 // A Block literal expression may be used as the initialization value for
1272 // Block variables at global or local static scope.
1273 case Expr::BlockExprClass:
1274 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001275 case Expr::ImplicitValueInitExprClass:
1276 // FIXME:
1277 // We can never form an lvalue with an implicit value initialization as its
1278 // base through expression evaluation, so these only appear in one case: the
1279 // implicit variable declaration we invent when checking whether a constexpr
1280 // constructor can produce a constant expression. We must assume that such
1281 // an expression might be a global lvalue.
1282 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001283 }
John McCall95007602010-05-10 23:27:23 +00001284}
1285
Richard Smithb228a862012-02-15 02:18:13 +00001286static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1287 assert(Base && "no location for a null lvalue");
1288 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1289 if (VD)
1290 Info.Note(VD->getLocation(), diag::note_declared_at);
1291 else
Ted Kremenek28831752012-08-23 20:46:57 +00001292 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001293 diag::note_constexpr_temporary_here);
1294}
1295
Richard Smith80815602011-11-07 05:07:52 +00001296/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001297/// value for an address or reference constant expression. Return true if we
1298/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001299static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1300 QualType Type, const LValue &LVal) {
1301 bool IsReferenceType = Type->isReferenceType();
1302
Richard Smith357362d2011-12-13 06:39:58 +00001303 APValue::LValueBase Base = LVal.getLValueBase();
1304 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1305
Richard Smith0dea49e2012-02-18 04:58:18 +00001306 // Check that the object is a global. Note that the fake 'this' object we
1307 // manufacture when checking potential constant expressions is conservatively
1308 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001309 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001310 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001311 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001312 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1313 << IsReferenceType << !Designator.Entries.empty()
1314 << !!VD << VD;
1315 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001316 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001317 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001318 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001319 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001320 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001321 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001322 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001323 LVal.getLValueCallIndex() == 0) &&
1324 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001325
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001326 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1327 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001328 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001329 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001330 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001331
Hans Wennborg82dd8772014-06-25 22:19:48 +00001332 // A dllimport variable never acts like a constant.
1333 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001334 return false;
1335 }
1336 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1337 // __declspec(dllimport) must be handled very carefully:
1338 // We must never initialize an expression with the thunk in C++.
1339 // Doing otherwise would allow the same id-expression to yield
1340 // different addresses for the same function in different translation
1341 // units. However, this means that we must dynamically initialize the
1342 // expression with the contents of the import address table at runtime.
1343 //
1344 // The C language has no notion of ODR; furthermore, it has no notion of
1345 // dynamic initialization. This means that we are permitted to
1346 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001347 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001348 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001349 }
1350 }
1351
Richard Smitha8105bc2012-01-06 16:39:00 +00001352 // Allow address constant expressions to be past-the-end pointers. This is
1353 // an extension: the standard requires them to point to an object.
1354 if (!IsReferenceType)
1355 return true;
1356
1357 // A reference constant expression must refer to an object.
1358 if (!Base) {
1359 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001360 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001361 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001362 }
1363
Richard Smith357362d2011-12-13 06:39:58 +00001364 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001365 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001366 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001367 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001368 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001369 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001370 }
1371
Richard Smith80815602011-11-07 05:07:52 +00001372 return true;
1373}
1374
Richard Smithfddd3842011-12-30 21:15:51 +00001375/// Check that this core constant expression is of literal type, and if not,
1376/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001377static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001378 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001379 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001380 return true;
1381
Richard Smith7525ff62013-05-09 07:14:00 +00001382 // C++1y: A constant initializer for an object o [...] may also invoke
1383 // constexpr constructors for o and its subobjects even if those objects
1384 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001385 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001386 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001387 return true;
1388
Richard Smithfddd3842011-12-30 21:15:51 +00001389 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001390 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001391 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001392 << E->getType();
1393 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001394 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001395 return false;
1396}
1397
Richard Smith0b0a0b62011-10-29 20:57:55 +00001398/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001399/// constant expression. If not, report an appropriate diagnostic. Does not
1400/// check that the expression is of literal type.
1401static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1402 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001403 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001404 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1405 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001406 return false;
1407 }
1408
Richard Smith77be48a2014-07-31 06:31:19 +00001409 // We allow _Atomic(T) to be initialized from anything that T can be
1410 // initialized from.
1411 if (const AtomicType *AT = Type->getAs<AtomicType>())
1412 Type = AT->getValueType();
1413
Richard Smithb228a862012-02-15 02:18:13 +00001414 // Core issue 1454: For a literal constant expression of array or class type,
1415 // each subobject of its value shall have been initialized by a constant
1416 // expression.
1417 if (Value.isArray()) {
1418 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1419 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1420 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1421 Value.getArrayInitializedElt(I)))
1422 return false;
1423 }
1424 if (!Value.hasArrayFiller())
1425 return true;
1426 return CheckConstantExpression(Info, DiagLoc, EltTy,
1427 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001428 }
Richard Smithb228a862012-02-15 02:18:13 +00001429 if (Value.isUnion() && Value.getUnionField()) {
1430 return CheckConstantExpression(Info, DiagLoc,
1431 Value.getUnionField()->getType(),
1432 Value.getUnionValue());
1433 }
1434 if (Value.isStruct()) {
1435 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1436 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1437 unsigned BaseIndex = 0;
1438 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1439 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1440 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1441 Value.getStructBase(BaseIndex)))
1442 return false;
1443 }
1444 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001445 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001446 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1447 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001448 return false;
1449 }
1450 }
1451
1452 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001453 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001454 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001455 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1456 }
1457
1458 // Everything else is fine.
1459 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001460}
1461
Benjamin Kramer8407df72015-03-09 16:47:52 +00001462static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001463 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001464}
1465
1466static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001467 if (Value.CallIndex)
1468 return false;
1469 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1470 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001471}
1472
Richard Smithcecf1842011-11-01 21:06:14 +00001473static bool IsWeakLValue(const LValue &Value) {
1474 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001475 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001476}
1477
David Majnemerb5116032014-12-09 23:32:34 +00001478static bool isZeroSized(const LValue &Value) {
1479 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001480 if (Decl && isa<VarDecl>(Decl)) {
1481 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001482 if (Ty->isArrayType())
1483 return Ty->isIncompleteType() ||
1484 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001485 }
1486 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001487}
1488
Richard Smith2e312c82012-03-03 22:46:17 +00001489static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001490 // A null base expression indicates a null pointer. These are always
1491 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001492 if (!Value.getLValueBase()) {
1493 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001494 return true;
1495 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001496
Richard Smith027bf112011-11-17 22:56:20 +00001497 // We have a non-null base. These are generally known to be true, but if it's
1498 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001499 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001500 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001501 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001502}
1503
Richard Smith2e312c82012-03-03 22:46:17 +00001504static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001505 switch (Val.getKind()) {
1506 case APValue::Uninitialized:
1507 return false;
1508 case APValue::Int:
1509 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001510 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001511 case APValue::Float:
1512 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001513 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001514 case APValue::ComplexInt:
1515 Result = Val.getComplexIntReal().getBoolValue() ||
1516 Val.getComplexIntImag().getBoolValue();
1517 return true;
1518 case APValue::ComplexFloat:
1519 Result = !Val.getComplexFloatReal().isZero() ||
1520 !Val.getComplexFloatImag().isZero();
1521 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001522 case APValue::LValue:
1523 return EvalPointerValueAsBool(Val, Result);
1524 case APValue::MemberPointer:
1525 Result = Val.getMemberPointerDecl();
1526 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001527 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001528 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001529 case APValue::Struct:
1530 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001531 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001532 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001533 }
1534
Richard Smith11562c52011-10-28 17:51:58 +00001535 llvm_unreachable("unknown APValue kind");
1536}
1537
1538static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1539 EvalInfo &Info) {
1540 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001541 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001542 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001543 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001544 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001545}
1546
Richard Smith357362d2011-12-13 06:39:58 +00001547template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001548static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001549 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001550 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001551 << SrcValue << DestType;
Richard Smith0c6124b2015-12-03 01:36:22 +00001552 return Info.noteSideEffect();
Richard Smith357362d2011-12-13 06:39:58 +00001553}
1554
1555static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1556 QualType SrcType, const APFloat &Value,
1557 QualType DestType, APSInt &Result) {
1558 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001559 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001560 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001561
Richard Smith357362d2011-12-13 06:39:58 +00001562 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001563 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001564 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1565 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001566 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001567 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001568}
1569
Richard Smith357362d2011-12-13 06:39:58 +00001570static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1571 QualType SrcType, QualType DestType,
1572 APFloat &Result) {
1573 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001574 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001575 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1576 APFloat::rmNearestTiesToEven, &ignored)
1577 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001578 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001579 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001580}
1581
Richard Smith911e1422012-01-30 22:27:01 +00001582static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1583 QualType DestType, QualType SrcType,
1584 APSInt &Value) {
1585 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001586 APSInt Result = Value;
1587 // Figure out if this is a truncate, extend or noop cast.
1588 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001589 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001590 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001591 return Result;
1592}
1593
Richard Smith357362d2011-12-13 06:39:58 +00001594static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1595 QualType SrcType, const APSInt &Value,
1596 QualType DestType, APFloat &Result) {
1597 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1598 if (Result.convertFromAPInt(Value, Value.isSigned(),
1599 APFloat::rmNearestTiesToEven)
1600 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001601 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001602 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001603}
1604
Richard Smith49ca8aa2013-08-06 07:09:20 +00001605static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1606 APValue &Value, const FieldDecl *FD) {
1607 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1608
1609 if (!Value.isInt()) {
1610 // Trying to store a pointer-cast-to-integer into a bitfield.
1611 // FIXME: In this case, we should provide the diagnostic for casting
1612 // a pointer to an integer.
1613 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1614 Info.Diag(E);
1615 return false;
1616 }
1617
1618 APSInt &Int = Value.getInt();
1619 unsigned OldBitWidth = Int.getBitWidth();
1620 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1621 if (NewBitWidth < OldBitWidth)
1622 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1623 return true;
1624}
1625
Eli Friedman803acb32011-12-22 03:51:45 +00001626static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1627 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001628 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001629 if (!Evaluate(SVal, Info, E))
1630 return false;
1631 if (SVal.isInt()) {
1632 Res = SVal.getInt();
1633 return true;
1634 }
1635 if (SVal.isFloat()) {
1636 Res = SVal.getFloat().bitcastToAPInt();
1637 return true;
1638 }
1639 if (SVal.isVector()) {
1640 QualType VecTy = E->getType();
1641 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1642 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1643 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1644 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1645 Res = llvm::APInt::getNullValue(VecSize);
1646 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1647 APValue &Elt = SVal.getVectorElt(i);
1648 llvm::APInt EltAsInt;
1649 if (Elt.isInt()) {
1650 EltAsInt = Elt.getInt();
1651 } else if (Elt.isFloat()) {
1652 EltAsInt = Elt.getFloat().bitcastToAPInt();
1653 } else {
1654 // Don't try to handle vectors of anything other than int or float
1655 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001656 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001657 return false;
1658 }
1659 unsigned BaseEltSize = EltAsInt.getBitWidth();
1660 if (BigEndian)
1661 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1662 else
1663 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1664 }
1665 return true;
1666 }
1667 // Give up if the input isn't an int, float, or vector. For example, we
1668 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001669 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001670 return false;
1671}
1672
Richard Smith43e77732013-05-07 04:50:00 +00001673/// Perform the given integer operation, which is known to need at most BitWidth
1674/// bits, and check for overflow in the original type (if that type was not an
1675/// unsigned type).
1676template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001677static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1678 const APSInt &LHS, const APSInt &RHS,
1679 unsigned BitWidth, Operation Op,
1680 APSInt &Result) {
1681 if (LHS.isUnsigned()) {
1682 Result = Op(LHS, RHS);
1683 return true;
1684 }
Richard Smith43e77732013-05-07 04:50:00 +00001685
1686 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001687 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001688 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001689 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001690 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001691 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001692 << Result.toString(10) << E->getType();
1693 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001694 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001695 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001696 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001697}
1698
1699/// Perform the given binary integer operation.
1700static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1701 BinaryOperatorKind Opcode, APSInt RHS,
1702 APSInt &Result) {
1703 switch (Opcode) {
1704 default:
1705 Info.Diag(E);
1706 return false;
1707 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001708 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1709 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001710 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001711 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1712 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001713 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001714 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1715 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001716 case BO_And: Result = LHS & RHS; return true;
1717 case BO_Xor: Result = LHS ^ RHS; return true;
1718 case BO_Or: Result = LHS | RHS; return true;
1719 case BO_Div:
1720 case BO_Rem:
1721 if (RHS == 0) {
1722 Info.Diag(E, diag::note_expr_divide_by_zero);
1723 return false;
1724 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001725 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1726 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1727 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001728 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1729 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001730 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1731 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001732 return true;
1733 case BO_Shl: {
1734 if (Info.getLangOpts().OpenCL)
1735 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1736 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1737 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1738 RHS.isUnsigned());
1739 else if (RHS.isSigned() && RHS.isNegative()) {
1740 // During constant-folding, a negative shift is an opposite shift. Such
1741 // a shift is not a constant expression.
1742 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1743 RHS = -RHS;
1744 goto shift_right;
1745 }
1746 shift_left:
1747 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1748 // the shifted type.
1749 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1750 if (SA != RHS) {
1751 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1752 << RHS << E->getType() << LHS.getBitWidth();
1753 } else if (LHS.isSigned()) {
1754 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1755 // operand, and must not overflow the corresponding unsigned type.
1756 if (LHS.isNegative())
1757 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1758 else if (LHS.countLeadingZeros() < SA)
1759 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1760 }
1761 Result = LHS << SA;
1762 return true;
1763 }
1764 case BO_Shr: {
1765 if (Info.getLangOpts().OpenCL)
1766 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1767 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1768 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1769 RHS.isUnsigned());
1770 else if (RHS.isSigned() && RHS.isNegative()) {
1771 // During constant-folding, a negative shift is an opposite shift. Such a
1772 // shift is not a constant expression.
1773 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1774 RHS = -RHS;
1775 goto shift_left;
1776 }
1777 shift_right:
1778 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1779 // shifted type.
1780 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1781 if (SA != RHS)
1782 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1783 << RHS << E->getType() << LHS.getBitWidth();
1784 Result = LHS >> SA;
1785 return true;
1786 }
1787
1788 case BO_LT: Result = LHS < RHS; return true;
1789 case BO_GT: Result = LHS > RHS; return true;
1790 case BO_LE: Result = LHS <= RHS; return true;
1791 case BO_GE: Result = LHS >= RHS; return true;
1792 case BO_EQ: Result = LHS == RHS; return true;
1793 case BO_NE: Result = LHS != RHS; return true;
1794 }
1795}
1796
Richard Smith861b5b52013-05-07 23:34:45 +00001797/// Perform the given binary floating-point operation, in-place, on LHS.
1798static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1799 APFloat &LHS, BinaryOperatorKind Opcode,
1800 const APFloat &RHS) {
1801 switch (Opcode) {
1802 default:
1803 Info.Diag(E);
1804 return false;
1805 case BO_Mul:
1806 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1807 break;
1808 case BO_Add:
1809 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1810 break;
1811 case BO_Sub:
1812 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1813 break;
1814 case BO_Div:
1815 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1816 break;
1817 }
1818
Richard Smith0c6124b2015-12-03 01:36:22 +00001819 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001820 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smith0c6124b2015-12-03 01:36:22 +00001821 // Undefined behavior is a side-effect.
1822 return Info.noteSideEffect();
1823 }
Richard Smith861b5b52013-05-07 23:34:45 +00001824 return true;
1825}
1826
Richard Smitha8105bc2012-01-06 16:39:00 +00001827/// Cast an lvalue referring to a base subobject to a derived class, by
1828/// truncating the lvalue's path to the given length.
1829static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1830 const RecordDecl *TruncatedType,
1831 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001832 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001833
1834 // Check we actually point to a derived class object.
1835 if (TruncatedElements == D.Entries.size())
1836 return true;
1837 assert(TruncatedElements >= D.MostDerivedPathLength &&
1838 "not casting to a derived class");
1839 if (!Result.checkSubobject(Info, E, CSK_Derived))
1840 return false;
1841
1842 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001843 const RecordDecl *RD = TruncatedType;
1844 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001845 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001846 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1847 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001848 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001849 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001850 else
Richard Smithd62306a2011-11-10 06:34:14 +00001851 Result.Offset -= Layout.getBaseClassOffset(Base);
1852 RD = Base;
1853 }
Richard Smith027bf112011-11-17 22:56:20 +00001854 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001855 return true;
1856}
1857
John McCalld7bca762012-05-01 00:38:49 +00001858static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001859 const CXXRecordDecl *Derived,
1860 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001861 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001862 if (!RL) {
1863 if (Derived->isInvalidDecl()) return false;
1864 RL = &Info.Ctx.getASTRecordLayout(Derived);
1865 }
1866
Richard Smithd62306a2011-11-10 06:34:14 +00001867 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001868 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001869 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001870}
1871
Richard Smitha8105bc2012-01-06 16:39:00 +00001872static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001873 const CXXRecordDecl *DerivedDecl,
1874 const CXXBaseSpecifier *Base) {
1875 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1876
John McCalld7bca762012-05-01 00:38:49 +00001877 if (!Base->isVirtual())
1878 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001879
Richard Smitha8105bc2012-01-06 16:39:00 +00001880 SubobjectDesignator &D = Obj.Designator;
1881 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001882 return false;
1883
Richard Smitha8105bc2012-01-06 16:39:00 +00001884 // Extract most-derived object and corresponding type.
1885 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1886 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1887 return false;
1888
1889 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001890 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001891 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1892 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001893 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001894 return true;
1895}
1896
Richard Smith84401042013-06-03 05:03:02 +00001897static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1898 QualType Type, LValue &Result) {
1899 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1900 PathE = E->path_end();
1901 PathI != PathE; ++PathI) {
1902 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1903 *PathI))
1904 return false;
1905 Type = (*PathI)->getType();
1906 }
1907 return true;
1908}
1909
Richard Smithd62306a2011-11-10 06:34:14 +00001910/// Update LVal to refer to the given field, which must be a member of the type
1911/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001912static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001913 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001914 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001915 if (!RL) {
1916 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001917 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001918 }
Richard Smithd62306a2011-11-10 06:34:14 +00001919
1920 unsigned I = FD->getFieldIndex();
1921 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001922 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001923 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001924}
1925
Richard Smith1b78b3d2012-01-25 22:15:11 +00001926/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001927static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001928 LValue &LVal,
1929 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001930 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001931 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001932 return false;
1933 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001934}
1935
Richard Smithd62306a2011-11-10 06:34:14 +00001936/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001937static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1938 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001939 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1940 // extension.
1941 if (Type->isVoidType() || Type->isFunctionType()) {
1942 Size = CharUnits::One();
1943 return true;
1944 }
1945
1946 if (!Type->isConstantSizeType()) {
1947 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001948 // FIXME: Better diagnostic.
1949 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001950 return false;
1951 }
1952
1953 Size = Info.Ctx.getTypeSizeInChars(Type);
1954 return true;
1955}
1956
1957/// Update a pointer value to model pointer arithmetic.
1958/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001959/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001960/// \param LVal - The pointer value to be updated.
1961/// \param EltTy - The pointee type represented by LVal.
1962/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001963static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1964 LValue &LVal, QualType EltTy,
1965 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001966 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001967 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001968 return false;
1969
1970 // Compute the new offset in the appropriate width.
1971 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001972 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001973 return true;
1974}
1975
Richard Smith66c96992012-02-18 22:04:06 +00001976/// Update an lvalue to refer to a component of a complex number.
1977/// \param Info - Information about the ongoing evaluation.
1978/// \param LVal - The lvalue to be updated.
1979/// \param EltTy - The complex number's component type.
1980/// \param Imag - False for the real component, true for the imaginary.
1981static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1982 LValue &LVal, QualType EltTy,
1983 bool Imag) {
1984 if (Imag) {
1985 CharUnits SizeOfComponent;
1986 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1987 return false;
1988 LVal.Offset += SizeOfComponent;
1989 }
1990 LVal.addComplex(Info, E, EltTy, Imag);
1991 return true;
1992}
1993
Richard Smith27908702011-10-24 17:54:18 +00001994/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001995///
1996/// \param Info Information about the ongoing evaluation.
1997/// \param E An expression to be used when printing diagnostics.
1998/// \param VD The variable whose initializer should be obtained.
1999/// \param Frame The frame in which the variable was created. Must be null
2000/// if this variable is not local to the evaluation.
2001/// \param Result Filled in with a pointer to the value of the variable.
2002static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2003 const VarDecl *VD, CallStackFrame *Frame,
2004 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002005 // If this is a parameter to an active constexpr function call, perform
2006 // argument substitution.
2007 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002008 // Assume arguments of a potential constant expression are unknown
2009 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002010 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002011 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002012 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002013 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002014 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002015 }
Richard Smith3229b742013-05-05 21:17:10 +00002016 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002017 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002018 }
Richard Smith27908702011-10-24 17:54:18 +00002019
Richard Smithd9f663b2013-04-22 15:31:51 +00002020 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002021 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002022 Result = Frame->getTemporary(VD);
2023 assert(Result && "missing value for local variable");
2024 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002025 }
2026
Richard Smithd0b4dd62011-12-19 06:19:21 +00002027 // Dig out the initializer, and use the declaration which it's attached to.
2028 const Expr *Init = VD->getAnyInitializer(VD);
2029 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002030 // If we're checking a potential constant expression, the variable could be
2031 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002032 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002034 return false;
2035 }
2036
Richard Smithd62306a2011-11-10 06:34:14 +00002037 // If we're currently evaluating the initializer of this declaration, use that
2038 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002039 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002040 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002041 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002042 }
2043
Richard Smithcecf1842011-11-01 21:06:14 +00002044 // Never evaluate the initializer of a weak variable. We can't be sure that
2045 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002046 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002047 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002048 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002049 }
Richard Smithcecf1842011-11-01 21:06:14 +00002050
Richard Smithd0b4dd62011-12-19 06:19:21 +00002051 // Check that we can fold the initializer. In C++, we will have already done
2052 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002053 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002054 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002055 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002056 Notes.size() + 1) << VD;
2057 Info.Note(VD->getLocation(), diag::note_declared_at);
2058 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002059 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002060 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002061 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002062 Notes.size() + 1) << VD;
2063 Info.Note(VD->getLocation(), diag::note_declared_at);
2064 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002065 }
Richard Smith27908702011-10-24 17:54:18 +00002066
Richard Smith3229b742013-05-05 21:17:10 +00002067 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002068 return true;
Richard Smith27908702011-10-24 17:54:18 +00002069}
2070
Richard Smith11562c52011-10-28 17:51:58 +00002071static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002072 Qualifiers Quals = T.getQualifiers();
2073 return Quals.hasConst() && !Quals.hasVolatile();
2074}
2075
Richard Smithe97cbd72011-11-11 04:05:33 +00002076/// Get the base index of the given base class within an APValue representing
2077/// the given derived class.
2078static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2079 const CXXRecordDecl *Base) {
2080 Base = Base->getCanonicalDecl();
2081 unsigned Index = 0;
2082 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2083 E = Derived->bases_end(); I != E; ++I, ++Index) {
2084 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2085 return Index;
2086 }
2087
2088 llvm_unreachable("base class missing from derived class's bases list");
2089}
2090
Richard Smith3da88fa2013-04-26 14:36:30 +00002091/// Extract the value of a character from a string literal.
2092static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2093 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002094 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2095 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2096 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002097 const StringLiteral *S = cast<StringLiteral>(Lit);
2098 const ConstantArrayType *CAT =
2099 Info.Ctx.getAsConstantArrayType(S->getType());
2100 assert(CAT && "string literal isn't an array");
2101 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002102 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002103
2104 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002105 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002106 if (Index < S->getLength())
2107 Value = S->getCodeUnit(Index);
2108 return Value;
2109}
2110
Richard Smith3da88fa2013-04-26 14:36:30 +00002111// Expand a string literal into an array of characters.
2112static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2113 APValue &Result) {
2114 const StringLiteral *S = cast<StringLiteral>(Lit);
2115 const ConstantArrayType *CAT =
2116 Info.Ctx.getAsConstantArrayType(S->getType());
2117 assert(CAT && "string literal isn't an array");
2118 QualType CharType = CAT->getElementType();
2119 assert(CharType->isIntegerType() && "unexpected character type");
2120
2121 unsigned Elts = CAT->getSize().getZExtValue();
2122 Result = APValue(APValue::UninitArray(),
2123 std::min(S->getLength(), Elts), Elts);
2124 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2125 CharType->isUnsignedIntegerType());
2126 if (Result.hasArrayFiller())
2127 Result.getArrayFiller() = APValue(Value);
2128 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2129 Value = S->getCodeUnit(I);
2130 Result.getArrayInitializedElt(I) = APValue(Value);
2131 }
2132}
2133
2134// Expand an array so that it has more than Index filled elements.
2135static void expandArray(APValue &Array, unsigned Index) {
2136 unsigned Size = Array.getArraySize();
2137 assert(Index < Size);
2138
2139 // Always at least double the number of elements for which we store a value.
2140 unsigned OldElts = Array.getArrayInitializedElts();
2141 unsigned NewElts = std::max(Index+1, OldElts * 2);
2142 NewElts = std::min(Size, std::max(NewElts, 8u));
2143
2144 // Copy the data across.
2145 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2146 for (unsigned I = 0; I != OldElts; ++I)
2147 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2148 for (unsigned I = OldElts; I != NewElts; ++I)
2149 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2150 if (NewValue.hasArrayFiller())
2151 NewValue.getArrayFiller() = Array.getArrayFiller();
2152 Array.swap(NewValue);
2153}
2154
Richard Smithb01fe402014-09-16 01:24:02 +00002155/// Determine whether a type would actually be read by an lvalue-to-rvalue
2156/// conversion. If it's of class type, we may assume that the copy operation
2157/// is trivial. Note that this is never true for a union type with fields
2158/// (because the copy always "reads" the active member) and always true for
2159/// a non-class type.
2160static bool isReadByLvalueToRvalueConversion(QualType T) {
2161 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2162 if (!RD || (RD->isUnion() && !RD->field_empty()))
2163 return true;
2164 if (RD->isEmpty())
2165 return false;
2166
2167 for (auto *Field : RD->fields())
2168 if (isReadByLvalueToRvalueConversion(Field->getType()))
2169 return true;
2170
2171 for (auto &BaseSpec : RD->bases())
2172 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2173 return true;
2174
2175 return false;
2176}
2177
2178/// Diagnose an attempt to read from any unreadable field within the specified
2179/// type, which might be a class type.
2180static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2181 QualType T) {
2182 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2183 if (!RD)
2184 return false;
2185
2186 if (!RD->hasMutableFields())
2187 return false;
2188
2189 for (auto *Field : RD->fields()) {
2190 // If we're actually going to read this field in some way, then it can't
2191 // be mutable. If we're in a union, then assigning to a mutable field
2192 // (even an empty one) can change the active member, so that's not OK.
2193 // FIXME: Add core issue number for the union case.
2194 if (Field->isMutable() &&
2195 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2196 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2197 Info.Note(Field->getLocation(), diag::note_declared_at);
2198 return true;
2199 }
2200
2201 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2202 return true;
2203 }
2204
2205 for (auto &BaseSpec : RD->bases())
2206 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2207 return true;
2208
2209 // All mutable fields were empty, and thus not actually read.
2210 return false;
2211}
2212
Richard Smith861b5b52013-05-07 23:34:45 +00002213/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002214enum AccessKinds {
2215 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002216 AK_Assign,
2217 AK_Increment,
2218 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002219};
2220
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002221namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002222/// A handle to a complete object (an object that is not a subobject of
2223/// another object).
2224struct CompleteObject {
2225 /// The value of the complete object.
2226 APValue *Value;
2227 /// The type of the complete object.
2228 QualType Type;
2229
Craig Topper36250ad2014-05-12 05:36:57 +00002230 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002231 CompleteObject(APValue *Value, QualType Type)
2232 : Value(Value), Type(Type) {
2233 assert(Value && "missing value for complete object");
2234 }
2235
Aaron Ballman67347662015-02-15 22:00:28 +00002236 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002237};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002238} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002239
Richard Smith3da88fa2013-04-26 14:36:30 +00002240/// Find the designated sub-object of an rvalue.
2241template<typename SubobjectHandler>
2242typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002243findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002244 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002245 if (Sub.Invalid)
2246 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002247 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002248 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002249 if (Info.getLangOpts().CPlusPlus11)
2250 Info.Diag(E, diag::note_constexpr_access_past_end)
2251 << handler.AccessKind;
2252 else
2253 Info.Diag(E);
2254 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002255 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002256
Richard Smith3229b742013-05-05 21:17:10 +00002257 APValue *O = Obj.Value;
2258 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002259 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002260
Richard Smithd62306a2011-11-10 06:34:14 +00002261 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002262 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2263 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002264 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002265 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2266 return handler.failed();
2267 }
2268
Richard Smith49ca8aa2013-08-06 07:09:20 +00002269 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002270 // If we are reading an object of class type, there may still be more
2271 // things we need to check: if there are any mutable subobjects, we
2272 // cannot perform this read. (This only happens when performing a trivial
2273 // copy or assignment.)
2274 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2275 diagnoseUnreadableFields(Info, E, ObjType))
2276 return handler.failed();
2277
Richard Smith49ca8aa2013-08-06 07:09:20 +00002278 if (!handler.found(*O, ObjType))
2279 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002280
Richard Smith49ca8aa2013-08-06 07:09:20 +00002281 // If we modified a bit-field, truncate it to the right width.
2282 if (handler.AccessKind != AK_Read &&
2283 LastField && LastField->isBitField() &&
2284 !truncateBitfieldValue(Info, E, *O, LastField))
2285 return false;
2286
2287 return true;
2288 }
2289
Craig Topper36250ad2014-05-12 05:36:57 +00002290 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002291 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002292 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002293 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002294 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002295 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002296 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002297 // Note, it should not be possible to form a pointer with a valid
2298 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002299 if (Info.getLangOpts().CPlusPlus11)
2300 Info.Diag(E, diag::note_constexpr_access_past_end)
2301 << handler.AccessKind;
2302 else
2303 Info.Diag(E);
2304 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002305 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002306
2307 ObjType = CAT->getElementType();
2308
Richard Smith14a94132012-02-17 03:35:37 +00002309 // An array object is represented as either an Array APValue or as an
2310 // LValue which refers to a string literal.
2311 if (O->isLValue()) {
2312 assert(I == N - 1 && "extracting subobject of character?");
2313 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002314 if (handler.AccessKind != AK_Read)
2315 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2316 *O);
2317 else
2318 return handler.foundString(*O, ObjType, Index);
2319 }
2320
2321 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002322 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002323 else if (handler.AccessKind != AK_Read) {
2324 expandArray(*O, Index);
2325 O = &O->getArrayInitializedElt(Index);
2326 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002327 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002328 } else if (ObjType->isAnyComplexType()) {
2329 // Next subobject is a complex number.
2330 uint64_t Index = Sub.Entries[I].ArrayIndex;
2331 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002332 if (Info.getLangOpts().CPlusPlus11)
2333 Info.Diag(E, diag::note_constexpr_access_past_end)
2334 << handler.AccessKind;
2335 else
2336 Info.Diag(E);
2337 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002338 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002339
2340 bool WasConstQualified = ObjType.isConstQualified();
2341 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2342 if (WasConstQualified)
2343 ObjType.addConst();
2344
Richard Smith66c96992012-02-18 22:04:06 +00002345 assert(I == N - 1 && "extracting subobject of scalar?");
2346 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002347 return handler.found(Index ? O->getComplexIntImag()
2348 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002349 } else {
2350 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002351 return handler.found(Index ? O->getComplexFloatImag()
2352 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002353 }
Richard Smithd62306a2011-11-10 06:34:14 +00002354 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002355 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002356 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002357 << Field;
2358 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002359 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002360 }
2361
Richard Smithd62306a2011-11-10 06:34:14 +00002362 // Next subobject is a class, struct or union field.
2363 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2364 if (RD->isUnion()) {
2365 const FieldDecl *UnionField = O->getUnionField();
2366 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002367 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002368 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2369 << handler.AccessKind << Field << !UnionField << UnionField;
2370 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002371 }
Richard Smithd62306a2011-11-10 06:34:14 +00002372 O = &O->getUnionValue();
2373 } else
2374 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002375
2376 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002377 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002378 if (WasConstQualified && !Field->isMutable())
2379 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002380
2381 if (ObjType.isVolatileQualified()) {
2382 if (Info.getLangOpts().CPlusPlus) {
2383 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002384 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2385 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002386 Info.Note(Field->getLocation(), diag::note_declared_at);
2387 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002388 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002389 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002390 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002391 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002392
2393 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002394 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002395 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002396 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2397 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2398 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002399
2400 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002401 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002402 if (WasConstQualified)
2403 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002404 }
2405 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002406}
2407
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002408namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002409struct ExtractSubobjectHandler {
2410 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002411 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002412
2413 static const AccessKinds AccessKind = AK_Read;
2414
2415 typedef bool result_type;
2416 bool failed() { return false; }
2417 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002418 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002419 return true;
2420 }
2421 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002422 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002423 return true;
2424 }
2425 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002426 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002427 return true;
2428 }
2429 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002430 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002431 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2432 return true;
2433 }
2434};
Richard Smith3229b742013-05-05 21:17:10 +00002435} // end anonymous namespace
2436
Richard Smith3da88fa2013-04-26 14:36:30 +00002437const AccessKinds ExtractSubobjectHandler::AccessKind;
2438
2439/// Extract the designated sub-object of an rvalue.
2440static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002441 const CompleteObject &Obj,
2442 const SubobjectDesignator &Sub,
2443 APValue &Result) {
2444 ExtractSubobjectHandler Handler = { Info, Result };
2445 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002446}
2447
Richard Smith3229b742013-05-05 21:17:10 +00002448namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002449struct ModifySubobjectHandler {
2450 EvalInfo &Info;
2451 APValue &NewVal;
2452 const Expr *E;
2453
2454 typedef bool result_type;
2455 static const AccessKinds AccessKind = AK_Assign;
2456
2457 bool checkConst(QualType QT) {
2458 // Assigning to a const object has undefined behavior.
2459 if (QT.isConstQualified()) {
2460 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2461 return false;
2462 }
2463 return true;
2464 }
2465
2466 bool failed() { return false; }
2467 bool found(APValue &Subobj, QualType SubobjType) {
2468 if (!checkConst(SubobjType))
2469 return false;
2470 // We've been given ownership of NewVal, so just swap it in.
2471 Subobj.swap(NewVal);
2472 return true;
2473 }
2474 bool found(APSInt &Value, QualType SubobjType) {
2475 if (!checkConst(SubobjType))
2476 return false;
2477 if (!NewVal.isInt()) {
2478 // Maybe trying to write a cast pointer value into a complex?
2479 Info.Diag(E);
2480 return false;
2481 }
2482 Value = NewVal.getInt();
2483 return true;
2484 }
2485 bool found(APFloat &Value, QualType SubobjType) {
2486 if (!checkConst(SubobjType))
2487 return false;
2488 Value = NewVal.getFloat();
2489 return true;
2490 }
2491 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2492 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2493 }
2494};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002495} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002496
Richard Smith3229b742013-05-05 21:17:10 +00002497const AccessKinds ModifySubobjectHandler::AccessKind;
2498
Richard Smith3da88fa2013-04-26 14:36:30 +00002499/// Update the designated sub-object of an rvalue to the given value.
2500static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002501 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002502 const SubobjectDesignator &Sub,
2503 APValue &NewVal) {
2504 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002505 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002506}
2507
Richard Smith84f6dcf2012-02-02 01:16:57 +00002508/// Find the position where two subobject designators diverge, or equivalently
2509/// the length of the common initial subsequence.
2510static unsigned FindDesignatorMismatch(QualType ObjType,
2511 const SubobjectDesignator &A,
2512 const SubobjectDesignator &B,
2513 bool &WasArrayIndex) {
2514 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2515 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002516 if (!ObjType.isNull() &&
2517 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002518 // Next subobject is an array element.
2519 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2520 WasArrayIndex = true;
2521 return I;
2522 }
Richard Smith66c96992012-02-18 22:04:06 +00002523 if (ObjType->isAnyComplexType())
2524 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2525 else
2526 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002527 } else {
2528 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2529 WasArrayIndex = false;
2530 return I;
2531 }
2532 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2533 // Next subobject is a field.
2534 ObjType = FD->getType();
2535 else
2536 // Next subobject is a base class.
2537 ObjType = QualType();
2538 }
2539 }
2540 WasArrayIndex = false;
2541 return I;
2542}
2543
2544/// Determine whether the given subobject designators refer to elements of the
2545/// same array object.
2546static bool AreElementsOfSameArray(QualType ObjType,
2547 const SubobjectDesignator &A,
2548 const SubobjectDesignator &B) {
2549 if (A.Entries.size() != B.Entries.size())
2550 return false;
2551
George Burgess IVa51c4072015-10-16 01:49:01 +00002552 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002553 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2554 // A is a subobject of the array element.
2555 return false;
2556
2557 // If A (and B) designates an array element, the last entry will be the array
2558 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2559 // of length 1' case, and the entire path must match.
2560 bool WasArrayIndex;
2561 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2562 return CommonLength >= A.Entries.size() - IsArray;
2563}
2564
Richard Smith3229b742013-05-05 21:17:10 +00002565/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002566static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2567 AccessKinds AK, const LValue &LVal,
2568 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002569 if (!LVal.Base) {
2570 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2571 return CompleteObject();
2572 }
2573
Craig Topper36250ad2014-05-12 05:36:57 +00002574 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002575 if (LVal.CallIndex) {
2576 Frame = Info.getCallFrame(LVal.CallIndex);
2577 if (!Frame) {
2578 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2579 << AK << LVal.Base.is<const ValueDecl*>();
2580 NoteLValueLocation(Info, LVal.Base);
2581 return CompleteObject();
2582 }
Richard Smith3229b742013-05-05 21:17:10 +00002583 }
2584
2585 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2586 // is not a constant expression (even if the object is non-volatile). We also
2587 // apply this rule to C++98, in order to conform to the expected 'volatile'
2588 // semantics.
2589 if (LValType.isVolatileQualified()) {
2590 if (Info.getLangOpts().CPlusPlus)
2591 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2592 << AK << LValType;
2593 else
2594 Info.Diag(E);
2595 return CompleteObject();
2596 }
2597
2598 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002599 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002600 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002601
2602 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2603 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2604 // In C++11, constexpr, non-volatile variables initialized with constant
2605 // expressions are constant expressions too. Inside constexpr functions,
2606 // parameters are constant expressions even if they're non-const.
2607 // In C++1y, objects local to a constant expression (those with a Frame) are
2608 // both readable and writable inside constant expressions.
2609 // In C, such things can also be folded, although they are not ICEs.
2610 const VarDecl *VD = dyn_cast<VarDecl>(D);
2611 if (VD) {
2612 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2613 VD = VDef;
2614 }
2615 if (!VD || VD->isInvalidDecl()) {
2616 Info.Diag(E);
2617 return CompleteObject();
2618 }
2619
2620 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002621 if (BaseType.isVolatileQualified()) {
2622 if (Info.getLangOpts().CPlusPlus) {
2623 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2624 << AK << 1 << VD;
2625 Info.Note(VD->getLocation(), diag::note_declared_at);
2626 } else {
2627 Info.Diag(E);
2628 }
2629 return CompleteObject();
2630 }
2631
2632 // Unless we're looking at a local variable or argument in a constexpr call,
2633 // the variable we're reading must be const.
2634 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002635 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002636 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2637 // OK, we can read and modify an object if we're in the process of
2638 // evaluating its initializer, because its lifetime began in this
2639 // evaluation.
2640 } else if (AK != AK_Read) {
2641 // All the remaining cases only permit reading.
2642 Info.Diag(E, diag::note_constexpr_modify_global);
2643 return CompleteObject();
2644 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002645 // OK, we can read this variable.
2646 } else if (BaseType->isIntegralOrEnumerationType()) {
2647 if (!BaseType.isConstQualified()) {
2648 if (Info.getLangOpts().CPlusPlus) {
2649 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2650 Info.Note(VD->getLocation(), diag::note_declared_at);
2651 } else {
2652 Info.Diag(E);
2653 }
2654 return CompleteObject();
2655 }
2656 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2657 // We support folding of const floating-point types, in order to make
2658 // static const data members of such types (supported as an extension)
2659 // more useful.
2660 if (Info.getLangOpts().CPlusPlus11) {
2661 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2662 Info.Note(VD->getLocation(), diag::note_declared_at);
2663 } else {
2664 Info.CCEDiag(E);
2665 }
2666 } else {
2667 // FIXME: Allow folding of values of any literal type in all languages.
2668 if (Info.getLangOpts().CPlusPlus11) {
2669 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2670 Info.Note(VD->getLocation(), diag::note_declared_at);
2671 } else {
2672 Info.Diag(E);
2673 }
2674 return CompleteObject();
2675 }
2676 }
2677
2678 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2679 return CompleteObject();
2680 } else {
2681 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2682
2683 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002684 if (const MaterializeTemporaryExpr *MTE =
2685 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2686 assert(MTE->getStorageDuration() == SD_Static &&
2687 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002688
Richard Smithe6c01442013-06-05 00:46:14 +00002689 // Per C++1y [expr.const]p2:
2690 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2691 // - a [...] glvalue of integral or enumeration type that refers to
2692 // a non-volatile const object [...]
2693 // [...]
2694 // - a [...] glvalue of literal type that refers to a non-volatile
2695 // object whose lifetime began within the evaluation of e.
2696 //
2697 // C++11 misses the 'began within the evaluation of e' check and
2698 // instead allows all temporaries, including things like:
2699 // int &&r = 1;
2700 // int x = ++r;
2701 // constexpr int k = r;
2702 // Therefore we use the C++1y rules in C++11 too.
2703 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2704 const ValueDecl *ED = MTE->getExtendingDecl();
2705 if (!(BaseType.isConstQualified() &&
2706 BaseType->isIntegralOrEnumerationType()) &&
2707 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2708 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2709 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2710 return CompleteObject();
2711 }
2712
2713 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2714 assert(BaseVal && "got reference to unevaluated temporary");
2715 } else {
2716 Info.Diag(E);
2717 return CompleteObject();
2718 }
2719 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002720 BaseVal = Frame->getTemporary(Base);
2721 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002722 }
Richard Smith3229b742013-05-05 21:17:10 +00002723
2724 // Volatile temporary objects cannot be accessed in constant expressions.
2725 if (BaseType.isVolatileQualified()) {
2726 if (Info.getLangOpts().CPlusPlus) {
2727 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2728 << AK << 0;
2729 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2730 } else {
2731 Info.Diag(E);
2732 }
2733 return CompleteObject();
2734 }
2735 }
2736
Richard Smith7525ff62013-05-09 07:14:00 +00002737 // During the construction of an object, it is not yet 'const'.
2738 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2739 // and this doesn't do quite the right thing for const subobjects of the
2740 // object under construction.
2741 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2742 BaseType = Info.Ctx.getCanonicalType(BaseType);
2743 BaseType.removeLocalConst();
2744 }
2745
Richard Smith6d4c6582013-11-05 22:18:15 +00002746 // In C++1y, we can't safely access any mutable state when we might be
2747 // evaluating after an unmodeled side effect or an evaluation failure.
2748 //
2749 // FIXME: Not all local state is mutable. Allow local constant subobjects
2750 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002751 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002752 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002753 return CompleteObject();
2754
2755 return CompleteObject(BaseVal, BaseType);
2756}
2757
Richard Smith243ef902013-05-05 23:31:59 +00002758/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2759/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2760/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002761///
2762/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002763/// \param Conv - The expression for which we are performing the conversion.
2764/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002765/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2766/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002767/// \param LVal - The glvalue on which we are attempting to perform this action.
2768/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002769static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002770 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002771 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002772 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002773 return false;
2774
Richard Smith3229b742013-05-05 21:17:10 +00002775 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002776 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002777 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002778 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2779 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2780 // initializer until now for such expressions. Such an expression can't be
2781 // an ICE in C, so this only matters for fold.
2782 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2783 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002784 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002785 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002786 }
Richard Smith3229b742013-05-05 21:17:10 +00002787 APValue Lit;
2788 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2789 return false;
2790 CompleteObject LitObj(&Lit, Base->getType());
2791 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002792 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002793 // We represent a string literal array as an lvalue pointing at the
2794 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002795 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002796 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2797 CompleteObject StrObj(&Str, Base->getType());
2798 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002799 }
Richard Smith11562c52011-10-28 17:51:58 +00002800 }
2801
Richard Smith3229b742013-05-05 21:17:10 +00002802 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2803 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002804}
2805
2806/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002807static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002808 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002809 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002810 return false;
2811
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002812 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002813 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002814 return false;
2815 }
2816
Richard Smith3229b742013-05-05 21:17:10 +00002817 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2818 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002819}
2820
Richard Smith243ef902013-05-05 23:31:59 +00002821static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2822 return T->isSignedIntegerType() &&
2823 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2824}
2825
2826namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002827struct CompoundAssignSubobjectHandler {
2828 EvalInfo &Info;
2829 const Expr *E;
2830 QualType PromotedLHSType;
2831 BinaryOperatorKind Opcode;
2832 const APValue &RHS;
2833
2834 static const AccessKinds AccessKind = AK_Assign;
2835
2836 typedef bool result_type;
2837
2838 bool checkConst(QualType QT) {
2839 // Assigning to a const object has undefined behavior.
2840 if (QT.isConstQualified()) {
2841 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2842 return false;
2843 }
2844 return true;
2845 }
2846
2847 bool failed() { return false; }
2848 bool found(APValue &Subobj, QualType SubobjType) {
2849 switch (Subobj.getKind()) {
2850 case APValue::Int:
2851 return found(Subobj.getInt(), SubobjType);
2852 case APValue::Float:
2853 return found(Subobj.getFloat(), SubobjType);
2854 case APValue::ComplexInt:
2855 case APValue::ComplexFloat:
2856 // FIXME: Implement complex compound assignment.
2857 Info.Diag(E);
2858 return false;
2859 case APValue::LValue:
2860 return foundPointer(Subobj, SubobjType);
2861 default:
2862 // FIXME: can this happen?
2863 Info.Diag(E);
2864 return false;
2865 }
2866 }
2867 bool found(APSInt &Value, QualType SubobjType) {
2868 if (!checkConst(SubobjType))
2869 return false;
2870
2871 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2872 // We don't support compound assignment on integer-cast-to-pointer
2873 // values.
2874 Info.Diag(E);
2875 return false;
2876 }
2877
2878 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2879 SubobjType, Value);
2880 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2881 return false;
2882 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2883 return true;
2884 }
2885 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002886 return checkConst(SubobjType) &&
2887 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2888 Value) &&
2889 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2890 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002891 }
2892 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2893 if (!checkConst(SubobjType))
2894 return false;
2895
2896 QualType PointeeType;
2897 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2898 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002899
2900 if (PointeeType.isNull() || !RHS.isInt() ||
2901 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002902 Info.Diag(E);
2903 return false;
2904 }
2905
Richard Smith861b5b52013-05-07 23:34:45 +00002906 int64_t Offset = getExtValue(RHS.getInt());
2907 if (Opcode == BO_Sub)
2908 Offset = -Offset;
2909
2910 LValue LVal;
2911 LVal.setFrom(Info.Ctx, Subobj);
2912 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2913 return false;
2914 LVal.moveInto(Subobj);
2915 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002916 }
2917 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2918 llvm_unreachable("shouldn't encounter string elements here");
2919 }
2920};
2921} // end anonymous namespace
2922
2923const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2924
2925/// Perform a compound assignment of LVal <op>= RVal.
2926static bool handleCompoundAssignment(
2927 EvalInfo &Info, const Expr *E,
2928 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2929 BinaryOperatorKind Opcode, const APValue &RVal) {
2930 if (LVal.Designator.Invalid)
2931 return false;
2932
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002933 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002934 Info.Diag(E);
2935 return false;
2936 }
2937
2938 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2939 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2940 RVal };
2941 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2942}
2943
2944namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002945struct IncDecSubobjectHandler {
2946 EvalInfo &Info;
2947 const Expr *E;
2948 AccessKinds AccessKind;
2949 APValue *Old;
2950
2951 typedef bool result_type;
2952
2953 bool checkConst(QualType QT) {
2954 // Assigning to a const object has undefined behavior.
2955 if (QT.isConstQualified()) {
2956 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2957 return false;
2958 }
2959 return true;
2960 }
2961
2962 bool failed() { return false; }
2963 bool found(APValue &Subobj, QualType SubobjType) {
2964 // Stash the old value. Also clear Old, so we don't clobber it later
2965 // if we're post-incrementing a complex.
2966 if (Old) {
2967 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002968 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002969 }
2970
2971 switch (Subobj.getKind()) {
2972 case APValue::Int:
2973 return found(Subobj.getInt(), SubobjType);
2974 case APValue::Float:
2975 return found(Subobj.getFloat(), SubobjType);
2976 case APValue::ComplexInt:
2977 return found(Subobj.getComplexIntReal(),
2978 SubobjType->castAs<ComplexType>()->getElementType()
2979 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2980 case APValue::ComplexFloat:
2981 return found(Subobj.getComplexFloatReal(),
2982 SubobjType->castAs<ComplexType>()->getElementType()
2983 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2984 case APValue::LValue:
2985 return foundPointer(Subobj, SubobjType);
2986 default:
2987 // FIXME: can this happen?
2988 Info.Diag(E);
2989 return false;
2990 }
2991 }
2992 bool found(APSInt &Value, QualType SubobjType) {
2993 if (!checkConst(SubobjType))
2994 return false;
2995
2996 if (!SubobjType->isIntegerType()) {
2997 // We don't support increment / decrement on integer-cast-to-pointer
2998 // values.
2999 Info.Diag(E);
3000 return false;
3001 }
3002
3003 if (Old) *Old = APValue(Value);
3004
3005 // bool arithmetic promotes to int, and the conversion back to bool
3006 // doesn't reduce mod 2^n, so special-case it.
3007 if (SubobjType->isBooleanType()) {
3008 if (AccessKind == AK_Increment)
3009 Value = 1;
3010 else
3011 Value = !Value;
3012 return true;
3013 }
3014
3015 bool WasNegative = Value.isNegative();
3016 if (AccessKind == AK_Increment) {
3017 ++Value;
3018
3019 if (!WasNegative && Value.isNegative() &&
3020 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3021 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003022 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003023 }
3024 } else {
3025 --Value;
3026
3027 if (WasNegative && !Value.isNegative() &&
3028 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3029 unsigned BitWidth = Value.getBitWidth();
3030 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3031 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003032 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003033 }
3034 }
3035 return true;
3036 }
3037 bool found(APFloat &Value, QualType SubobjType) {
3038 if (!checkConst(SubobjType))
3039 return false;
3040
3041 if (Old) *Old = APValue(Value);
3042
3043 APFloat One(Value.getSemantics(), 1);
3044 if (AccessKind == AK_Increment)
3045 Value.add(One, APFloat::rmNearestTiesToEven);
3046 else
3047 Value.subtract(One, APFloat::rmNearestTiesToEven);
3048 return true;
3049 }
3050 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3051 if (!checkConst(SubobjType))
3052 return false;
3053
3054 QualType PointeeType;
3055 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3056 PointeeType = PT->getPointeeType();
3057 else {
3058 Info.Diag(E);
3059 return false;
3060 }
3061
3062 LValue LVal;
3063 LVal.setFrom(Info.Ctx, Subobj);
3064 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3065 AccessKind == AK_Increment ? 1 : -1))
3066 return false;
3067 LVal.moveInto(Subobj);
3068 return true;
3069 }
3070 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3071 llvm_unreachable("shouldn't encounter string elements here");
3072 }
3073};
3074} // end anonymous namespace
3075
3076/// Perform an increment or decrement on LVal.
3077static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3078 QualType LValType, bool IsIncrement, APValue *Old) {
3079 if (LVal.Designator.Invalid)
3080 return false;
3081
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003082 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003083 Info.Diag(E);
3084 return false;
3085 }
3086
3087 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3088 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3089 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3090 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3091}
3092
Richard Smithe97cbd72011-11-11 04:05:33 +00003093/// Build an lvalue for the object argument of a member function call.
3094static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3095 LValue &This) {
3096 if (Object->getType()->isPointerType())
3097 return EvaluatePointer(Object, This, Info);
3098
3099 if (Object->isGLValue())
3100 return EvaluateLValue(Object, This, Info);
3101
Richard Smithd9f663b2013-04-22 15:31:51 +00003102 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003103 return EvaluateTemporary(Object, This, Info);
3104
Richard Smith3e79a572014-06-11 19:53:12 +00003105 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003106 return false;
3107}
3108
3109/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3110/// lvalue referring to the result.
3111///
3112/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003113/// \param LV - An lvalue referring to the base of the member pointer.
3114/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003115/// \param IncludeMember - Specifies whether the member itself is included in
3116/// the resulting LValue subobject designator. This is not possible when
3117/// creating a bound member function.
3118/// \return The field or method declaration to which the member pointer refers,
3119/// or 0 if evaluation fails.
3120static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003121 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003122 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003123 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003124 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003125 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003126 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003127 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003128
3129 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3130 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003131 if (!MemPtr.getDecl()) {
3132 // FIXME: Specific diagnostic.
3133 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003134 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003135 }
Richard Smith253c2a32012-01-27 01:14:48 +00003136
Richard Smith027bf112011-11-17 22:56:20 +00003137 if (MemPtr.isDerivedMember()) {
3138 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003139 // The end of the derived-to-base path for the base object must match the
3140 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003141 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003142 LV.Designator.Entries.size()) {
3143 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003144 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003145 }
Richard Smith027bf112011-11-17 22:56:20 +00003146 unsigned PathLengthToMember =
3147 LV.Designator.Entries.size() - MemPtr.Path.size();
3148 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3149 const CXXRecordDecl *LVDecl = getAsBaseClass(
3150 LV.Designator.Entries[PathLengthToMember + I]);
3151 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003152 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3153 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003154 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003155 }
Richard Smith027bf112011-11-17 22:56:20 +00003156 }
3157
3158 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003159 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003160 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003161 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003162 } else if (!MemPtr.Path.empty()) {
3163 // Extend the LValue path with the member pointer's path.
3164 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3165 MemPtr.Path.size() + IncludeMember);
3166
3167 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003168 if (const PointerType *PT = LVType->getAs<PointerType>())
3169 LVType = PT->getPointeeType();
3170 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3171 assert(RD && "member pointer access on non-class-type expression");
3172 // The first class in the path is that of the lvalue.
3173 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3174 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003175 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003176 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003177 RD = Base;
3178 }
3179 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003180 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3181 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003182 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003183 }
3184
3185 // Add the member. Note that we cannot build bound member functions here.
3186 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003187 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003188 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003189 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003190 } else if (const IndirectFieldDecl *IFD =
3191 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003192 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003193 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003194 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003195 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003196 }
Richard Smith027bf112011-11-17 22:56:20 +00003197 }
3198
3199 return MemPtr.getDecl();
3200}
3201
Richard Smith84401042013-06-03 05:03:02 +00003202static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3203 const BinaryOperator *BO,
3204 LValue &LV,
3205 bool IncludeMember = true) {
3206 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3207
3208 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3209 if (Info.keepEvaluatingAfterFailure()) {
3210 MemberPtr MemPtr;
3211 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3212 }
Craig Topper36250ad2014-05-12 05:36:57 +00003213 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003214 }
3215
3216 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3217 BO->getRHS(), IncludeMember);
3218}
3219
Richard Smith027bf112011-11-17 22:56:20 +00003220/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3221/// the provided lvalue, which currently refers to the base object.
3222static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3223 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003224 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003225 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003226 return false;
3227
Richard Smitha8105bc2012-01-06 16:39:00 +00003228 QualType TargetQT = E->getType();
3229 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3230 TargetQT = PT->getPointeeType();
3231
3232 // Check this cast lands within the final derived-to-base subobject path.
3233 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003234 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003235 << D.MostDerivedType << TargetQT;
3236 return false;
3237 }
3238
Richard Smith027bf112011-11-17 22:56:20 +00003239 // Check the type of the final cast. We don't need to check the path,
3240 // since a cast can only be formed if the path is unique.
3241 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003242 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3243 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003244 if (NewEntriesSize == D.MostDerivedPathLength)
3245 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3246 else
Richard Smith027bf112011-11-17 22:56:20 +00003247 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003248 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003249 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003250 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003251 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003252 }
Richard Smith027bf112011-11-17 22:56:20 +00003253
3254 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003255 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003256}
3257
Mike Stump876387b2009-10-27 22:09:17 +00003258namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003259enum EvalStmtResult {
3260 /// Evaluation failed.
3261 ESR_Failed,
3262 /// Hit a 'return' statement.
3263 ESR_Returned,
3264 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003265 ESR_Succeeded,
3266 /// Hit a 'continue' statement.
3267 ESR_Continue,
3268 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003269 ESR_Break,
3270 /// Still scanning for 'case' or 'default' statement.
3271 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003272};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003273}
Richard Smith254a73d2011-10-28 22:34:42 +00003274
Richard Smithd9f663b2013-04-22 15:31:51 +00003275static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3276 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3277 // We don't need to evaluate the initializer for a static local.
3278 if (!VD->hasLocalStorage())
3279 return true;
3280
3281 LValue Result;
3282 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003283 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003284
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003285 const Expr *InitE = VD->getInit();
3286 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003287 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3288 << false << VD->getType();
3289 Val = APValue();
3290 return false;
3291 }
3292
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003293 if (InitE->isValueDependent())
3294 return false;
3295
3296 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003297 // Wipe out any partially-computed value, to allow tracking that this
3298 // evaluation failed.
3299 Val = APValue();
3300 return false;
3301 }
3302 }
3303
3304 return true;
3305}
3306
Richard Smith4e18ca52013-05-06 05:56:11 +00003307/// Evaluate a condition (either a variable declaration or an expression).
3308static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3309 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003310 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003311 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3312 return false;
3313 return EvaluateAsBooleanCondition(Cond, Result, Info);
3314}
3315
Richard Smith52a980a2015-08-28 02:43:42 +00003316/// \brief A location where the result (returned value) of evaluating a
3317/// statement should be stored.
3318struct StmtResult {
3319 /// The APValue that should be filled in with the returned value.
3320 APValue &Value;
3321 /// The location containing the result, if any (used to support RVO).
3322 const LValue *Slot;
3323};
3324
3325static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003326 const Stmt *S,
3327 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003328
3329/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003330static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003331 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003332 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003333 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003334 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003335 case ESR_Break:
3336 return ESR_Succeeded;
3337 case ESR_Succeeded:
3338 case ESR_Continue:
3339 return ESR_Continue;
3340 case ESR_Failed:
3341 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003342 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003343 return ESR;
3344 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003345 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003346}
3347
Richard Smith496ddcf2013-05-12 17:32:42 +00003348/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003349static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003350 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003351 BlockScopeRAII Scope(Info);
3352
Richard Smith496ddcf2013-05-12 17:32:42 +00003353 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003354 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003355 {
3356 FullExpressionRAII Scope(Info);
3357 if (SS->getConditionVariable() &&
3358 !EvaluateDecl(Info, SS->getConditionVariable()))
3359 return ESR_Failed;
3360 if (!EvaluateInteger(SS->getCond(), Value, Info))
3361 return ESR_Failed;
3362 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003363
3364 // Find the switch case corresponding to the value of the condition.
3365 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003366 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003367 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3368 SC = SC->getNextSwitchCase()) {
3369 if (isa<DefaultStmt>(SC)) {
3370 Found = SC;
3371 continue;
3372 }
3373
3374 const CaseStmt *CS = cast<CaseStmt>(SC);
3375 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3376 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3377 : LHS;
3378 if (LHS <= Value && Value <= RHS) {
3379 Found = SC;
3380 break;
3381 }
3382 }
3383
3384 if (!Found)
3385 return ESR_Succeeded;
3386
3387 // Search the switch body for the switch case and evaluate it from there.
3388 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3389 case ESR_Break:
3390 return ESR_Succeeded;
3391 case ESR_Succeeded:
3392 case ESR_Continue:
3393 case ESR_Failed:
3394 case ESR_Returned:
3395 return ESR;
3396 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003397 // This can only happen if the switch case is nested within a statement
3398 // expression. We have no intention of supporting that.
3399 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3400 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003401 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003402 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003403}
3404
Richard Smith254a73d2011-10-28 22:34:42 +00003405// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003406static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003407 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003408 if (!Info.nextStep(S))
3409 return ESR_Failed;
3410
Richard Smith496ddcf2013-05-12 17:32:42 +00003411 // If we're hunting down a 'case' or 'default' label, recurse through
3412 // substatements until we hit the label.
3413 if (Case) {
3414 // FIXME: We don't start the lifetime of objects whose initialization we
3415 // jump over. However, such objects must be of class type with a trivial
3416 // default constructor that initialize all subobjects, so must be empty,
3417 // so this almost never matters.
3418 switch (S->getStmtClass()) {
3419 case Stmt::CompoundStmtClass:
3420 // FIXME: Precompute which substatement of a compound statement we
3421 // would jump to, and go straight there rather than performing a
3422 // linear scan each time.
3423 case Stmt::LabelStmtClass:
3424 case Stmt::AttributedStmtClass:
3425 case Stmt::DoStmtClass:
3426 break;
3427
3428 case Stmt::CaseStmtClass:
3429 case Stmt::DefaultStmtClass:
3430 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003431 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003432 break;
3433
3434 case Stmt::IfStmtClass: {
3435 // FIXME: Precompute which side of an 'if' we would jump to, and go
3436 // straight there rather than scanning both sides.
3437 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003438
3439 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3440 // preceded by our switch label.
3441 BlockScopeRAII Scope(Info);
3442
Richard Smith496ddcf2013-05-12 17:32:42 +00003443 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3444 if (ESR != ESR_CaseNotFound || !IS->getElse())
3445 return ESR;
3446 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3447 }
3448
3449 case Stmt::WhileStmtClass: {
3450 EvalStmtResult ESR =
3451 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3452 if (ESR != ESR_Continue)
3453 return ESR;
3454 break;
3455 }
3456
3457 case Stmt::ForStmtClass: {
3458 const ForStmt *FS = cast<ForStmt>(S);
3459 EvalStmtResult ESR =
3460 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3461 if (ESR != ESR_Continue)
3462 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003463 if (FS->getInc()) {
3464 FullExpressionRAII IncScope(Info);
3465 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3466 return ESR_Failed;
3467 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003468 break;
3469 }
3470
3471 case Stmt::DeclStmtClass:
3472 // FIXME: If the variable has initialization that can't be jumped over,
3473 // bail out of any immediately-surrounding compound-statement too.
3474 default:
3475 return ESR_CaseNotFound;
3476 }
3477 }
3478
Richard Smith254a73d2011-10-28 22:34:42 +00003479 switch (S->getStmtClass()) {
3480 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003481 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003482 // Don't bother evaluating beyond an expression-statement which couldn't
3483 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003484 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003485 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003486 return ESR_Failed;
3487 return ESR_Succeeded;
3488 }
3489
3490 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003491 return ESR_Failed;
3492
3493 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003494 return ESR_Succeeded;
3495
Richard Smithd9f663b2013-04-22 15:31:51 +00003496 case Stmt::DeclStmtClass: {
3497 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003498 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003499 // Each declaration initialization is its own full-expression.
3500 // FIXME: This isn't quite right; if we're performing aggregate
3501 // initialization, each braced subexpression is its own full-expression.
3502 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003503 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003504 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003505 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003506 return ESR_Succeeded;
3507 }
3508
Richard Smith357362d2011-12-13 06:39:58 +00003509 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003510 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003511 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003512 if (RetExpr &&
3513 !(Result.Slot
3514 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3515 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003516 return ESR_Failed;
3517 return ESR_Returned;
3518 }
Richard Smith254a73d2011-10-28 22:34:42 +00003519
3520 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003521 BlockScopeRAII Scope(Info);
3522
Richard Smith254a73d2011-10-28 22:34:42 +00003523 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003524 for (const auto *BI : CS->body()) {
3525 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003526 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003527 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003528 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003529 return ESR;
3530 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003531 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003532 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003533
3534 case Stmt::IfStmtClass: {
3535 const IfStmt *IS = cast<IfStmt>(S);
3536
3537 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003538 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003539 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003540 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003541 return ESR_Failed;
3542
3543 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3544 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3545 if (ESR != ESR_Succeeded)
3546 return ESR;
3547 }
3548 return ESR_Succeeded;
3549 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003550
3551 case Stmt::WhileStmtClass: {
3552 const WhileStmt *WS = cast<WhileStmt>(S);
3553 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003554 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003555 bool Continue;
3556 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3557 Continue))
3558 return ESR_Failed;
3559 if (!Continue)
3560 break;
3561
3562 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3563 if (ESR != ESR_Continue)
3564 return ESR;
3565 }
3566 return ESR_Succeeded;
3567 }
3568
3569 case Stmt::DoStmtClass: {
3570 const DoStmt *DS = cast<DoStmt>(S);
3571 bool Continue;
3572 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003573 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003574 if (ESR != ESR_Continue)
3575 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003576 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003577
Richard Smith08d6a2c2013-07-24 07:11:57 +00003578 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003579 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3580 return ESR_Failed;
3581 } while (Continue);
3582 return ESR_Succeeded;
3583 }
3584
3585 case Stmt::ForStmtClass: {
3586 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003587 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003588 if (FS->getInit()) {
3589 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3590 if (ESR != ESR_Succeeded)
3591 return ESR;
3592 }
3593 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003594 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003595 bool Continue = true;
3596 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3597 FS->getCond(), Continue))
3598 return ESR_Failed;
3599 if (!Continue)
3600 break;
3601
3602 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3603 if (ESR != ESR_Continue)
3604 return ESR;
3605
Richard Smith08d6a2c2013-07-24 07:11:57 +00003606 if (FS->getInc()) {
3607 FullExpressionRAII IncScope(Info);
3608 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3609 return ESR_Failed;
3610 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003611 }
3612 return ESR_Succeeded;
3613 }
3614
Richard Smith896e0d72013-05-06 06:51:17 +00003615 case Stmt::CXXForRangeStmtClass: {
3616 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003617 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003618
3619 // Initialize the __range variable.
3620 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3621 if (ESR != ESR_Succeeded)
3622 return ESR;
3623
3624 // Create the __begin and __end iterators.
3625 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3626 if (ESR != ESR_Succeeded)
3627 return ESR;
3628
3629 while (true) {
3630 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003631 {
3632 bool Continue = true;
3633 FullExpressionRAII CondExpr(Info);
3634 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3635 return ESR_Failed;
3636 if (!Continue)
3637 break;
3638 }
Richard Smith896e0d72013-05-06 06:51:17 +00003639
3640 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003641 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003642 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3643 if (ESR != ESR_Succeeded)
3644 return ESR;
3645
3646 // Loop body.
3647 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3648 if (ESR != ESR_Continue)
3649 return ESR;
3650
3651 // Increment: ++__begin
3652 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3653 return ESR_Failed;
3654 }
3655
3656 return ESR_Succeeded;
3657 }
3658
Richard Smith496ddcf2013-05-12 17:32:42 +00003659 case Stmt::SwitchStmtClass:
3660 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3661
Richard Smith4e18ca52013-05-06 05:56:11 +00003662 case Stmt::ContinueStmtClass:
3663 return ESR_Continue;
3664
3665 case Stmt::BreakStmtClass:
3666 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003667
3668 case Stmt::LabelStmtClass:
3669 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3670
3671 case Stmt::AttributedStmtClass:
3672 // As a general principle, C++11 attributes can be ignored without
3673 // any semantic impact.
3674 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3675 Case);
3676
3677 case Stmt::CaseStmtClass:
3678 case Stmt::DefaultStmtClass:
3679 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003680 }
3681}
3682
Richard Smithcc36f692011-12-22 02:22:31 +00003683/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3684/// default constructor. If so, we'll fold it whether or not it's marked as
3685/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3686/// so we need special handling.
3687static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003688 const CXXConstructorDecl *CD,
3689 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003690 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3691 return false;
3692
Richard Smith66e05fe2012-01-18 05:21:49 +00003693 // Value-initialization does not call a trivial default constructor, so such a
3694 // call is a core constant expression whether or not the constructor is
3695 // constexpr.
3696 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003697 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003698 // FIXME: If DiagDecl is an implicitly-declared special member function,
3699 // we should be much more explicit about why it's not constexpr.
3700 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3701 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3702 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003703 } else {
3704 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3705 }
3706 }
3707 return true;
3708}
3709
Richard Smith357362d2011-12-13 06:39:58 +00003710/// CheckConstexprFunction - Check that a function can be called in a constant
3711/// expression.
3712static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3713 const FunctionDecl *Declaration,
3714 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003715 // Potential constant expressions can contain calls to declared, but not yet
3716 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003717 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003718 Declaration->isConstexpr())
3719 return false;
3720
Richard Smith0838f3a2013-05-14 05:18:44 +00003721 // Bail out with no diagnostic if the function declaration itself is invalid.
3722 // We will have produced a relevant diagnostic while parsing it.
3723 if (Declaration->isInvalidDecl())
3724 return false;
3725
Richard Smith357362d2011-12-13 06:39:58 +00003726 // Can we evaluate this function call?
3727 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3728 return true;
3729
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003730 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003731 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003732 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3733 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003734 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3735 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3736 << DiagDecl;
3737 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3738 } else {
3739 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3740 }
3741 return false;
3742}
3743
Richard Smithbe6dd812014-11-19 21:27:17 +00003744/// Determine if a class has any fields that might need to be copied by a
3745/// trivial copy or move operation.
3746static bool hasFields(const CXXRecordDecl *RD) {
3747 if (!RD || RD->isEmpty())
3748 return false;
3749 for (auto *FD : RD->fields()) {
3750 if (FD->isUnnamedBitfield())
3751 continue;
3752 return true;
3753 }
3754 for (auto &Base : RD->bases())
3755 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3756 return true;
3757 return false;
3758}
3759
Richard Smithd62306a2011-11-10 06:34:14 +00003760namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003761typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003762}
3763
3764/// EvaluateArgs - Evaluate the arguments to a function call.
3765static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3766 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003767 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003768 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003769 I != E; ++I) {
3770 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3771 // If we're checking for a potential constant expression, evaluate all
3772 // initializers even if some of them fail.
3773 if (!Info.keepEvaluatingAfterFailure())
3774 return false;
3775 Success = false;
3776 }
3777 }
3778 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003779}
3780
Richard Smith254a73d2011-10-28 22:34:42 +00003781/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003782static bool HandleFunctionCall(SourceLocation CallLoc,
3783 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003784 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003785 EvalInfo &Info, APValue &Result,
3786 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003787 ArgVector ArgValues(Args.size());
3788 if (!EvaluateArgs(Args, ArgValues, Info))
3789 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003790
Richard Smith253c2a32012-01-27 01:14:48 +00003791 if (!Info.CheckCallLimit(CallLoc))
3792 return false;
3793
3794 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003795
3796 // For a trivial copy or move assignment, perform an APValue copy. This is
3797 // essential for unions, where the operations performed by the assignment
3798 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003799 //
3800 // Skip this for non-union classes with no fields; in that case, the defaulted
3801 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003802 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003803 if (MD && MD->isDefaulted() &&
3804 (MD->getParent()->isUnion() ||
3805 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003806 assert(This &&
3807 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3808 LValue RHS;
3809 RHS.setFrom(Info.Ctx, ArgValues[0]);
3810 APValue RHSValue;
3811 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3812 RHS, RHSValue))
3813 return false;
3814 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3815 RHSValue))
3816 return false;
3817 This->moveInto(Result);
3818 return true;
3819 }
3820
Richard Smith52a980a2015-08-28 02:43:42 +00003821 StmtResult Ret = {Result, ResultSlot};
3822 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003823 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003824 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003825 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003826 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003827 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003828 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003829}
3830
Richard Smithd62306a2011-11-10 06:34:14 +00003831/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003832static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003833 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003834 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003835 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003836 ArgVector ArgValues(Args.size());
3837 if (!EvaluateArgs(Args, ArgValues, Info))
3838 return false;
3839
Richard Smith253c2a32012-01-27 01:14:48 +00003840 if (!Info.CheckCallLimit(CallLoc))
3841 return false;
3842
Richard Smith3607ffe2012-02-13 03:54:03 +00003843 const CXXRecordDecl *RD = Definition->getParent();
3844 if (RD->getNumVBases()) {
3845 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3846 return false;
3847 }
3848
Richard Smith253c2a32012-01-27 01:14:48 +00003849 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003850
Richard Smith52a980a2015-08-28 02:43:42 +00003851 // FIXME: Creating an APValue just to hold a nonexistent return value is
3852 // wasteful.
3853 APValue RetVal;
3854 StmtResult Ret = {RetVal, nullptr};
3855
Richard Smithd62306a2011-11-10 06:34:14 +00003856 // If it's a delegating constructor, just delegate.
3857 if (Definition->isDelegatingConstructor()) {
3858 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003859 {
3860 FullExpressionRAII InitScope(Info);
3861 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3862 return false;
3863 }
Richard Smith52a980a2015-08-28 02:43:42 +00003864 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003865 }
3866
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003867 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003868 // essential for unions (or classes with anonymous union members), where the
3869 // operations performed by the constructor cannot be represented by
3870 // ctor-initializers.
3871 //
3872 // Skip this for empty non-union classes; we should not perform an
3873 // lvalue-to-rvalue conversion on them because their copy constructor does not
3874 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003875 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003876 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003877 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003878 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003879 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003880 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003881 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003882 }
3883
3884 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003885 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003886 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003887 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003888
John McCalld7bca762012-05-01 00:38:49 +00003889 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003890 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3891
Richard Smith08d6a2c2013-07-24 07:11:57 +00003892 // A scope for temporaries lifetime-extended by reference members.
3893 BlockScopeRAII LifetimeExtendedScope(Info);
3894
Richard Smith253c2a32012-01-27 01:14:48 +00003895 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003896 unsigned BasesSeen = 0;
3897#ifndef NDEBUG
3898 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3899#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003900 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003901 LValue Subobject = This;
3902 APValue *Value = &Result;
3903
3904 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003905 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003906 if (I->isBaseInitializer()) {
3907 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003908#ifndef NDEBUG
3909 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003910 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003911 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3912 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3913 "base class initializers not in expected order");
3914 ++BaseIt;
3915#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003916 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003917 BaseType->getAsCXXRecordDecl(), &Layout))
3918 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003919 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003920 } else if ((FD = I->getMember())) {
3921 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003922 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003923 if (RD->isUnion()) {
3924 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003925 Value = &Result.getUnionValue();
3926 } else {
3927 Value = &Result.getStructField(FD->getFieldIndex());
3928 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003929 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003930 // Walk the indirect field decl's chain to find the object to initialize,
3931 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003932 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003933 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003934 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3935 // Switch the union field if it differs. This happens if we had
3936 // preceding zero-initialization, and we're now initializing a union
3937 // subobject other than the first.
3938 // FIXME: In this case, the values of the other subobjects are
3939 // specified, since zero-initialization sets all padding bits to zero.
3940 if (Value->isUninit() ||
3941 (Value->isUnion() && Value->getUnionField() != FD)) {
3942 if (CD->isUnion())
3943 *Value = APValue(FD);
3944 else
3945 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003946 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003947 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003948 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003949 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003950 if (CD->isUnion())
3951 Value = &Value->getUnionValue();
3952 else
3953 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003954 }
Richard Smithd62306a2011-11-10 06:34:14 +00003955 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003956 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003957 }
Richard Smith253c2a32012-01-27 01:14:48 +00003958
Richard Smith08d6a2c2013-07-24 07:11:57 +00003959 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003960 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3961 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003962 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003963 // If we're checking for a potential constant expression, evaluate all
3964 // initializers even if some of them fail.
3965 if (!Info.keepEvaluatingAfterFailure())
3966 return false;
3967 Success = false;
3968 }
Richard Smithd62306a2011-11-10 06:34:14 +00003969 }
3970
Richard Smithd9f663b2013-04-22 15:31:51 +00003971 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00003972 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003973}
3974
Eli Friedman9a156e52008-11-12 09:44:48 +00003975//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003976// Generic Evaluation
3977//===----------------------------------------------------------------------===//
3978namespace {
3979
Aaron Ballman68af21c2014-01-03 19:26:43 +00003980template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003981class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003982 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003983private:
Richard Smith52a980a2015-08-28 02:43:42 +00003984 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003985 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003986 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003987 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003988 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003989 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003990 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003991
Richard Smith17100ba2012-02-16 02:46:34 +00003992 // Check whether a conditional operator with a non-constant condition is a
3993 // potential constant expression. If neither arm is a potential constant
3994 // expression, then the conditional operator is not either.
3995 template<typename ConditionalOperator>
3996 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003997 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003998
3999 // Speculatively evaluate both arms.
4000 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004001 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004002 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4003
4004 StmtVisitorTy::Visit(E->getFalseExpr());
4005 if (Diag.empty())
4006 return;
4007
4008 Diag.clear();
4009 StmtVisitorTy::Visit(E->getTrueExpr());
4010 if (Diag.empty())
4011 return;
4012 }
4013
4014 Error(E, diag::note_constexpr_conditional_never_const);
4015 }
4016
4017
4018 template<typename ConditionalOperator>
4019 bool HandleConditionalOperator(const ConditionalOperator *E) {
4020 bool BoolResult;
4021 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004022 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00004023 CheckPotentialConstantConditional(E);
4024 return false;
4025 }
4026
4027 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4028 return StmtVisitorTy::Visit(EvalExpr);
4029 }
4030
Peter Collingbournee9200682011-05-13 03:29:01 +00004031protected:
4032 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004033 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004034 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4035
Richard Smith92b1ce02011-12-12 09:28:41 +00004036 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004037 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004038 }
4039
Aaron Ballman68af21c2014-01-03 19:26:43 +00004040 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004041
4042public:
4043 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4044
4045 EvalInfo &getEvalInfo() { return Info; }
4046
Richard Smithf57d8cb2011-12-09 22:58:01 +00004047 /// Report an evaluation error. This should only be called when an error is
4048 /// first discovered. When propagating an error, just return false.
4049 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004050 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004051 return false;
4052 }
4053 bool Error(const Expr *E) {
4054 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4055 }
4056
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004058 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004059 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004060 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004061 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004062 }
4063
Aaron Ballman68af21c2014-01-03 19:26:43 +00004064 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004065 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004066 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004067 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004068 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004069 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004070 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004071 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004072 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004073 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004074 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004075 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004076 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004077 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004078 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004079 // The initializer may not have been parsed yet, or might be erroneous.
4080 if (!E->getExpr())
4081 return Error(E);
4082 return StmtVisitorTy::Visit(E->getExpr());
4083 }
Richard Smith5894a912011-12-19 22:12:41 +00004084 // We cannot create any objects for which cleanups are required, so there is
4085 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004086 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004087 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004088
Aaron Ballman68af21c2014-01-03 19:26:43 +00004089 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004090 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4091 return static_cast<Derived*>(this)->VisitCastExpr(E);
4092 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004093 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004094 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4095 return static_cast<Derived*>(this)->VisitCastExpr(E);
4096 }
4097
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004099 switch (E->getOpcode()) {
4100 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004101 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004102
4103 case BO_Comma:
4104 VisitIgnoredValue(E->getLHS());
4105 return StmtVisitorTy::Visit(E->getRHS());
4106
4107 case BO_PtrMemD:
4108 case BO_PtrMemI: {
4109 LValue Obj;
4110 if (!HandleMemberPointerAccess(Info, E, Obj))
4111 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004112 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004113 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004114 return false;
4115 return DerivedSuccess(Result, E);
4116 }
4117 }
4118 }
4119
Aaron Ballman68af21c2014-01-03 19:26:43 +00004120 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004121 // Evaluate and cache the common expression. We treat it as a temporary,
4122 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004123 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004124 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004125 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004126
Richard Smith17100ba2012-02-16 02:46:34 +00004127 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004128 }
4129
Aaron Ballman68af21c2014-01-03 19:26:43 +00004130 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004131 bool IsBcpCall = false;
4132 // If the condition (ignoring parens) is a __builtin_constant_p call,
4133 // the result is a constant expression if it can be folded without
4134 // side-effects. This is an important GNU extension. See GCC PR38377
4135 // for discussion.
4136 if (const CallExpr *CallCE =
4137 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004138 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004139 IsBcpCall = true;
4140
4141 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4142 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004143 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004144 return false;
4145
Richard Smith6d4c6582013-11-05 22:18:15 +00004146 FoldConstant Fold(Info, IsBcpCall);
4147 if (!HandleConditionalOperator(E)) {
4148 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004149 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004150 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004151
4152 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004153 }
4154
Aaron Ballman68af21c2014-01-03 19:26:43 +00004155 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004156 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4157 return DerivedSuccess(*Value, E);
4158
4159 const Expr *Source = E->getSourceExpr();
4160 if (!Source)
4161 return Error(E);
4162 if (Source == E) { // sanity checking.
4163 assert(0 && "OpaqueValueExpr recursively refers to itself");
4164 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004165 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004166 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004167 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004168
Aaron Ballman68af21c2014-01-03 19:26:43 +00004169 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004170 APValue Result;
4171 if (!handleCallExpr(E, Result, nullptr))
4172 return false;
4173 return DerivedSuccess(Result, E);
4174 }
4175
4176 bool handleCallExpr(const CallExpr *E, APValue &Result,
4177 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004178 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004179 QualType CalleeType = Callee->getType();
4180
Craig Topper36250ad2014-05-12 05:36:57 +00004181 const FunctionDecl *FD = nullptr;
4182 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004183 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004184 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004185
Richard Smithe97cbd72011-11-11 04:05:33 +00004186 // Extract function decl and 'this' pointer from the callee.
4187 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004188 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004189 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4190 // Explicit bound member calls, such as x.f() or p->g();
4191 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004192 return false;
4193 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004194 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004195 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004196 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4197 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004198 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4199 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004200 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004201 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004202 return Error(Callee);
4203
4204 FD = dyn_cast<FunctionDecl>(Member);
4205 if (!FD)
4206 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004207 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004208 LValue Call;
4209 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004210 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004211
Richard Smitha8105bc2012-01-06 16:39:00 +00004212 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004213 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004214 FD = dyn_cast_or_null<FunctionDecl>(
4215 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004216 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004217 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004218
4219 // Overloaded operator calls to member functions are represented as normal
4220 // calls with '*this' as the first argument.
4221 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4222 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004223 // FIXME: When selecting an implicit conversion for an overloaded
4224 // operator delete, we sometimes try to evaluate calls to conversion
4225 // operators without a 'this' parameter!
4226 if (Args.empty())
4227 return Error(E);
4228
Richard Smithe97cbd72011-11-11 04:05:33 +00004229 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4230 return false;
4231 This = &ThisVal;
4232 Args = Args.slice(1);
4233 }
4234
4235 // Don't call function pointers which have been cast to some other type.
4236 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004237 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004238 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004239 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004240
Richard Smith47b34932012-02-01 02:39:43 +00004241 if (This && !This->checkSubobject(Info, E, CSK_This))
4242 return false;
4243
Richard Smith3607ffe2012-02-13 03:54:03 +00004244 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4245 // calls to such functions in constant expressions.
4246 if (This && !HasQualifier &&
4247 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4248 return Error(E, diag::note_constexpr_virtual_call);
4249
Craig Topper36250ad2014-05-12 05:36:57 +00004250 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004251 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004252
Richard Smith357362d2011-12-13 06:39:58 +00004253 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004254 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4255 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 return false;
4257
Richard Smith52a980a2015-08-28 02:43:42 +00004258 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004259 }
4260
Aaron Ballman68af21c2014-01-03 19:26:43 +00004261 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004262 return StmtVisitorTy::Visit(E->getInitializer());
4263 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004264 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004265 if (E->getNumInits() == 0)
4266 return DerivedZeroInitialization(E);
4267 if (E->getNumInits() == 1)
4268 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004270 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004271 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004272 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004273 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004274 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004275 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004276 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004277 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004278 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004279 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004280
Richard Smithd62306a2011-11-10 06:34:14 +00004281 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004283 assert(!E->isArrow() && "missing call to bound member function?");
4284
Richard Smith2e312c82012-03-03 22:46:17 +00004285 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004286 if (!Evaluate(Val, Info, E->getBase()))
4287 return false;
4288
4289 QualType BaseTy = E->getBase()->getType();
4290
4291 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004292 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004293 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004294 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004295 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4296
Richard Smith3229b742013-05-05 21:17:10 +00004297 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004298 SubobjectDesignator Designator(BaseTy);
4299 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004300
Richard Smith3229b742013-05-05 21:17:10 +00004301 APValue Result;
4302 return extractSubobject(Info, E, Obj, Designator, Result) &&
4303 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004304 }
4305
Aaron Ballman68af21c2014-01-03 19:26:43 +00004306 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004307 switch (E->getCastKind()) {
4308 default:
4309 break;
4310
Richard Smitha23ab512013-05-23 00:30:41 +00004311 case CK_AtomicToNonAtomic: {
4312 APValue AtomicVal;
4313 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4314 return false;
4315 return DerivedSuccess(AtomicVal, E);
4316 }
4317
Richard Smith11562c52011-10-28 17:51:58 +00004318 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004319 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004320 return StmtVisitorTy::Visit(E->getSubExpr());
4321
4322 case CK_LValueToRValue: {
4323 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004324 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4325 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004326 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004327 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004328 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004329 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004330 return false;
4331 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004332 }
4333 }
4334
Richard Smithf57d8cb2011-12-09 22:58:01 +00004335 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004336 }
4337
Aaron Ballman68af21c2014-01-03 19:26:43 +00004338 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004339 return VisitUnaryPostIncDec(UO);
4340 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004341 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004342 return VisitUnaryPostIncDec(UO);
4343 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004344 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004345 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004346 return Error(UO);
4347
4348 LValue LVal;
4349 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4350 return false;
4351 APValue RVal;
4352 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4353 UO->isIncrementOp(), &RVal))
4354 return false;
4355 return DerivedSuccess(RVal, UO);
4356 }
4357
Aaron Ballman68af21c2014-01-03 19:26:43 +00004358 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004359 // We will have checked the full-expressions inside the statement expression
4360 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004361 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004362 return Error(E);
4363
Richard Smith08d6a2c2013-07-24 07:11:57 +00004364 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004365 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004366 if (CS->body_empty())
4367 return true;
4368
Richard Smith51f03172013-06-20 03:00:05 +00004369 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4370 BE = CS->body_end();
4371 /**/; ++BI) {
4372 if (BI + 1 == BE) {
4373 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4374 if (!FinalExpr) {
4375 Info.Diag((*BI)->getLocStart(),
4376 diag::note_constexpr_stmt_expr_unsupported);
4377 return false;
4378 }
4379 return this->Visit(FinalExpr);
4380 }
4381
4382 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004383 StmtResult Result = { ReturnValue, nullptr };
4384 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004385 if (ESR != ESR_Succeeded) {
4386 // FIXME: If the statement-expression terminated due to 'return',
4387 // 'break', or 'continue', it would be nice to propagate that to
4388 // the outer statement evaluation rather than bailing out.
4389 if (ESR != ESR_Failed)
4390 Info.Diag((*BI)->getLocStart(),
4391 diag::note_constexpr_stmt_expr_unsupported);
4392 return false;
4393 }
4394 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004395
4396 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004397 }
4398
Richard Smith4a678122011-10-24 18:44:57 +00004399 /// Visit a value which is evaluated, but whose value is ignored.
4400 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004401 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004402 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004403};
4404
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004405}
Peter Collingbournee9200682011-05-13 03:29:01 +00004406
4407//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004408// Common base class for lvalue and temporary evaluation.
4409//===----------------------------------------------------------------------===//
4410namespace {
4411template<class Derived>
4412class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004413 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004414protected:
4415 LValue &Result;
4416 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004417 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004418
4419 bool Success(APValue::LValueBase B) {
4420 Result.set(B);
4421 return true;
4422 }
4423
4424public:
4425 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4426 ExprEvaluatorBaseTy(Info), Result(Result) {}
4427
Richard Smith2e312c82012-03-03 22:46:17 +00004428 bool Success(const APValue &V, const Expr *E) {
4429 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004430 return true;
4431 }
Richard Smith027bf112011-11-17 22:56:20 +00004432
Richard Smith027bf112011-11-17 22:56:20 +00004433 bool VisitMemberExpr(const MemberExpr *E) {
4434 // Handle non-static data members.
4435 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004436 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004437 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004438 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004439 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004440 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004441 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004442 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004443 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004444 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004445 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004446 BaseTy = E->getBase()->getType();
4447 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004448 if (!EvalOK) {
4449 if (!this->Info.allowInvalidBaseExpr())
4450 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004451 Result.setInvalid(E);
4452 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004453 }
Richard Smith027bf112011-11-17 22:56:20 +00004454
Richard Smith1b78b3d2012-01-25 22:15:11 +00004455 const ValueDecl *MD = E->getMemberDecl();
4456 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4457 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4458 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4459 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004460 if (!HandleLValueMember(this->Info, E, Result, FD))
4461 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004462 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004463 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4464 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004465 } else
4466 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004467
Richard Smith1b78b3d2012-01-25 22:15:11 +00004468 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004469 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004470 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004471 RefValue))
4472 return false;
4473 return Success(RefValue, E);
4474 }
4475 return true;
4476 }
4477
4478 bool VisitBinaryOperator(const BinaryOperator *E) {
4479 switch (E->getOpcode()) {
4480 default:
4481 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4482
4483 case BO_PtrMemD:
4484 case BO_PtrMemI:
4485 return HandleMemberPointerAccess(this->Info, E, Result);
4486 }
4487 }
4488
4489 bool VisitCastExpr(const CastExpr *E) {
4490 switch (E->getCastKind()) {
4491 default:
4492 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4493
4494 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004495 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004496 if (!this->Visit(E->getSubExpr()))
4497 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004498
4499 // Now figure out the necessary offset to add to the base LV to get from
4500 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004501 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4502 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004503 }
4504 }
4505};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004506}
Richard Smith027bf112011-11-17 22:56:20 +00004507
4508//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004509// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004510//
4511// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4512// function designators (in C), decl references to void objects (in C), and
4513// temporaries (if building with -Wno-address-of-temporary).
4514//
4515// LValue evaluation produces values comprising a base expression of one of the
4516// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004517// - Declarations
4518// * VarDecl
4519// * FunctionDecl
4520// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004521// * CompoundLiteralExpr in C
4522// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004523// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004524// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004525// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004526// * ObjCEncodeExpr
4527// * AddrLabelExpr
4528// * BlockExpr
4529// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004530// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004531// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004532// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004533// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4534// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004535// * A MaterializeTemporaryExpr that has static storage duration, with no
4536// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004537// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004538//===----------------------------------------------------------------------===//
4539namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004540class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004541 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004542public:
Richard Smith027bf112011-11-17 22:56:20 +00004543 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4544 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004545
Richard Smith11562c52011-10-28 17:51:58 +00004546 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004547 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004548
Peter Collingbournee9200682011-05-13 03:29:01 +00004549 bool VisitDeclRefExpr(const DeclRefExpr *E);
4550 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004551 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004552 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4553 bool VisitMemberExpr(const MemberExpr *E);
4554 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4555 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004556 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004557 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004558 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4559 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004560 bool VisitUnaryReal(const UnaryOperator *E);
4561 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004562 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4563 return VisitUnaryPreIncDec(UO);
4564 }
4565 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4566 return VisitUnaryPreIncDec(UO);
4567 }
Richard Smith3229b742013-05-05 21:17:10 +00004568 bool VisitBinAssign(const BinaryOperator *BO);
4569 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004570
Peter Collingbournee9200682011-05-13 03:29:01 +00004571 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004572 switch (E->getCastKind()) {
4573 default:
Richard Smith027bf112011-11-17 22:56:20 +00004574 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004575
Eli Friedmance3e02a2011-10-11 00:13:24 +00004576 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004577 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004578 if (!Visit(E->getSubExpr()))
4579 return false;
4580 Result.Designator.setInvalid();
4581 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004582
Richard Smith027bf112011-11-17 22:56:20 +00004583 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004584 if (!Visit(E->getSubExpr()))
4585 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004586 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004587 }
4588 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004589};
4590} // end anonymous namespace
4591
Richard Smith11562c52011-10-28 17:51:58 +00004592/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004593/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004594/// * function designators in C, and
4595/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004596/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004597static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4598 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004599 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004600 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004601}
4602
Peter Collingbournee9200682011-05-13 03:29:01 +00004603bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004604 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004605 return Success(FD);
4606 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004607 return VisitVarDecl(E, VD);
4608 return Error(E);
4609}
Richard Smith733237d2011-10-24 23:14:33 +00004610
Richard Smith11562c52011-10-28 17:51:58 +00004611bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004612 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004613 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4614 Frame = Info.CurrentCall;
4615
Richard Smithfec09922011-11-01 16:57:24 +00004616 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004617 if (Frame) {
4618 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004619 return true;
4620 }
Richard Smithce40ad62011-11-12 22:28:03 +00004621 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004622 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004623
Richard Smith3229b742013-05-05 21:17:10 +00004624 APValue *V;
4625 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004626 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004627 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004628 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004629 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4630 return false;
4631 }
Richard Smith3229b742013-05-05 21:17:10 +00004632 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004633}
4634
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004635bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4636 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004637 // Walk through the expression to find the materialized temporary itself.
4638 SmallVector<const Expr *, 2> CommaLHSs;
4639 SmallVector<SubobjectAdjustment, 2> Adjustments;
4640 const Expr *Inner = E->GetTemporaryExpr()->
4641 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004642
Richard Smith84401042013-06-03 05:03:02 +00004643 // If we passed any comma operators, evaluate their LHSs.
4644 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4645 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4646 return false;
4647
Richard Smithe6c01442013-06-05 00:46:14 +00004648 // A materialized temporary with static storage duration can appear within the
4649 // result of a constant expression evaluation, so we need to preserve its
4650 // value for use outside this evaluation.
4651 APValue *Value;
4652 if (E->getStorageDuration() == SD_Static) {
4653 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004654 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004655 Result.set(E);
4656 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004657 Value = &Info.CurrentCall->
4658 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004659 Result.set(E, Info.CurrentCall->Index);
4660 }
4661
Richard Smithea4ad5d2013-06-06 08:19:16 +00004662 QualType Type = Inner->getType();
4663
Richard Smith84401042013-06-03 05:03:02 +00004664 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004665 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4666 (E->getStorageDuration() == SD_Static &&
4667 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4668 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004669 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004670 }
Richard Smith84401042013-06-03 05:03:02 +00004671
4672 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004673 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4674 --I;
4675 switch (Adjustments[I].Kind) {
4676 case SubobjectAdjustment::DerivedToBaseAdjustment:
4677 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4678 Type, Result))
4679 return false;
4680 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4681 break;
4682
4683 case SubobjectAdjustment::FieldAdjustment:
4684 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4685 return false;
4686 Type = Adjustments[I].Field->getType();
4687 break;
4688
4689 case SubobjectAdjustment::MemberPointerAdjustment:
4690 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4691 Adjustments[I].Ptr.RHS))
4692 return false;
4693 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4694 break;
4695 }
4696 }
4697
4698 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004699}
4700
Peter Collingbournee9200682011-05-13 03:29:01 +00004701bool
4702LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004703 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4704 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4705 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004706 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004707}
4708
Richard Smith6e525142011-12-27 12:18:28 +00004709bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004710 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004711 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004712
4713 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4714 << E->getExprOperand()->getType()
4715 << E->getExprOperand()->getSourceRange();
4716 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004717}
4718
Francois Pichet0066db92012-04-16 04:08:35 +00004719bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4720 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004721}
Francois Pichet0066db92012-04-16 04:08:35 +00004722
Peter Collingbournee9200682011-05-13 03:29:01 +00004723bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004724 // Handle static data members.
4725 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4726 VisitIgnoredValue(E->getBase());
4727 return VisitVarDecl(E, VD);
4728 }
4729
Richard Smith254a73d2011-10-28 22:34:42 +00004730 // Handle static member functions.
4731 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4732 if (MD->isStatic()) {
4733 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004734 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004735 }
4736 }
4737
Richard Smithd62306a2011-11-10 06:34:14 +00004738 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004739 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004740}
4741
Peter Collingbournee9200682011-05-13 03:29:01 +00004742bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004743 // FIXME: Deal with vectors as array subscript bases.
4744 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004746
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004747 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004748 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004749
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004750 APSInt Index;
4751 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004752 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004753
Richard Smith861b5b52013-05-07 23:34:45 +00004754 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4755 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004756}
Eli Friedman9a156e52008-11-12 09:44:48 +00004757
Peter Collingbournee9200682011-05-13 03:29:01 +00004758bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004759 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004760}
4761
Richard Smith66c96992012-02-18 22:04:06 +00004762bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4763 if (!Visit(E->getSubExpr()))
4764 return false;
4765 // __real is a no-op on scalar lvalues.
4766 if (E->getSubExpr()->getType()->isAnyComplexType())
4767 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4768 return true;
4769}
4770
4771bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4772 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4773 "lvalue __imag__ on scalar?");
4774 if (!Visit(E->getSubExpr()))
4775 return false;
4776 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4777 return true;
4778}
4779
Richard Smith243ef902013-05-05 23:31:59 +00004780bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004781 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004782 return Error(UO);
4783
4784 if (!this->Visit(UO->getSubExpr()))
4785 return false;
4786
Richard Smith243ef902013-05-05 23:31:59 +00004787 return handleIncDec(
4788 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004789 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004790}
4791
4792bool LValueExprEvaluator::VisitCompoundAssignOperator(
4793 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004794 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004795 return Error(CAO);
4796
Richard Smith3229b742013-05-05 21:17:10 +00004797 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004798
4799 // The overall lvalue result is the result of evaluating the LHS.
4800 if (!this->Visit(CAO->getLHS())) {
4801 if (Info.keepEvaluatingAfterFailure())
4802 Evaluate(RHS, this->Info, CAO->getRHS());
4803 return false;
4804 }
4805
Richard Smith3229b742013-05-05 21:17:10 +00004806 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4807 return false;
4808
Richard Smith43e77732013-05-07 04:50:00 +00004809 return handleCompoundAssignment(
4810 this->Info, CAO,
4811 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4812 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004813}
4814
4815bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004816 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004817 return Error(E);
4818
Richard Smith3229b742013-05-05 21:17:10 +00004819 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004820
4821 if (!this->Visit(E->getLHS())) {
4822 if (Info.keepEvaluatingAfterFailure())
4823 Evaluate(NewVal, this->Info, E->getRHS());
4824 return false;
4825 }
4826
Richard Smith3229b742013-05-05 21:17:10 +00004827 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4828 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004829
4830 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004831 NewVal);
4832}
4833
Eli Friedman9a156e52008-11-12 09:44:48 +00004834//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004835// Pointer Evaluation
4836//===----------------------------------------------------------------------===//
4837
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004838namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004839class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004840 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004841 LValue &Result;
4842
Peter Collingbournee9200682011-05-13 03:29:01 +00004843 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004844 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004845 return true;
4846 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004847public:
Mike Stump11289f42009-09-09 15:08:12 +00004848
John McCall45d55e42010-05-07 21:00:08 +00004849 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004850 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004851
Richard Smith2e312c82012-03-03 22:46:17 +00004852 bool Success(const APValue &V, const Expr *E) {
4853 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004854 return true;
4855 }
Richard Smithfddd3842011-12-30 21:15:51 +00004856 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004857 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004858 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004859
John McCall45d55e42010-05-07 21:00:08 +00004860 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004861 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004862 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004863 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004864 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004865 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004866 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004867 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004868 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004869 bool VisitCallExpr(const CallExpr *E);
4870 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004871 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004872 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004873 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004874 }
Richard Smithd62306a2011-11-10 06:34:14 +00004875 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004876 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004877 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004878 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004879 if (!Info.CurrentCall->This) {
4880 if (Info.getLangOpts().CPlusPlus11)
4881 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4882 else
4883 Info.Diag(E);
4884 return false;
4885 }
Richard Smithd62306a2011-11-10 06:34:14 +00004886 Result = *Info.CurrentCall->This;
4887 return true;
4888 }
John McCallc07a0c72011-02-17 10:25:35 +00004889
Eli Friedman449fe542009-03-23 04:56:01 +00004890 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004891};
Chris Lattner05706e882008-07-11 18:11:29 +00004892} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004893
John McCall45d55e42010-05-07 21:00:08 +00004894static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004895 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004896 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004897}
4898
John McCall45d55e42010-05-07 21:00:08 +00004899bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004900 if (E->getOpcode() != BO_Add &&
4901 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004902 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004903
Chris Lattner05706e882008-07-11 18:11:29 +00004904 const Expr *PExp = E->getLHS();
4905 const Expr *IExp = E->getRHS();
4906 if (IExp->getType()->isPointerType())
4907 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004908
Richard Smith253c2a32012-01-27 01:14:48 +00004909 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4910 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004911 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004912
John McCall45d55e42010-05-07 21:00:08 +00004913 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004914 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004915 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004916
4917 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004918 if (E->getOpcode() == BO_Sub)
4919 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004920
Ted Kremenek28831752012-08-23 20:46:57 +00004921 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004922 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4923 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004924}
Eli Friedman9a156e52008-11-12 09:44:48 +00004925
John McCall45d55e42010-05-07 21:00:08 +00004926bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4927 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004928}
Mike Stump11289f42009-09-09 15:08:12 +00004929
Peter Collingbournee9200682011-05-13 03:29:01 +00004930bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4931 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004932
Eli Friedman847a2bc2009-12-27 05:43:15 +00004933 switch (E->getCastKind()) {
4934 default:
4935 break;
4936
John McCalle3027922010-08-25 11:45:40 +00004937 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004938 case CK_CPointerToObjCPointerCast:
4939 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004940 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004941 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004942 if (!Visit(SubExpr))
4943 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004944 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4945 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4946 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004947 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004948 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004949 if (SubExpr->getType()->isVoidPointerType())
4950 CCEDiag(E, diag::note_constexpr_invalid_cast)
4951 << 3 << SubExpr->getType();
4952 else
4953 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4954 }
Richard Smith96e0c102011-11-04 02:25:55 +00004955 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004956
Anders Carlsson18275092010-10-31 20:41:46 +00004957 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004958 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004959 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004960 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004961 if (!Result.Base && Result.Offset.isZero())
4962 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004963
Richard Smithd62306a2011-11-10 06:34:14 +00004964 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004965 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004966 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4967 castAs<PointerType>()->getPointeeType(),
4968 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004969
Richard Smith027bf112011-11-17 22:56:20 +00004970 case CK_BaseToDerived:
4971 if (!Visit(E->getSubExpr()))
4972 return false;
4973 if (!Result.Base && Result.Offset.isZero())
4974 return true;
4975 return HandleBaseToDerivedCast(Info, E, Result);
4976
Richard Smith0b0a0b62011-10-29 20:57:55 +00004977 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004978 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004979 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004980
John McCalle3027922010-08-25 11:45:40 +00004981 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004982 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4983
Richard Smith2e312c82012-03-03 22:46:17 +00004984 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004985 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004986 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004987
John McCall45d55e42010-05-07 21:00:08 +00004988 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004989 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4990 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004991 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004992 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004993 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004994 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004995 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004996 return true;
4997 } else {
4998 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004999 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005000 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005001 }
5002 }
John McCalle3027922010-08-25 11:45:40 +00005003 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005004 if (SubExpr->isGLValue()) {
5005 if (!EvaluateLValue(SubExpr, Result, Info))
5006 return false;
5007 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005008 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005009 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005010 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005011 return false;
5012 }
Richard Smith96e0c102011-11-04 02:25:55 +00005013 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005014 if (const ConstantArrayType *CAT
5015 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5016 Result.addArray(Info, E, CAT);
5017 else
5018 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005019 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005020
John McCalle3027922010-08-25 11:45:40 +00005021 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005022 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005023 }
5024
Richard Smith11562c52011-10-28 17:51:58 +00005025 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005026}
Chris Lattner05706e882008-07-11 18:11:29 +00005027
Hal Finkel0dd05d42014-10-03 17:18:37 +00005028static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5029 // C++ [expr.alignof]p3:
5030 // When alignof is applied to a reference type, the result is the
5031 // alignment of the referenced type.
5032 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5033 T = Ref->getPointeeType();
5034
5035 // __alignof is defined to return the preferred alignment.
5036 return Info.Ctx.toCharUnitsFromBits(
5037 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5038}
5039
5040static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5041 E = E->IgnoreParens();
5042
5043 // The kinds of expressions that we have special-case logic here for
5044 // should be kept up to date with the special checks for those
5045 // expressions in Sema.
5046
5047 // alignof decl is always accepted, even if it doesn't make sense: we default
5048 // to 1 in those cases.
5049 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5050 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5051 /*RefAsPointee*/true);
5052
5053 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5054 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5055 /*RefAsPointee*/true);
5056
5057 return GetAlignOfType(Info, E->getType());
5058}
5059
Peter Collingbournee9200682011-05-13 03:29:01 +00005060bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005061 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005062 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005063
Alp Tokera724cff2013-12-28 21:59:02 +00005064 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005065 case Builtin::BI__builtin_addressof:
5066 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005067 case Builtin::BI__builtin_assume_aligned: {
5068 // We need to be very careful here because: if the pointer does not have the
5069 // asserted alignment, then the behavior is undefined, and undefined
5070 // behavior is non-constant.
5071 if (!EvaluatePointer(E->getArg(0), Result, Info))
5072 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005073
Hal Finkel0dd05d42014-10-03 17:18:37 +00005074 LValue OffsetResult(Result);
5075 APSInt Alignment;
5076 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5077 return false;
5078 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5079
5080 if (E->getNumArgs() > 2) {
5081 APSInt Offset;
5082 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5083 return false;
5084
5085 int64_t AdditionalOffset = -getExtValue(Offset);
5086 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5087 }
5088
5089 // If there is a base object, then it must have the correct alignment.
5090 if (OffsetResult.Base) {
5091 CharUnits BaseAlignment;
5092 if (const ValueDecl *VD =
5093 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5094 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5095 } else {
5096 BaseAlignment =
5097 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5098 }
5099
5100 if (BaseAlignment < Align) {
5101 Result.Designator.setInvalid();
5102 // FIXME: Quantities here cast to integers because the plural modifier
5103 // does not work on APSInts yet.
5104 CCEDiag(E->getArg(0),
5105 diag::note_constexpr_baa_insufficient_alignment) << 0
5106 << (int) BaseAlignment.getQuantity()
5107 << (unsigned) getExtValue(Alignment);
5108 return false;
5109 }
5110 }
5111
5112 // The offset must also have the correct alignment.
5113 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5114 Result.Designator.setInvalid();
5115 APSInt Offset(64, false);
5116 Offset = OffsetResult.Offset.getQuantity();
5117
5118 if (OffsetResult.Base)
5119 CCEDiag(E->getArg(0),
5120 diag::note_constexpr_baa_insufficient_alignment) << 1
5121 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5122 else
5123 CCEDiag(E->getArg(0),
5124 diag::note_constexpr_baa_value_insufficient_alignment)
5125 << Offset << (unsigned) getExtValue(Alignment);
5126
5127 return false;
5128 }
5129
5130 return true;
5131 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005132 default:
5133 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5134 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005135}
Chris Lattner05706e882008-07-11 18:11:29 +00005136
5137//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005138// Member Pointer Evaluation
5139//===----------------------------------------------------------------------===//
5140
5141namespace {
5142class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005143 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005144 MemberPtr &Result;
5145
5146 bool Success(const ValueDecl *D) {
5147 Result = MemberPtr(D);
5148 return true;
5149 }
5150public:
5151
5152 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5153 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5154
Richard Smith2e312c82012-03-03 22:46:17 +00005155 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005156 Result.setFrom(V);
5157 return true;
5158 }
Richard Smithfddd3842011-12-30 21:15:51 +00005159 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005160 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005161 }
5162
5163 bool VisitCastExpr(const CastExpr *E);
5164 bool VisitUnaryAddrOf(const UnaryOperator *E);
5165};
5166} // end anonymous namespace
5167
5168static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5169 EvalInfo &Info) {
5170 assert(E->isRValue() && E->getType()->isMemberPointerType());
5171 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5172}
5173
5174bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5175 switch (E->getCastKind()) {
5176 default:
5177 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5178
5179 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005180 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005181 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005182
5183 case CK_BaseToDerivedMemberPointer: {
5184 if (!Visit(E->getSubExpr()))
5185 return false;
5186 if (E->path_empty())
5187 return true;
5188 // Base-to-derived member pointer casts store the path in derived-to-base
5189 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5190 // the wrong end of the derived->base arc, so stagger the path by one class.
5191 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5192 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5193 PathI != PathE; ++PathI) {
5194 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5195 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5196 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005197 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005198 }
5199 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5200 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005201 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005202 return true;
5203 }
5204
5205 case CK_DerivedToBaseMemberPointer:
5206 if (!Visit(E->getSubExpr()))
5207 return false;
5208 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5209 PathE = E->path_end(); PathI != PathE; ++PathI) {
5210 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5211 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5212 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005213 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005214 }
5215 return true;
5216 }
5217}
5218
5219bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5220 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5221 // member can be formed.
5222 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5223}
5224
5225//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005226// Record Evaluation
5227//===----------------------------------------------------------------------===//
5228
5229namespace {
5230 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005231 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005232 const LValue &This;
5233 APValue &Result;
5234 public:
5235
5236 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5237 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5238
Richard Smith2e312c82012-03-03 22:46:17 +00005239 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005240 Result = V;
5241 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005242 }
Richard Smithfddd3842011-12-30 21:15:51 +00005243 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005244
Richard Smith52a980a2015-08-28 02:43:42 +00005245 bool VisitCallExpr(const CallExpr *E) {
5246 return handleCallExpr(E, Result, &This);
5247 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005248 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005249 bool VisitInitListExpr(const InitListExpr *E);
5250 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005251 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005252 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005253}
Richard Smithd62306a2011-11-10 06:34:14 +00005254
Richard Smithfddd3842011-12-30 21:15:51 +00005255/// Perform zero-initialization on an object of non-union class type.
5256/// C++11 [dcl.init]p5:
5257/// To zero-initialize an object or reference of type T means:
5258/// [...]
5259/// -- if T is a (possibly cv-qualified) non-union class type,
5260/// each non-static data member and each base-class subobject is
5261/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005262static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5263 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005264 const LValue &This, APValue &Result) {
5265 assert(!RD->isUnion() && "Expected non-union class type");
5266 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5267 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005268 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005269
John McCalld7bca762012-05-01 00:38:49 +00005270 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005271 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5272
5273 if (CD) {
5274 unsigned Index = 0;
5275 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005276 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005277 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5278 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005279 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5280 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005281 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005282 Result.getStructBase(Index)))
5283 return false;
5284 }
5285 }
5286
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005287 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005288 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005289 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005290 continue;
5291
5292 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005293 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005294 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005295
David Blaikie2d7c57e2012-04-30 02:36:29 +00005296 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005297 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005298 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005299 return false;
5300 }
5301
5302 return true;
5303}
5304
5305bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5306 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005307 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005308 if (RD->isUnion()) {
5309 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5310 // object's first non-static named data member is zero-initialized
5311 RecordDecl::field_iterator I = RD->field_begin();
5312 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005313 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005314 return true;
5315 }
5316
5317 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005318 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005319 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005320 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005321 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005322 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005323 }
5324
Richard Smith5d108602012-02-17 00:44:16 +00005325 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005326 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005327 return false;
5328 }
5329
Richard Smitha8105bc2012-01-06 16:39:00 +00005330 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005331}
5332
Richard Smithe97cbd72011-11-11 04:05:33 +00005333bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5334 switch (E->getCastKind()) {
5335 default:
5336 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5337
5338 case CK_ConstructorConversion:
5339 return Visit(E->getSubExpr());
5340
5341 case CK_DerivedToBase:
5342 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005343 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005344 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005345 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005346 if (!DerivedObject.isStruct())
5347 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005348
5349 // Derived-to-base rvalue conversion: just slice off the derived part.
5350 APValue *Value = &DerivedObject;
5351 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5352 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5353 PathE = E->path_end(); PathI != PathE; ++PathI) {
5354 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5355 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5356 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5357 RD = Base;
5358 }
5359 Result = *Value;
5360 return true;
5361 }
5362 }
5363}
5364
Richard Smithd62306a2011-11-10 06:34:14 +00005365bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5366 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005367 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005368 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5369
5370 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005371 const FieldDecl *Field = E->getInitializedFieldInUnion();
5372 Result = APValue(Field);
5373 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005374 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005375
5376 // If the initializer list for a union does not contain any elements, the
5377 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005378 // FIXME: The element should be initialized from an initializer list.
5379 // Is this difference ever observable for initializer lists which
5380 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005381 ImplicitValueInitExpr VIE(Field->getType());
5382 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5383
Richard Smithd62306a2011-11-10 06:34:14 +00005384 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005385 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5386 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005387
5388 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5389 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5390 isa<CXXDefaultInitExpr>(InitExpr));
5391
Richard Smithb228a862012-02-15 02:18:13 +00005392 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005393 }
5394
5395 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5396 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005397 Result = APValue(APValue::UninitStruct(), 0,
5398 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005399 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005400 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005401 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005402 // Anonymous bit-fields are not considered members of the class for
5403 // purposes of aggregate initialization.
5404 if (Field->isUnnamedBitfield())
5405 continue;
5406
5407 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005408
Richard Smith253c2a32012-01-27 01:14:48 +00005409 bool HaveInit = ElementNo < E->getNumInits();
5410
5411 // FIXME: Diagnostics here should point to the end of the initializer
5412 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005413 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005414 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005415 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005416
5417 // Perform an implicit value-initialization for members beyond the end of
5418 // the initializer list.
5419 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005420 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005421
Richard Smith852c9db2013-04-20 22:23:05 +00005422 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5423 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5424 isa<CXXDefaultInitExpr>(Init));
5425
Richard Smith49ca8aa2013-08-06 07:09:20 +00005426 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5427 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5428 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005429 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005430 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005431 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005432 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005433 }
5434 }
5435
Richard Smith253c2a32012-01-27 01:14:48 +00005436 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005437}
5438
5439bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5440 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005441 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5442
Richard Smithfddd3842011-12-30 21:15:51 +00005443 bool ZeroInit = E->requiresZeroInitialization();
5444 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005445 // If we've already performed zero-initialization, we're already done.
5446 if (!Result.isUninit())
5447 return true;
5448
Richard Smithda3f4fd2014-03-05 23:32:50 +00005449 // We can get here in two different ways:
5450 // 1) We're performing value-initialization, and should zero-initialize
5451 // the object, or
5452 // 2) We're performing default-initialization of an object with a trivial
5453 // constexpr default constructor, in which case we should start the
5454 // lifetimes of all the base subobjects (there can be no data member
5455 // subobjects in this case) per [basic.life]p1.
5456 // Either way, ZeroInitialization is appropriate.
5457 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005458 }
5459
Craig Topper36250ad2014-05-12 05:36:57 +00005460 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005461 FD->getBody(Definition);
5462
Richard Smith357362d2011-12-13 06:39:58 +00005463 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5464 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005465
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005466 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005467 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005468 if (const MaterializeTemporaryExpr *ME
5469 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5470 return Visit(ME->GetTemporaryExpr());
5471
Richard Smithfddd3842011-12-30 21:15:51 +00005472 if (ZeroInit && !ZeroInitialization(E))
5473 return false;
5474
Craig Topper5fc8fc22014-08-27 06:28:36 +00005475 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005476 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005477 cast<CXXConstructorDecl>(Definition), Info,
5478 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005479}
5480
Richard Smithcc1b96d2013-06-12 22:31:48 +00005481bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5482 const CXXStdInitializerListExpr *E) {
5483 const ConstantArrayType *ArrayType =
5484 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5485
5486 LValue Array;
5487 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5488 return false;
5489
5490 // Get a pointer to the first element of the array.
5491 Array.addArray(Info, E, ArrayType);
5492
5493 // FIXME: Perform the checks on the field types in SemaInit.
5494 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5495 RecordDecl::field_iterator Field = Record->field_begin();
5496 if (Field == Record->field_end())
5497 return Error(E);
5498
5499 // Start pointer.
5500 if (!Field->getType()->isPointerType() ||
5501 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5502 ArrayType->getElementType()))
5503 return Error(E);
5504
5505 // FIXME: What if the initializer_list type has base classes, etc?
5506 Result = APValue(APValue::UninitStruct(), 0, 2);
5507 Array.moveInto(Result.getStructField(0));
5508
5509 if (++Field == Record->field_end())
5510 return Error(E);
5511
5512 if (Field->getType()->isPointerType() &&
5513 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5514 ArrayType->getElementType())) {
5515 // End pointer.
5516 if (!HandleLValueArrayAdjustment(Info, E, Array,
5517 ArrayType->getElementType(),
5518 ArrayType->getSize().getZExtValue()))
5519 return false;
5520 Array.moveInto(Result.getStructField(1));
5521 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5522 // Length.
5523 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5524 else
5525 return Error(E);
5526
5527 if (++Field != Record->field_end())
5528 return Error(E);
5529
5530 return true;
5531}
5532
Richard Smithd62306a2011-11-10 06:34:14 +00005533static bool EvaluateRecord(const Expr *E, const LValue &This,
5534 APValue &Result, EvalInfo &Info) {
5535 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005536 "can't evaluate expression as a record rvalue");
5537 return RecordExprEvaluator(Info, This, Result).Visit(E);
5538}
5539
5540//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005541// Temporary Evaluation
5542//
5543// Temporaries are represented in the AST as rvalues, but generally behave like
5544// lvalues. The full-object of which the temporary is a subobject is implicitly
5545// materialized so that a reference can bind to it.
5546//===----------------------------------------------------------------------===//
5547namespace {
5548class TemporaryExprEvaluator
5549 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5550public:
5551 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5552 LValueExprEvaluatorBaseTy(Info, Result) {}
5553
5554 /// Visit an expression which constructs the value of this temporary.
5555 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005556 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005557 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5558 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005559 }
5560
5561 bool VisitCastExpr(const CastExpr *E) {
5562 switch (E->getCastKind()) {
5563 default:
5564 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5565
5566 case CK_ConstructorConversion:
5567 return VisitConstructExpr(E->getSubExpr());
5568 }
5569 }
5570 bool VisitInitListExpr(const InitListExpr *E) {
5571 return VisitConstructExpr(E);
5572 }
5573 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5574 return VisitConstructExpr(E);
5575 }
5576 bool VisitCallExpr(const CallExpr *E) {
5577 return VisitConstructExpr(E);
5578 }
Richard Smith513955c2014-12-17 19:24:30 +00005579 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5580 return VisitConstructExpr(E);
5581 }
Richard Smith027bf112011-11-17 22:56:20 +00005582};
5583} // end anonymous namespace
5584
5585/// Evaluate an expression of record type as a temporary.
5586static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005587 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005588 return TemporaryExprEvaluator(Info, Result).Visit(E);
5589}
5590
5591//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005592// Vector Evaluation
5593//===----------------------------------------------------------------------===//
5594
5595namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005596 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005597 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005598 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005599 public:
Mike Stump11289f42009-09-09 15:08:12 +00005600
Richard Smith2d406342011-10-22 21:10:00 +00005601 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5602 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005603
Craig Topper9798b932015-09-29 04:30:05 +00005604 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005605 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5606 // FIXME: remove this APValue copy.
5607 Result = APValue(V.data(), V.size());
5608 return true;
5609 }
Richard Smith2e312c82012-03-03 22:46:17 +00005610 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005611 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005612 Result = V;
5613 return true;
5614 }
Richard Smithfddd3842011-12-30 21:15:51 +00005615 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005616
Richard Smith2d406342011-10-22 21:10:00 +00005617 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005618 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005619 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005620 bool VisitInitListExpr(const InitListExpr *E);
5621 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005622 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005623 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005624 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005625 };
5626} // end anonymous namespace
5627
5628static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005629 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005630 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005631}
5632
Richard Smith2d406342011-10-22 21:10:00 +00005633bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5634 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005635 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005636
Richard Smith161f09a2011-12-06 22:44:34 +00005637 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005638 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005639
Eli Friedmanc757de22011-03-25 00:43:55 +00005640 switch (E->getCastKind()) {
5641 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005642 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005643 if (SETy->isIntegerType()) {
5644 APSInt IntResult;
5645 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005646 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005647 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005648 } else if (SETy->isRealFloatingType()) {
5649 APFloat F(0.0);
5650 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005651 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005652 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005653 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005654 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005655 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005656
5657 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005658 SmallVector<APValue, 4> Elts(NElts, Val);
5659 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005660 }
Eli Friedman803acb32011-12-22 03:51:45 +00005661 case CK_BitCast: {
5662 // Evaluate the operand into an APInt we can extract from.
5663 llvm::APInt SValInt;
5664 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5665 return false;
5666 // Extract the elements
5667 QualType EltTy = VTy->getElementType();
5668 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5669 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5670 SmallVector<APValue, 4> Elts;
5671 if (EltTy->isRealFloatingType()) {
5672 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005673 unsigned FloatEltSize = EltSize;
5674 if (&Sem == &APFloat::x87DoubleExtended)
5675 FloatEltSize = 80;
5676 for (unsigned i = 0; i < NElts; i++) {
5677 llvm::APInt Elt;
5678 if (BigEndian)
5679 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5680 else
5681 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005682 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005683 }
5684 } else if (EltTy->isIntegerType()) {
5685 for (unsigned i = 0; i < NElts; i++) {
5686 llvm::APInt Elt;
5687 if (BigEndian)
5688 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5689 else
5690 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5691 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5692 }
5693 } else {
5694 return Error(E);
5695 }
5696 return Success(Elts, E);
5697 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005698 default:
Richard Smith11562c52011-10-28 17:51:58 +00005699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005700 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005701}
5702
Richard Smith2d406342011-10-22 21:10:00 +00005703bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005704VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005705 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005706 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005707 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005708
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005709 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005710 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005711
Eli Friedmanb9c71292012-01-03 23:24:20 +00005712 // The number of initializers can be less than the number of
5713 // vector elements. For OpenCL, this can be due to nested vector
5714 // initialization. For GCC compatibility, missing trailing elements
5715 // should be initialized with zeroes.
5716 unsigned CountInits = 0, CountElts = 0;
5717 while (CountElts < NumElements) {
5718 // Handle nested vector initialization.
5719 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005720 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005721 APValue v;
5722 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5723 return Error(E);
5724 unsigned vlen = v.getVectorLength();
5725 for (unsigned j = 0; j < vlen; j++)
5726 Elements.push_back(v.getVectorElt(j));
5727 CountElts += vlen;
5728 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005729 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005730 if (CountInits < NumInits) {
5731 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005732 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005733 } else // trailing integer zero.
5734 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5735 Elements.push_back(APValue(sInt));
5736 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005737 } else {
5738 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005739 if (CountInits < NumInits) {
5740 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005741 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005742 } else // trailing float zero.
5743 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5744 Elements.push_back(APValue(f));
5745 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005746 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005747 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005748 }
Richard Smith2d406342011-10-22 21:10:00 +00005749 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005750}
5751
Richard Smith2d406342011-10-22 21:10:00 +00005752bool
Richard Smithfddd3842011-12-30 21:15:51 +00005753VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005754 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005755 QualType EltTy = VT->getElementType();
5756 APValue ZeroElement;
5757 if (EltTy->isIntegerType())
5758 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5759 else
5760 ZeroElement =
5761 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5762
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005763 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005764 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005765}
5766
Richard Smith2d406342011-10-22 21:10:00 +00005767bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005768 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005769 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005770}
5771
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005772//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005773// Array Evaluation
5774//===----------------------------------------------------------------------===//
5775
5776namespace {
5777 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005778 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005779 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005780 APValue &Result;
5781 public:
5782
Richard Smithd62306a2011-11-10 06:34:14 +00005783 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5784 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005785
5786 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005787 assert((V.isArray() || V.isLValue()) &&
5788 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005789 Result = V;
5790 return true;
5791 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005792
Richard Smithfddd3842011-12-30 21:15:51 +00005793 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005794 const ConstantArrayType *CAT =
5795 Info.Ctx.getAsConstantArrayType(E->getType());
5796 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005797 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005798
5799 Result = APValue(APValue::UninitArray(), 0,
5800 CAT->getSize().getZExtValue());
5801 if (!Result.hasArrayFiller()) return true;
5802
Richard Smithfddd3842011-12-30 21:15:51 +00005803 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005804 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005805 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005806 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005807 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005808 }
5809
Richard Smith52a980a2015-08-28 02:43:42 +00005810 bool VisitCallExpr(const CallExpr *E) {
5811 return handleCallExpr(E, Result, &This);
5812 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005813 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005814 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005815 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5816 const LValue &Subobject,
5817 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005818 };
5819} // end anonymous namespace
5820
Richard Smithd62306a2011-11-10 06:34:14 +00005821static bool EvaluateArray(const Expr *E, const LValue &This,
5822 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005823 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005824 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005825}
5826
5827bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5828 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5829 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005830 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005831
Richard Smithca2cfbf2011-12-22 01:07:19 +00005832 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5833 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005834 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005835 LValue LV;
5836 if (!EvaluateLValue(E->getInit(0), LV, Info))
5837 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005838 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005839 LV.moveInto(Val);
5840 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005841 }
5842
Richard Smith253c2a32012-01-27 01:14:48 +00005843 bool Success = true;
5844
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005845 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5846 "zero-initialized array shouldn't have any initialized elts");
5847 APValue Filler;
5848 if (Result.isArray() && Result.hasArrayFiller())
5849 Filler = Result.getArrayFiller();
5850
Richard Smith9543c5e2013-04-22 14:44:29 +00005851 unsigned NumEltsToInit = E->getNumInits();
5852 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005853 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005854
5855 // If the initializer might depend on the array index, run it for each
5856 // array element. For now, just whitelist non-class value-initialization.
5857 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5858 NumEltsToInit = NumElts;
5859
5860 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005861
5862 // If the array was previously zero-initialized, preserve the
5863 // zero-initialized values.
5864 if (!Filler.isUninit()) {
5865 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5866 Result.getArrayInitializedElt(I) = Filler;
5867 if (Result.hasArrayFiller())
5868 Result.getArrayFiller() = Filler;
5869 }
5870
Richard Smithd62306a2011-11-10 06:34:14 +00005871 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005872 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005873 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5874 const Expr *Init =
5875 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005876 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005877 Info, Subobject, Init) ||
5878 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005879 CAT->getElementType(), 1)) {
5880 if (!Info.keepEvaluatingAfterFailure())
5881 return false;
5882 Success = false;
5883 }
Richard Smithd62306a2011-11-10 06:34:14 +00005884 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005885
Richard Smith9543c5e2013-04-22 14:44:29 +00005886 if (!Result.hasArrayFiller())
5887 return Success;
5888
5889 // If we get here, we have a trivial filler, which we can just evaluate
5890 // once and splat over the rest of the array elements.
5891 assert(FillerExpr && "no array filler for incomplete init list");
5892 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5893 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005894}
5895
Richard Smith027bf112011-11-17 22:56:20 +00005896bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005897 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5898}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005899
Richard Smith9543c5e2013-04-22 14:44:29 +00005900bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5901 const LValue &Subobject,
5902 APValue *Value,
5903 QualType Type) {
5904 bool HadZeroInit = !Value->isUninit();
5905
5906 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5907 unsigned N = CAT->getSize().getZExtValue();
5908
5909 // Preserve the array filler if we had prior zero-initialization.
5910 APValue Filler =
5911 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5912 : APValue();
5913
5914 *Value = APValue(APValue::UninitArray(), N, N);
5915
5916 if (HadZeroInit)
5917 for (unsigned I = 0; I != N; ++I)
5918 Value->getArrayInitializedElt(I) = Filler;
5919
5920 // Initialize the elements.
5921 LValue ArrayElt = Subobject;
5922 ArrayElt.addArray(Info, E, CAT);
5923 for (unsigned I = 0; I != N; ++I)
5924 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5925 CAT->getElementType()) ||
5926 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5927 CAT->getElementType(), 1))
5928 return false;
5929
5930 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005931 }
Richard Smith027bf112011-11-17 22:56:20 +00005932
Richard Smith9543c5e2013-04-22 14:44:29 +00005933 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005934 return Error(E);
5935
Richard Smith027bf112011-11-17 22:56:20 +00005936 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005937
Richard Smithfddd3842011-12-30 21:15:51 +00005938 bool ZeroInit = E->requiresZeroInitialization();
5939 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005940 if (HadZeroInit)
5941 return true;
5942
Richard Smithda3f4fd2014-03-05 23:32:50 +00005943 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5944 ImplicitValueInitExpr VIE(Type);
5945 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005946 }
5947
Craig Topper36250ad2014-05-12 05:36:57 +00005948 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005949 FD->getBody(Definition);
5950
Richard Smith357362d2011-12-13 06:39:58 +00005951 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5952 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005953
Richard Smith9eae7232012-01-12 18:54:33 +00005954 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005955 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005956 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005957 return false;
5958 }
5959
Craig Topper5fc8fc22014-08-27 06:28:36 +00005960 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005961 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005962 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005963 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005964}
5965
Richard Smithf3e9e432011-11-07 09:22:26 +00005966//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005967// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005968//
5969// As a GNU extension, we support casting pointers to sufficiently-wide integer
5970// types and back in constant folding. Integer values are thus represented
5971// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005972//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005973
5974namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005975class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005976 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005977 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005978public:
Richard Smith2e312c82012-03-03 22:46:17 +00005979 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005980 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005981
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005982 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005983 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005984 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005985 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005986 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005987 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005988 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005989 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005990 return true;
5991 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005992 bool Success(const llvm::APSInt &SI, const Expr *E) {
5993 return Success(SI, E, Result);
5994 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005995
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005996 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005997 assert(E->getType()->isIntegralOrEnumerationType() &&
5998 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005999 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006000 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006001 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006002 Result.getInt().setIsUnsigned(
6003 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006004 return true;
6005 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006006 bool Success(const llvm::APInt &I, const Expr *E) {
6007 return Success(I, E, Result);
6008 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006009
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006010 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006011 assert(E->getType()->isIntegralOrEnumerationType() &&
6012 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006013 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006014 return true;
6015 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006016 bool Success(uint64_t Value, const Expr *E) {
6017 return Success(Value, E, Result);
6018 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006019
Ken Dyckdbc01912011-03-11 02:13:43 +00006020 bool Success(CharUnits Size, const Expr *E) {
6021 return Success(Size.getQuantity(), E);
6022 }
6023
Richard Smith2e312c82012-03-03 22:46:17 +00006024 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006025 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006026 Result = V;
6027 return true;
6028 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006029 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006030 }
Mike Stump11289f42009-09-09 15:08:12 +00006031
Richard Smithfddd3842011-12-30 21:15:51 +00006032 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006033
Peter Collingbournee9200682011-05-13 03:29:01 +00006034 //===--------------------------------------------------------------------===//
6035 // Visitor Methods
6036 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006037
Chris Lattner7174bf32008-07-12 00:38:25 +00006038 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006039 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006040 }
6041 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006042 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006043 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006044
6045 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6046 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006047 if (CheckReferencedDecl(E, E->getDecl()))
6048 return true;
6049
6050 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006051 }
6052 bool VisitMemberExpr(const MemberExpr *E) {
6053 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00006054 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006055 return true;
6056 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006057
6058 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006059 }
6060
Peter Collingbournee9200682011-05-13 03:29:01 +00006061 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006062 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006063 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006064 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006065
Peter Collingbournee9200682011-05-13 03:29:01 +00006066 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006067 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006068
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006069 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006070 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006071 }
Mike Stump11289f42009-09-09 15:08:12 +00006072
Ted Kremeneke65b0862012-03-06 20:05:56 +00006073 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6074 return Success(E->getValue(), E);
6075 }
6076
Richard Smith4ce706a2011-10-11 21:43:33 +00006077 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006078 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006079 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006080 }
6081
Douglas Gregor29c42f22012-02-24 07:38:34 +00006082 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6083 return Success(E->getValue(), E);
6084 }
6085
John Wiegley6242b6a2011-04-28 00:16:57 +00006086 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6087 return Success(E->getValue(), E);
6088 }
6089
John Wiegleyf9f65842011-04-25 06:54:41 +00006090 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6091 return Success(E->getValue(), E);
6092 }
6093
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006094 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006095 bool VisitUnaryImag(const UnaryOperator *E);
6096
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006097 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006098 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006099
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006100private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006101 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006102 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006103};
Chris Lattner05706e882008-07-11 18:11:29 +00006104} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006105
Richard Smith11562c52011-10-28 17:51:58 +00006106/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6107/// produce either the integer value or a pointer.
6108///
6109/// GCC has a heinous extension which folds casts between pointer types and
6110/// pointer-sized integral types. We support this by allowing the evaluation of
6111/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6112/// Some simple arithmetic on such values is supported (they are treated much
6113/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006114static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006115 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006116 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006117 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006118}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006119
Richard Smithf57d8cb2011-12-09 22:58:01 +00006120static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006121 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006122 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006123 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006124 if (!Val.isInt()) {
6125 // FIXME: It would be better to produce the diagnostic for casting
6126 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006127 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006128 return false;
6129 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006130 Result = Val.getInt();
6131 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006132}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006133
Richard Smithf57d8cb2011-12-09 22:58:01 +00006134/// Check whether the given declaration can be directly converted to an integral
6135/// rvalue. If not, no diagnostic is produced; there are other things we can
6136/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006137bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006138 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006139 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006140 // Check for signedness/width mismatches between E type and ECD value.
6141 bool SameSign = (ECD->getInitVal().isSigned()
6142 == E->getType()->isSignedIntegerOrEnumerationType());
6143 bool SameWidth = (ECD->getInitVal().getBitWidth()
6144 == Info.Ctx.getIntWidth(E->getType()));
6145 if (SameSign && SameWidth)
6146 return Success(ECD->getInitVal(), E);
6147 else {
6148 // Get rid of mismatch (otherwise Success assertions will fail)
6149 // by computing a new value matching the type of E.
6150 llvm::APSInt Val = ECD->getInitVal();
6151 if (!SameSign)
6152 Val.setIsSigned(!ECD->getInitVal().isSigned());
6153 if (!SameWidth)
6154 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6155 return Success(Val, E);
6156 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006157 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006158 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006159}
6160
Chris Lattner86ee2862008-10-06 06:40:35 +00006161/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6162/// as GCC.
6163static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6164 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006165 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006166 enum gcc_type_class {
6167 no_type_class = -1,
6168 void_type_class, integer_type_class, char_type_class,
6169 enumeral_type_class, boolean_type_class,
6170 pointer_type_class, reference_type_class, offset_type_class,
6171 real_type_class, complex_type_class,
6172 function_type_class, method_type_class,
6173 record_type_class, union_type_class,
6174 array_type_class, string_type_class,
6175 lang_type_class
6176 };
Mike Stump11289f42009-09-09 15:08:12 +00006177
6178 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006179 // ideal, however it is what gcc does.
6180 if (E->getNumArgs() == 0)
6181 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006182
Chris Lattner86ee2862008-10-06 06:40:35 +00006183 QualType ArgTy = E->getArg(0)->getType();
6184 if (ArgTy->isVoidType())
6185 return void_type_class;
6186 else if (ArgTy->isEnumeralType())
6187 return enumeral_type_class;
6188 else if (ArgTy->isBooleanType())
6189 return boolean_type_class;
6190 else if (ArgTy->isCharType())
6191 return string_type_class; // gcc doesn't appear to use char_type_class
6192 else if (ArgTy->isIntegerType())
6193 return integer_type_class;
6194 else if (ArgTy->isPointerType())
6195 return pointer_type_class;
6196 else if (ArgTy->isReferenceType())
6197 return reference_type_class;
6198 else if (ArgTy->isRealType())
6199 return real_type_class;
6200 else if (ArgTy->isComplexType())
6201 return complex_type_class;
6202 else if (ArgTy->isFunctionType())
6203 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006204 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006205 return record_type_class;
6206 else if (ArgTy->isUnionType())
6207 return union_type_class;
6208 else if (ArgTy->isArrayType())
6209 return array_type_class;
6210 else if (ArgTy->isUnionType())
6211 return union_type_class;
6212 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006213 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006214}
6215
Richard Smith5fab0c92011-12-28 19:48:30 +00006216/// EvaluateBuiltinConstantPForLValue - Determine the result of
6217/// __builtin_constant_p when applied to the given lvalue.
6218///
6219/// An lvalue is only "constant" if it is a pointer or reference to the first
6220/// character of a string literal.
6221template<typename LValue>
6222static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006223 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006224 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6225}
6226
6227/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6228/// GCC as we can manage.
6229static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6230 QualType ArgType = Arg->getType();
6231
6232 // __builtin_constant_p always has one operand. The rules which gcc follows
6233 // are not precisely documented, but are as follows:
6234 //
6235 // - If the operand is of integral, floating, complex or enumeration type,
6236 // and can be folded to a known value of that type, it returns 1.
6237 // - If the operand and can be folded to a pointer to the first character
6238 // of a string literal (or such a pointer cast to an integral type), it
6239 // returns 1.
6240 //
6241 // Otherwise, it returns 0.
6242 //
6243 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6244 // its support for this does not currently work.
6245 if (ArgType->isIntegralOrEnumerationType()) {
6246 Expr::EvalResult Result;
6247 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6248 return false;
6249
6250 APValue &V = Result.Val;
6251 if (V.getKind() == APValue::Int)
6252 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006253 if (V.getKind() == APValue::LValue)
6254 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006255 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6256 return Arg->isEvaluatable(Ctx);
6257 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6258 LValue LV;
6259 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006260 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006261 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6262 : EvaluatePointer(Arg, LV, Info)) &&
6263 !Status.HasSideEffects)
6264 return EvaluateBuiltinConstantPForLValue(LV);
6265 }
6266
6267 // Anything else isn't considered to be sufficiently constant.
6268 return false;
6269}
6270
John McCall95007602010-05-10 23:27:23 +00006271/// Retrieves the "underlying object type" of the given expression,
6272/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006273static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006274 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6275 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006276 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006277 } else if (const Expr *E = B.get<const Expr*>()) {
6278 if (isa<CompoundLiteralExpr>(E))
6279 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006280 }
6281
6282 return QualType();
6283}
6284
George Burgess IV3a03fab2015-09-04 21:28:13 +00006285/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006286/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6287/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006288/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6289///
6290/// Always returns an RValue with a pointer representation.
6291static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6292 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6293
6294 auto *NoParens = E->IgnoreParens();
6295 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006296 if (Cast == nullptr)
6297 return NoParens;
6298
6299 // We only conservatively allow a few kinds of casts, because this code is
6300 // inherently a simple solution that seeks to support the common case.
6301 auto CastKind = Cast->getCastKind();
6302 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6303 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006304 return NoParens;
6305
6306 auto *SubExpr = Cast->getSubExpr();
6307 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6308 return NoParens;
6309 return ignorePointerCastsAndParens(SubExpr);
6310}
6311
George Burgess IVa51c4072015-10-16 01:49:01 +00006312/// Checks to see if the given LValue's Designator is at the end of the LValue's
6313/// record layout. e.g.
6314/// struct { struct { int a, b; } fst, snd; } obj;
6315/// obj.fst // no
6316/// obj.snd // yes
6317/// obj.fst.a // no
6318/// obj.fst.b // no
6319/// obj.snd.a // no
6320/// obj.snd.b // yes
6321///
6322/// Please note: this function is specialized for how __builtin_object_size
6323/// views "objects".
6324static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6325 assert(!LVal.Designator.Invalid);
6326
6327 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6328 if (FD->getParent()->isUnion())
6329 return true;
6330 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6331 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6332 };
6333
6334 auto &Base = LVal.getLValueBase();
6335 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6336 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6337 if (!IsLastFieldDecl(FD))
6338 return false;
6339 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6340 for (auto *FD : IFD->chain())
6341 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6342 return false;
6343 }
6344 }
6345
6346 QualType BaseType = getType(Base);
6347 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6348 if (BaseType->isArrayType()) {
6349 // Because __builtin_object_size treats arrays as objects, we can ignore
6350 // the index iff this is the last array in the Designator.
6351 if (I + 1 == E)
6352 return true;
6353 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6354 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6355 if (Index + 1 != CAT->getSize())
6356 return false;
6357 BaseType = CAT->getElementType();
6358 } else if (BaseType->isAnyComplexType()) {
6359 auto *CT = BaseType->castAs<ComplexType>();
6360 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6361 if (Index != 1)
6362 return false;
6363 BaseType = CT->getElementType();
6364 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6365 if (!IsLastFieldDecl(FD))
6366 return false;
6367 BaseType = FD->getType();
6368 } else {
6369 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6370 "Expecting cast to a base class");
6371 return false;
6372 }
6373 }
6374 return true;
6375}
6376
6377/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6378static bool refersToCompleteObject(const LValue &LVal) {
6379 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6380 return false;
6381
6382 if (!LVal.InvalidBase)
6383 return true;
6384
6385 auto *E = LVal.Base.dyn_cast<const Expr *>();
6386 (void)E;
6387 assert(E != nullptr && isa<MemberExpr>(E));
6388 return false;
6389}
6390
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006391/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6392/// true and stores the result in @p Size.
6393///
6394/// If @p WasError is non-null, this will report whether the failure to evaluate
6395/// is to be treated as an Error in IntExprEvaluator.
6396static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6397 EvalInfo &Info, uint64_t &Size,
6398 bool *WasError = nullptr) {
6399 if (WasError != nullptr)
6400 *WasError = false;
6401
6402 auto Error = [&](const Expr *E) {
6403 if (WasError != nullptr)
6404 *WasError = true;
6405 return false;
6406 };
6407
6408 auto Success = [&](uint64_t S, const Expr *E) {
6409 Size = S;
6410 return true;
6411 };
6412
George Burgess IVbdb5b262015-08-19 02:19:07 +00006413 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006414 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006415 {
6416 // The operand of __builtin_object_size is never evaluated for side-effects.
6417 // If there are any, but we can determine the pointed-to object anyway, then
6418 // ignore the side-effects.
6419 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006420 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006421
6422 if (E->isGLValue()) {
6423 // It's possible for us to be given GLValues if we're called via
6424 // Expr::tryEvaluateObjectSize.
6425 APValue RVal;
6426 if (!EvaluateAsRValue(Info, E, RVal))
6427 return false;
6428 Base.setFrom(Info.Ctx, RVal);
6429 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006430 return false;
6431 }
John McCall95007602010-05-10 23:27:23 +00006432
George Burgess IVbdb5b262015-08-19 02:19:07 +00006433 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006434 // If we point to before the start of the object, there are no accessible
6435 // bytes.
6436 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006437 return Success(0, E);
6438
George Burgess IV3a03fab2015-09-04 21:28:13 +00006439 // In the case where we're not dealing with a subobject, we discard the
6440 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006441 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006442
6443 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6444 // exist. If we can't verify the base, then we can't do that.
6445 //
6446 // As a special case, we produce a valid object size for an unknown object
6447 // with a known designator if Type & 1 is 1. For instance:
6448 //
6449 // extern struct X { char buff[32]; int a, b, c; } *p;
6450 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6451 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6452 //
6453 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006454 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006455 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006456
George Burgess IVa51c4072015-10-16 01:49:01 +00006457 // If we're not examining only the subobject, then we reset to a complete
6458 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006459 //
6460 // If Type is 1 and we've lost track of the subobject, just find the complete
6461 // object instead. (If Type is 3, that's not correct behavior and we should
6462 // return 0 instead.)
6463 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006464 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006465 QualType T = getObjectType(End.getLValueBase());
6466 if (T.isNull())
6467 End.Designator.setInvalid();
6468 else {
6469 End.Designator = SubobjectDesignator(T);
6470 End.Offset = CharUnits::Zero();
6471 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006472 }
John McCall95007602010-05-10 23:27:23 +00006473
George Burgess IVbdb5b262015-08-19 02:19:07 +00006474 // If it is not possible to determine which objects ptr points to at compile
6475 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6476 // and (size_t) 0 for type 2 or 3.
6477 if (End.Designator.Invalid)
6478 return false;
6479
6480 // According to the GCC documentation, we want the size of the subobject
6481 // denoted by the pointer. But that's not quite right -- what we actually
6482 // want is the size of the immediately-enclosing array, if there is one.
6483 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006484 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006485 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6486 // We got a pointer to an array. Step to its end.
6487 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006488 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006489 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006490 // We're already pointing at the end of the object.
6491 AmountToAdd = 0;
6492 }
6493
George Burgess IV3a03fab2015-09-04 21:28:13 +00006494 QualType PointeeType = End.Designator.MostDerivedType;
6495 assert(!PointeeType.isNull());
6496 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006497 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006498
George Burgess IVbdb5b262015-08-19 02:19:07 +00006499 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6500 AmountToAdd))
6501 return false;
John McCall95007602010-05-10 23:27:23 +00006502
George Burgess IVbdb5b262015-08-19 02:19:07 +00006503 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006504
6505 // The following is a moderately common idiom in C:
6506 //
6507 // struct Foo { int a; char c[1]; };
6508 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6509 // strcpy(&F->c[0], Bar);
6510 //
6511 // So, if we see that we're examining a 1-length (or 0-length) array at the
6512 // end of a struct with an unknown base, we give up instead of breaking code
6513 // that behaves this way. Note that we only do this when Type=1, because
6514 // Type=3 is a lower bound, so answering conservatively is fine.
6515 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6516 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6517 End.Designator.MostDerivedIsArrayElement &&
6518 End.Designator.MostDerivedArraySize < 2 &&
6519 isDesignatorAtObjectEnd(Info.Ctx, End))
6520 return false;
6521
George Burgess IVbdb5b262015-08-19 02:19:07 +00006522 if (BaseOffset > EndOffset)
6523 return Success(0, E);
6524
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006525 return Success((EndOffset - BaseOffset).getQuantity(), E);
6526}
6527
6528bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6529 unsigned Type) {
6530 uint64_t Size;
6531 bool WasError;
6532 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6533 return Success(Size, E);
6534 if (WasError)
6535 return Error(E);
6536 return false;
John McCall95007602010-05-10 23:27:23 +00006537}
6538
Peter Collingbournee9200682011-05-13 03:29:01 +00006539bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006540 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006541 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006542 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006543
6544 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006545 // The type was checked when we built the expression.
6546 unsigned Type =
6547 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6548 assert(Type <= 3 && "unexpected type");
6549
6550 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006551 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006552
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006553 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006554 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006555
Richard Smith01ade172012-05-23 04:13:20 +00006556 // Expression had no side effects, but we couldn't statically determine the
6557 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006558 switch (Info.EvalMode) {
6559 case EvalInfo::EM_ConstantExpression:
6560 case EvalInfo::EM_PotentialConstantExpression:
6561 case EvalInfo::EM_ConstantFold:
6562 case EvalInfo::EM_EvaluateForOverflow:
6563 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006564 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006565 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006566 return Error(E);
6567 case EvalInfo::EM_ConstantExpressionUnevaluated:
6568 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006569 // Reduce it to a constant now.
6570 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006571 }
Mike Stump722cedf2009-10-26 18:35:08 +00006572 }
6573
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006574 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006575 case Builtin::BI__builtin_bswap32:
6576 case Builtin::BI__builtin_bswap64: {
6577 APSInt Val;
6578 if (!EvaluateInteger(E->getArg(0), Val, Info))
6579 return false;
6580
6581 return Success(Val.byteSwap(), E);
6582 }
6583
Richard Smith8889a3d2013-06-13 06:26:32 +00006584 case Builtin::BI__builtin_classify_type:
6585 return Success(EvaluateBuiltinClassifyType(E), E);
6586
6587 // FIXME: BI__builtin_clrsb
6588 // FIXME: BI__builtin_clrsbl
6589 // FIXME: BI__builtin_clrsbll
6590
Richard Smith80b3c8e2013-06-13 05:04:16 +00006591 case Builtin::BI__builtin_clz:
6592 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006593 case Builtin::BI__builtin_clzll:
6594 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006595 APSInt Val;
6596 if (!EvaluateInteger(E->getArg(0), Val, Info))
6597 return false;
6598 if (!Val)
6599 return Error(E);
6600
6601 return Success(Val.countLeadingZeros(), E);
6602 }
6603
Richard Smith8889a3d2013-06-13 06:26:32 +00006604 case Builtin::BI__builtin_constant_p:
6605 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6606
Richard Smith80b3c8e2013-06-13 05:04:16 +00006607 case Builtin::BI__builtin_ctz:
6608 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006609 case Builtin::BI__builtin_ctzll:
6610 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006611 APSInt Val;
6612 if (!EvaluateInteger(E->getArg(0), Val, Info))
6613 return false;
6614 if (!Val)
6615 return Error(E);
6616
6617 return Success(Val.countTrailingZeros(), E);
6618 }
6619
Richard Smith8889a3d2013-06-13 06:26:32 +00006620 case Builtin::BI__builtin_eh_return_data_regno: {
6621 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6622 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6623 return Success(Operand, E);
6624 }
6625
6626 case Builtin::BI__builtin_expect:
6627 return Visit(E->getArg(0));
6628
6629 case Builtin::BI__builtin_ffs:
6630 case Builtin::BI__builtin_ffsl:
6631 case Builtin::BI__builtin_ffsll: {
6632 APSInt Val;
6633 if (!EvaluateInteger(E->getArg(0), Val, Info))
6634 return false;
6635
6636 unsigned N = Val.countTrailingZeros();
6637 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6638 }
6639
6640 case Builtin::BI__builtin_fpclassify: {
6641 APFloat Val(0.0);
6642 if (!EvaluateFloat(E->getArg(5), Val, Info))
6643 return false;
6644 unsigned Arg;
6645 switch (Val.getCategory()) {
6646 case APFloat::fcNaN: Arg = 0; break;
6647 case APFloat::fcInfinity: Arg = 1; break;
6648 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6649 case APFloat::fcZero: Arg = 4; break;
6650 }
6651 return Visit(E->getArg(Arg));
6652 }
6653
6654 case Builtin::BI__builtin_isinf_sign: {
6655 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006656 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006657 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6658 }
6659
Richard Smithea3019d2013-10-15 19:07:14 +00006660 case Builtin::BI__builtin_isinf: {
6661 APFloat Val(0.0);
6662 return EvaluateFloat(E->getArg(0), Val, Info) &&
6663 Success(Val.isInfinity() ? 1 : 0, E);
6664 }
6665
6666 case Builtin::BI__builtin_isfinite: {
6667 APFloat Val(0.0);
6668 return EvaluateFloat(E->getArg(0), Val, Info) &&
6669 Success(Val.isFinite() ? 1 : 0, E);
6670 }
6671
6672 case Builtin::BI__builtin_isnan: {
6673 APFloat Val(0.0);
6674 return EvaluateFloat(E->getArg(0), Val, Info) &&
6675 Success(Val.isNaN() ? 1 : 0, E);
6676 }
6677
6678 case Builtin::BI__builtin_isnormal: {
6679 APFloat Val(0.0);
6680 return EvaluateFloat(E->getArg(0), Val, Info) &&
6681 Success(Val.isNormal() ? 1 : 0, E);
6682 }
6683
Richard Smith8889a3d2013-06-13 06:26:32 +00006684 case Builtin::BI__builtin_parity:
6685 case Builtin::BI__builtin_parityl:
6686 case Builtin::BI__builtin_parityll: {
6687 APSInt Val;
6688 if (!EvaluateInteger(E->getArg(0), Val, Info))
6689 return false;
6690
6691 return Success(Val.countPopulation() % 2, E);
6692 }
6693
Richard Smith80b3c8e2013-06-13 05:04:16 +00006694 case Builtin::BI__builtin_popcount:
6695 case Builtin::BI__builtin_popcountl:
6696 case Builtin::BI__builtin_popcountll: {
6697 APSInt Val;
6698 if (!EvaluateInteger(E->getArg(0), Val, Info))
6699 return false;
6700
6701 return Success(Val.countPopulation(), E);
6702 }
6703
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006704 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006705 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006706 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006707 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006708 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6709 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006710 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006711 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006712 case Builtin::BI__builtin_strlen: {
6713 // As an extension, we support __builtin_strlen() as a constant expression,
6714 // and support folding strlen() to a constant.
6715 LValue String;
6716 if (!EvaluatePointer(E->getArg(0), String, Info))
6717 return false;
6718
6719 // Fast path: if it's a string literal, search the string value.
6720 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6721 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006722 // The string literal may have embedded null characters. Find the first
6723 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006724 StringRef Str = S->getBytes();
6725 int64_t Off = String.Offset.getQuantity();
6726 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6727 S->getCharByteWidth() == 1) {
6728 Str = Str.substr(Off);
6729
6730 StringRef::size_type Pos = Str.find(0);
6731 if (Pos != StringRef::npos)
6732 Str = Str.substr(0, Pos);
6733
6734 return Success(Str.size(), E);
6735 }
6736
6737 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006738 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006739
6740 // Slow path: scan the bytes of the string looking for the terminating 0.
6741 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6742 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6743 APValue Char;
6744 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6745 !Char.isInt())
6746 return false;
6747 if (!Char.getInt())
6748 return Success(Strlen, E);
6749 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6750 return false;
6751 }
6752 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006753
Richard Smith01ba47d2012-04-13 00:45:38 +00006754 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006755 case Builtin::BI__atomic_is_lock_free:
6756 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006757 APSInt SizeVal;
6758 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6759 return false;
6760
6761 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6762 // of two less than the maximum inline atomic width, we know it is
6763 // lock-free. If the size isn't a power of two, or greater than the
6764 // maximum alignment where we promote atomics, we know it is not lock-free
6765 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6766 // the answer can only be determined at runtime; for example, 16-byte
6767 // atomics have lock-free implementations on some, but not all,
6768 // x86-64 processors.
6769
6770 // Check power-of-two.
6771 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006772 if (Size.isPowerOfTwo()) {
6773 // Check against inlining width.
6774 unsigned InlineWidthBits =
6775 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6776 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6777 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6778 Size == CharUnits::One() ||
6779 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6780 Expr::NPC_NeverValueDependent))
6781 // OK, we will inline appropriately-aligned operations of this size,
6782 // and _Atomic(T) is appropriately-aligned.
6783 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006784
Richard Smith01ba47d2012-04-13 00:45:38 +00006785 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6786 castAs<PointerType>()->getPointeeType();
6787 if (!PointeeType->isIncompleteType() &&
6788 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6789 // OK, we will inline operations on this object.
6790 return Success(1, E);
6791 }
6792 }
6793 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006794
Richard Smith01ba47d2012-04-13 00:45:38 +00006795 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6796 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006797 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006798 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006799}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006800
Richard Smith8b3497e2011-10-31 01:37:14 +00006801static bool HasSameBase(const LValue &A, const LValue &B) {
6802 if (!A.getLValueBase())
6803 return !B.getLValueBase();
6804 if (!B.getLValueBase())
6805 return false;
6806
Richard Smithce40ad62011-11-12 22:28:03 +00006807 if (A.getLValueBase().getOpaqueValue() !=
6808 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006809 const Decl *ADecl = GetLValueBaseDecl(A);
6810 if (!ADecl)
6811 return false;
6812 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006813 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006814 return false;
6815 }
6816
6817 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006818 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006819}
6820
Richard Smithd20f1e62014-10-21 23:01:04 +00006821/// \brief Determine whether this is a pointer past the end of the complete
6822/// object referred to by the lvalue.
6823static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6824 const LValue &LV) {
6825 // A null pointer can be viewed as being "past the end" but we don't
6826 // choose to look at it that way here.
6827 if (!LV.getLValueBase())
6828 return false;
6829
6830 // If the designator is valid and refers to a subobject, we're not pointing
6831 // past the end.
6832 if (!LV.getLValueDesignator().Invalid &&
6833 !LV.getLValueDesignator().isOnePastTheEnd())
6834 return false;
6835
David Majnemerc378ca52015-08-29 08:32:55 +00006836 // A pointer to an incomplete type might be past-the-end if the type's size is
6837 // zero. We cannot tell because the type is incomplete.
6838 QualType Ty = getType(LV.getLValueBase());
6839 if (Ty->isIncompleteType())
6840 return true;
6841
Richard Smithd20f1e62014-10-21 23:01:04 +00006842 // We're a past-the-end pointer if we point to the byte after the object,
6843 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006844 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006845 return LV.getLValueOffset() == Size;
6846}
6847
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006848namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006849
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006850/// \brief Data recursive integer evaluator of certain binary operators.
6851///
6852/// We use a data recursive algorithm for binary operators so that we are able
6853/// to handle extreme cases of chained binary operators without causing stack
6854/// overflow.
6855class DataRecursiveIntBinOpEvaluator {
6856 struct EvalResult {
6857 APValue Val;
6858 bool Failed;
6859
6860 EvalResult() : Failed(false) { }
6861
6862 void swap(EvalResult &RHS) {
6863 Val.swap(RHS.Val);
6864 Failed = RHS.Failed;
6865 RHS.Failed = false;
6866 }
6867 };
6868
6869 struct Job {
6870 const Expr *E;
6871 EvalResult LHSResult; // meaningful only for binary operator expression.
6872 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006873
David Blaikie73726062015-08-12 23:09:24 +00006874 Job() = default;
6875 Job(Job &&J)
6876 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6877 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6878 J.StoredInfo = nullptr;
6879 }
6880
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006881 void startSpeculativeEval(EvalInfo &Info) {
6882 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006883 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006884 StoredInfo = &Info;
6885 }
6886 ~Job() {
6887 if (StoredInfo) {
6888 StoredInfo->EvalStatus = OldEvalStatus;
6889 }
6890 }
6891 private:
David Blaikie73726062015-08-12 23:09:24 +00006892 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006893 Expr::EvalStatus OldEvalStatus;
6894 };
6895
6896 SmallVector<Job, 16> Queue;
6897
6898 IntExprEvaluator &IntEval;
6899 EvalInfo &Info;
6900 APValue &FinalResult;
6901
6902public:
6903 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6904 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6905
6906 /// \brief True if \param E is a binary operator that we are going to handle
6907 /// data recursively.
6908 /// We handle binary operators that are comma, logical, or that have operands
6909 /// with integral or enumeration type.
6910 static bool shouldEnqueue(const BinaryOperator *E) {
6911 return E->getOpcode() == BO_Comma ||
6912 E->isLogicalOp() ||
6913 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6914 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006915 }
6916
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006917 bool Traverse(const BinaryOperator *E) {
6918 enqueue(E);
6919 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006920 while (!Queue.empty())
6921 process(PrevResult);
6922
6923 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006925 FinalResult.swap(PrevResult.Val);
6926 return true;
6927 }
6928
6929private:
6930 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6931 return IntEval.Success(Value, E, Result);
6932 }
6933 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6934 return IntEval.Success(Value, E, Result);
6935 }
6936 bool Error(const Expr *E) {
6937 return IntEval.Error(E);
6938 }
6939 bool Error(const Expr *E, diag::kind D) {
6940 return IntEval.Error(E, D);
6941 }
6942
6943 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6944 return Info.CCEDiag(E, D);
6945 }
6946
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006947 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6948 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006949 bool &SuppressRHSDiags);
6950
6951 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6952 const BinaryOperator *E, APValue &Result);
6953
6954 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6955 Result.Failed = !Evaluate(Result.Val, Info, E);
6956 if (Result.Failed)
6957 Result.Val = APValue();
6958 }
6959
Richard Trieuba4d0872012-03-21 23:30:30 +00006960 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006961
6962 void enqueue(const Expr *E) {
6963 E = E->IgnoreParens();
6964 Queue.resize(Queue.size()+1);
6965 Queue.back().E = E;
6966 Queue.back().Kind = Job::AnyExprKind;
6967 }
6968};
6969
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006970}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006971
6972bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006973 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006974 bool &SuppressRHSDiags) {
6975 if (E->getOpcode() == BO_Comma) {
6976 // Ignore LHS but note if we could not evaluate it.
6977 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006978 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006979 return true;
6980 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006981
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006982 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006983 bool LHSAsBool;
6984 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006985 // We were able to evaluate the LHS, see if we can get away with not
6986 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006987 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6988 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006989 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006990 }
6991 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006992 LHSResult.Failed = true;
6993
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006994 // Since we weren't able to evaluate the left hand side, it
6995 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006996 if (!Info.noteSideEffect())
6997 return false;
6998
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006999 // We can't evaluate the LHS; however, sometimes the result
7000 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7001 // Don't ignore RHS and suppress diagnostics from this arm.
7002 SuppressRHSDiags = true;
7003 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007004
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007005 return true;
7006 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007007
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007008 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7009 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007010
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007011 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007012 return false; // Ignore RHS;
7013
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007014 return true;
7015}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007016
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007017bool DataRecursiveIntBinOpEvaluator::
7018 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7019 const BinaryOperator *E, APValue &Result) {
7020 if (E->getOpcode() == BO_Comma) {
7021 if (RHSResult.Failed)
7022 return false;
7023 Result = RHSResult.Val;
7024 return true;
7025 }
7026
7027 if (E->isLogicalOp()) {
7028 bool lhsResult, rhsResult;
7029 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7030 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7031
7032 if (LHSIsOK) {
7033 if (RHSIsOK) {
7034 if (E->getOpcode() == BO_LOr)
7035 return Success(lhsResult || rhsResult, E, Result);
7036 else
7037 return Success(lhsResult && rhsResult, E, Result);
7038 }
7039 } else {
7040 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007041 // We can't evaluate the LHS; however, sometimes the result
7042 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7043 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007044 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007045 }
7046 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007047
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007048 return false;
7049 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007050
7051 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7052 E->getRHS()->getType()->isIntegralOrEnumerationType());
7053
7054 if (LHSResult.Failed || RHSResult.Failed)
7055 return false;
7056
7057 const APValue &LHSVal = LHSResult.Val;
7058 const APValue &RHSVal = RHSResult.Val;
7059
7060 // Handle cases like (unsigned long)&a + 4.
7061 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7062 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007063 CharUnits AdditionalOffset =
7064 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007065 if (E->getOpcode() == BO_Add)
7066 Result.getLValueOffset() += AdditionalOffset;
7067 else
7068 Result.getLValueOffset() -= AdditionalOffset;
7069 return true;
7070 }
7071
7072 // Handle cases like 4 + (unsigned long)&a
7073 if (E->getOpcode() == BO_Add &&
7074 RHSVal.isLValue() && LHSVal.isInt()) {
7075 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007076 Result.getLValueOffset() +=
7077 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007078 return true;
7079 }
7080
7081 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7082 // Handle (intptr_t)&&A - (intptr_t)&&B.
7083 if (!LHSVal.getLValueOffset().isZero() ||
7084 !RHSVal.getLValueOffset().isZero())
7085 return false;
7086 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7087 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7088 if (!LHSExpr || !RHSExpr)
7089 return false;
7090 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7091 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7092 if (!LHSAddrExpr || !RHSAddrExpr)
7093 return false;
7094 // Make sure both labels come from the same function.
7095 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7096 RHSAddrExpr->getLabel()->getDeclContext())
7097 return false;
7098 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7099 return true;
7100 }
Richard Smith43e77732013-05-07 04:50:00 +00007101
7102 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007103 if (!LHSVal.isInt() || !RHSVal.isInt())
7104 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007105
7106 // Set up the width and signedness manually, in case it can't be deduced
7107 // from the operation we're performing.
7108 // FIXME: Don't do this in the cases where we can deduce it.
7109 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7110 E->getType()->isUnsignedIntegerOrEnumerationType());
7111 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7112 RHSVal.getInt(), Value))
7113 return false;
7114 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007115}
7116
Richard Trieuba4d0872012-03-21 23:30:30 +00007117void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007118 Job &job = Queue.back();
7119
7120 switch (job.Kind) {
7121 case Job::AnyExprKind: {
7122 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7123 if (shouldEnqueue(Bop)) {
7124 job.Kind = Job::BinOpKind;
7125 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007126 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007127 }
7128 }
7129
7130 EvaluateExpr(job.E, Result);
7131 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007132 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007133 }
7134
7135 case Job::BinOpKind: {
7136 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007137 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007138 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007139 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007140 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007141 }
7142 if (SuppressRHSDiags)
7143 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007144 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007145 job.Kind = Job::BinOpVisitedLHSKind;
7146 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007147 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007148 }
7149
7150 case Job::BinOpVisitedLHSKind: {
7151 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7152 EvalResult RHS;
7153 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007154 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007155 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007156 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007157 }
7158 }
7159
7160 llvm_unreachable("Invalid Job::Kind!");
7161}
7162
7163bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00007164 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007165 return Error(E);
7166
7167 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7168 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007169
Anders Carlssonacc79812008-11-16 07:17:21 +00007170 QualType LHSTy = E->getLHS()->getType();
7171 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007172
Chandler Carruthb29a7432014-10-11 11:03:30 +00007173 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007174 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007175 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007176 if (E->isAssignmentOp()) {
7177 LValue LV;
7178 EvaluateLValue(E->getLHS(), LV, Info);
7179 LHSOK = false;
7180 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007181 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7182 if (LHSOK) {
7183 LHS.makeComplexFloat();
7184 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7185 }
7186 } else {
7187 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7188 }
Richard Smith253c2a32012-01-27 01:14:48 +00007189 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007190 return false;
7191
Chandler Carruthb29a7432014-10-11 11:03:30 +00007192 if (E->getRHS()->getType()->isRealFloatingType()) {
7193 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7194 return false;
7195 RHS.makeComplexFloat();
7196 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7197 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007198 return false;
7199
7200 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007201 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007202 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007203 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007204 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7205
John McCalle3027922010-08-25 11:45:40 +00007206 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007207 return Success((CR_r == APFloat::cmpEqual &&
7208 CR_i == APFloat::cmpEqual), E);
7209 else {
John McCalle3027922010-08-25 11:45:40 +00007210 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007211 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007212 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007213 CR_r == APFloat::cmpLessThan ||
7214 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007215 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007216 CR_i == APFloat::cmpLessThan ||
7217 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007218 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007219 } else {
John McCalle3027922010-08-25 11:45:40 +00007220 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007221 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7222 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7223 else {
John McCalle3027922010-08-25 11:45:40 +00007224 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007225 "Invalid compex comparison.");
7226 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7227 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7228 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007229 }
7230 }
Mike Stump11289f42009-09-09 15:08:12 +00007231
Anders Carlssonacc79812008-11-16 07:17:21 +00007232 if (LHSTy->isRealFloatingType() &&
7233 RHSTy->isRealFloatingType()) {
7234 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007235
Richard Smith253c2a32012-01-27 01:14:48 +00007236 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7237 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007238 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007239
Richard Smith253c2a32012-01-27 01:14:48 +00007240 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007241 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007242
Anders Carlssonacc79812008-11-16 07:17:21 +00007243 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007244
Anders Carlssonacc79812008-11-16 07:17:21 +00007245 switch (E->getOpcode()) {
7246 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007247 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007248 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007249 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007250 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007251 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007252 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007253 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007254 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007255 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007256 E);
John McCalle3027922010-08-25 11:45:40 +00007257 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007258 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007259 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007260 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007261 || CR == APFloat::cmpLessThan
7262 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007263 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007264 }
Mike Stump11289f42009-09-09 15:08:12 +00007265
Eli Friedmana38da572009-04-28 19:17:36 +00007266 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007267 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007268 LValue LHSValue, RHSValue;
7269
7270 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
Richard Smith0c6124b2015-12-03 01:36:22 +00007271 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007272 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007273
Richard Smith253c2a32012-01-27 01:14:48 +00007274 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007275 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007276
Richard Smith8b3497e2011-10-31 01:37:14 +00007277 // Reject differing bases from the normal codepath; we special-case
7278 // comparisons to null.
7279 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007280 if (E->getOpcode() == BO_Sub) {
7281 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007282 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007283 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007284 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007285 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007286 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007287 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007288 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7289 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7290 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007291 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007292 // Make sure both labels come from the same function.
7293 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7294 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007295 return Error(E);
7296 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007297 }
Richard Smith83c68212011-10-31 05:11:32 +00007298 // Inequalities and subtractions between unrelated pointers have
7299 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007300 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007301 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007302 // A constant address may compare equal to the address of a symbol.
7303 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007304 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007305 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7306 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007307 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007308 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007309 // distinct addresses. In clang, the result of such a comparison is
7310 // unspecified, so it is not a constant expression. However, we do know
7311 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007312 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7313 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007314 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007315 // We can't tell whether weak symbols will end up pointing to the same
7316 // object.
7317 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007318 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007319 // We can't compare the address of the start of one object with the
7320 // past-the-end address of another object, per C++ DR1652.
7321 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7322 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7323 (RHSValue.Base && RHSValue.Offset.isZero() &&
7324 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7325 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007326 // We can't tell whether an object is at the same address as another
7327 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007328 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7329 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007330 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007331 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007332 // (Note that clang defaults to -fmerge-all-constants, which can
7333 // lead to inconsistent results for comparisons involving the address
7334 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007335 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007336 }
Eli Friedman64004332009-03-23 04:38:34 +00007337
Richard Smith1b470412012-02-01 08:10:20 +00007338 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7339 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7340
Richard Smith84f6dcf2012-02-02 01:16:57 +00007341 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7342 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7343
John McCalle3027922010-08-25 11:45:40 +00007344 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007345 // C++11 [expr.add]p6:
7346 // Unless both pointers point to elements of the same array object, or
7347 // one past the last element of the array object, the behavior is
7348 // undefined.
7349 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7350 !AreElementsOfSameArray(getType(LHSValue.Base),
7351 LHSDesignator, RHSDesignator))
7352 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7353
Chris Lattner882bdf22010-04-20 17:13:14 +00007354 QualType Type = E->getLHS()->getType();
7355 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007356
Richard Smithd62306a2011-11-10 06:34:14 +00007357 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007358 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007359 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007360
Richard Smith84c6b3d2013-09-10 21:34:14 +00007361 // As an extension, a type may have zero size (empty struct or union in
7362 // C, array of zero length). Pointer subtraction in such cases has
7363 // undefined behavior, so is not constant.
7364 if (ElementSize.isZero()) {
7365 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7366 << ElementType;
7367 return false;
7368 }
7369
Richard Smith1b470412012-02-01 08:10:20 +00007370 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7371 // and produce incorrect results when it overflows. Such behavior
7372 // appears to be non-conforming, but is common, so perhaps we should
7373 // assume the standard intended for such cases to be undefined behavior
7374 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007375
Richard Smith1b470412012-02-01 08:10:20 +00007376 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7377 // overflow in the final conversion to ptrdiff_t.
7378 APSInt LHS(
7379 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7380 APSInt RHS(
7381 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7382 APSInt ElemSize(
7383 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7384 APSInt TrueResult = (LHS - RHS) / ElemSize;
7385 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7386
Richard Smith0c6124b2015-12-03 01:36:22 +00007387 if (Result.extend(65) != TrueResult &&
7388 !HandleOverflow(Info, E, TrueResult, E->getType()))
7389 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007390 return Success(Result, E);
7391 }
Richard Smithde21b242012-01-31 06:41:30 +00007392
7393 // C++11 [expr.rel]p3:
7394 // Pointers to void (after pointer conversions) can be compared, with a
7395 // result defined as follows: If both pointers represent the same
7396 // address or are both the null pointer value, the result is true if the
7397 // operator is <= or >= and false otherwise; otherwise the result is
7398 // unspecified.
7399 // We interpret this as applying to pointers to *cv* void.
7400 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007401 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007402 CCEDiag(E, diag::note_constexpr_void_comparison);
7403
Richard Smith84f6dcf2012-02-02 01:16:57 +00007404 // C++11 [expr.rel]p2:
7405 // - If two pointers point to non-static data members of the same object,
7406 // or to subobjects or array elements fo such members, recursively, the
7407 // pointer to the later declared member compares greater provided the
7408 // two members have the same access control and provided their class is
7409 // not a union.
7410 // [...]
7411 // - Otherwise pointer comparisons are unspecified.
7412 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7413 E->isRelationalOp()) {
7414 bool WasArrayIndex;
7415 unsigned Mismatch =
7416 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7417 RHSDesignator, WasArrayIndex);
7418 // At the point where the designators diverge, the comparison has a
7419 // specified value if:
7420 // - we are comparing array indices
7421 // - we are comparing fields of a union, or fields with the same access
7422 // Otherwise, the result is unspecified and thus the comparison is not a
7423 // constant expression.
7424 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7425 Mismatch < RHSDesignator.Entries.size()) {
7426 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7427 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7428 if (!LF && !RF)
7429 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7430 else if (!LF)
7431 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7432 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7433 << RF->getParent() << RF;
7434 else if (!RF)
7435 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7436 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7437 << LF->getParent() << LF;
7438 else if (!LF->getParent()->isUnion() &&
7439 LF->getAccess() != RF->getAccess())
7440 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7441 << LF << LF->getAccess() << RF << RF->getAccess()
7442 << LF->getParent();
7443 }
7444 }
7445
Eli Friedman6c31cb42012-04-16 04:30:08 +00007446 // The comparison here must be unsigned, and performed with the same
7447 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007448 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7449 uint64_t CompareLHS = LHSOffset.getQuantity();
7450 uint64_t CompareRHS = RHSOffset.getQuantity();
7451 assert(PtrSize <= 64 && "Unexpected pointer width");
7452 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7453 CompareLHS &= Mask;
7454 CompareRHS &= Mask;
7455
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007456 // If there is a base and this is a relational operator, we can only
7457 // compare pointers within the object in question; otherwise, the result
7458 // depends on where the object is located in memory.
7459 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7460 QualType BaseTy = getType(LHSValue.Base);
7461 if (BaseTy->isIncompleteType())
7462 return Error(E);
7463 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7464 uint64_t OffsetLimit = Size.getQuantity();
7465 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7466 return Error(E);
7467 }
7468
Richard Smith8b3497e2011-10-31 01:37:14 +00007469 switch (E->getOpcode()) {
7470 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007471 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7472 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7473 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7474 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7475 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7476 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007477 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007478 }
7479 }
Richard Smith7bb00672012-02-01 01:42:44 +00007480
7481 if (LHSTy->isMemberPointerType()) {
7482 assert(E->isEqualityOp() && "unexpected member pointer operation");
7483 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7484
7485 MemberPtr LHSValue, RHSValue;
7486
7487 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7488 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7489 return false;
7490
7491 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7492 return false;
7493
7494 // C++11 [expr.eq]p2:
7495 // If both operands are null, they compare equal. Otherwise if only one is
7496 // null, they compare unequal.
7497 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7498 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7499 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7500 }
7501
7502 // Otherwise if either is a pointer to a virtual member function, the
7503 // result is unspecified.
7504 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7505 if (MD->isVirtual())
7506 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7507 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7508 if (MD->isVirtual())
7509 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7510
7511 // Otherwise they compare equal if and only if they would refer to the
7512 // same member of the same most derived object or the same subobject if
7513 // they were dereferenced with a hypothetical object of the associated
7514 // class type.
7515 bool Equal = LHSValue == RHSValue;
7516 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7517 }
7518
Richard Smithab44d9b2012-02-14 22:35:28 +00007519 if (LHSTy->isNullPtrType()) {
7520 assert(E->isComparisonOp() && "unexpected nullptr operation");
7521 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7522 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7523 // are compared, the result is true of the operator is <=, >= or ==, and
7524 // false otherwise.
7525 BinaryOperator::Opcode Opcode = E->getOpcode();
7526 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7527 }
7528
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007529 assert((!LHSTy->isIntegralOrEnumerationType() ||
7530 !RHSTy->isIntegralOrEnumerationType()) &&
7531 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7532 // We can't continue from here for non-integral types.
7533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007534}
7535
Peter Collingbournee190dee2011-03-11 19:24:49 +00007536/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7537/// a result as the expression's type.
7538bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7539 const UnaryExprOrTypeTraitExpr *E) {
7540 switch(E->getKind()) {
7541 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007542 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007543 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007544 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007545 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007546 }
Eli Friedman64004332009-03-23 04:38:34 +00007547
Peter Collingbournee190dee2011-03-11 19:24:49 +00007548 case UETT_VecStep: {
7549 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007550
Peter Collingbournee190dee2011-03-11 19:24:49 +00007551 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007552 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007553
Peter Collingbournee190dee2011-03-11 19:24:49 +00007554 // The vec_step built-in functions that take a 3-component
7555 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7556 if (n == 3)
7557 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007558
Peter Collingbournee190dee2011-03-11 19:24:49 +00007559 return Success(n, E);
7560 } else
7561 return Success(1, E);
7562 }
7563
7564 case UETT_SizeOf: {
7565 QualType SrcTy = E->getTypeOfArgument();
7566 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7567 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007568 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7569 SrcTy = Ref->getPointeeType();
7570
Richard Smithd62306a2011-11-10 06:34:14 +00007571 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007572 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007573 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007574 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007575 }
Alexey Bataev00396512015-07-02 03:40:19 +00007576 case UETT_OpenMPRequiredSimdAlign:
7577 assert(E->isArgumentType());
7578 return Success(
7579 Info.Ctx.toCharUnitsFromBits(
7580 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7581 .getQuantity(),
7582 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007583 }
7584
7585 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007586}
7587
Peter Collingbournee9200682011-05-13 03:29:01 +00007588bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007589 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007590 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007591 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007592 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007593 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007594 for (unsigned i = 0; i != n; ++i) {
7595 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7596 switch (ON.getKind()) {
7597 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007598 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007599 APSInt IdxResult;
7600 if (!EvaluateInteger(Idx, IdxResult, Info))
7601 return false;
7602 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7603 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007604 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007605 CurrentType = AT->getElementType();
7606 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7607 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007608 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007609 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007610
Douglas Gregor882211c2010-04-28 22:16:22 +00007611 case OffsetOfExpr::OffsetOfNode::Field: {
7612 FieldDecl *MemberDecl = ON.getField();
7613 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007614 if (!RT)
7615 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007616 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007617 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007618 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007619 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007620 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007621 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007622 CurrentType = MemberDecl->getType().getNonReferenceType();
7623 break;
7624 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007625
Douglas Gregor882211c2010-04-28 22:16:22 +00007626 case OffsetOfExpr::OffsetOfNode::Identifier:
7627 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007628
Douglas Gregord1702062010-04-29 00:18:15 +00007629 case OffsetOfExpr::OffsetOfNode::Base: {
7630 CXXBaseSpecifier *BaseSpec = ON.getBase();
7631 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007632 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007633
7634 // Find the layout of the class whose base we are looking into.
7635 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007636 if (!RT)
7637 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007638 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007639 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007640 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7641
7642 // Find the base class itself.
7643 CurrentType = BaseSpec->getType();
7644 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7645 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007646 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007647
7648 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007649 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007650 break;
7651 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007652 }
7653 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007654 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007655}
7656
Chris Lattnere13042c2008-07-11 19:10:17 +00007657bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007658 switch (E->getOpcode()) {
7659 default:
7660 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7661 // See C99 6.6p3.
7662 return Error(E);
7663 case UO_Extension:
7664 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7665 // If so, we could clear the diagnostic ID.
7666 return Visit(E->getSubExpr());
7667 case UO_Plus:
7668 // The result is just the value.
7669 return Visit(E->getSubExpr());
7670 case UO_Minus: {
7671 if (!Visit(E->getSubExpr()))
7672 return false;
7673 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007674 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007675 if (Value.isSigned() && Value.isMinSignedValue() &&
7676 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7677 E->getType()))
7678 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007679 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007680 }
7681 case UO_Not: {
7682 if (!Visit(E->getSubExpr()))
7683 return false;
7684 if (!Result.isInt()) return Error(E);
7685 return Success(~Result.getInt(), E);
7686 }
7687 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007688 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007689 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007690 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007691 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007692 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007693 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007694}
Mike Stump11289f42009-09-09 15:08:12 +00007695
Chris Lattner477c4be2008-07-12 01:15:53 +00007696/// HandleCast - This is used to evaluate implicit or explicit casts where the
7697/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007698bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7699 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007700 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007701 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007702
Eli Friedmanc757de22011-03-25 00:43:55 +00007703 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007704 case CK_BaseToDerived:
7705 case CK_DerivedToBase:
7706 case CK_UncheckedDerivedToBase:
7707 case CK_Dynamic:
7708 case CK_ToUnion:
7709 case CK_ArrayToPointerDecay:
7710 case CK_FunctionToPointerDecay:
7711 case CK_NullToPointer:
7712 case CK_NullToMemberPointer:
7713 case CK_BaseToDerivedMemberPointer:
7714 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007715 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007716 case CK_ConstructorConversion:
7717 case CK_IntegralToPointer:
7718 case CK_ToVoid:
7719 case CK_VectorSplat:
7720 case CK_IntegralToFloating:
7721 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007722 case CK_CPointerToObjCPointerCast:
7723 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007724 case CK_AnyPointerToBlockPointerCast:
7725 case CK_ObjCObjectLValueCast:
7726 case CK_FloatingRealToComplex:
7727 case CK_FloatingComplexToReal:
7728 case CK_FloatingComplexCast:
7729 case CK_FloatingComplexToIntegralComplex:
7730 case CK_IntegralRealToComplex:
7731 case CK_IntegralComplexCast:
7732 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007733 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007734 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007735 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007736 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007737 llvm_unreachable("invalid cast kind for integral value");
7738
Eli Friedman9faf2f92011-03-25 19:07:11 +00007739 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007740 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007741 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007742 case CK_ARCProduceObject:
7743 case CK_ARCConsumeObject:
7744 case CK_ARCReclaimReturnedObject:
7745 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007746 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007747 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007748
Richard Smith4ef685b2012-01-17 21:17:26 +00007749 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007750 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007751 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007752 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007753 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007754
7755 case CK_MemberPointerToBoolean:
7756 case CK_PointerToBoolean:
7757 case CK_IntegralToBoolean:
7758 case CK_FloatingToBoolean:
7759 case CK_FloatingComplexToBoolean:
7760 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007761 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007762 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007763 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007764 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007765 }
7766
Eli Friedmanc757de22011-03-25 00:43:55 +00007767 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007768 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007769 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007770
Eli Friedman742421e2009-02-20 01:15:07 +00007771 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007772 // Allow casts of address-of-label differences if they are no-ops
7773 // or narrowing. (The narrowing case isn't actually guaranteed to
7774 // be constant-evaluatable except in some narrow cases which are hard
7775 // to detect here. We let it through on the assumption the user knows
7776 // what they are doing.)
7777 if (Result.isAddrLabelDiff())
7778 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007779 // Only allow casts of lvalues if they are lossless.
7780 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7781 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007782
Richard Smith911e1422012-01-30 22:27:01 +00007783 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7784 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007785 }
Mike Stump11289f42009-09-09 15:08:12 +00007786
Eli Friedmanc757de22011-03-25 00:43:55 +00007787 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007788 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7789
John McCall45d55e42010-05-07 21:00:08 +00007790 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007791 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007792 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007793
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007794 if (LV.getLValueBase()) {
7795 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007796 // FIXME: Allow a larger integer size than the pointer size, and allow
7797 // narrowing back down to pointer width in subsequent integral casts.
7798 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007799 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007800 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007801
Richard Smithcf74da72011-11-16 07:18:12 +00007802 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007803 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007804 return true;
7805 }
7806
Ken Dyck02990832010-01-15 12:37:54 +00007807 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7808 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007809 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007810 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007811
Eli Friedmanc757de22011-03-25 00:43:55 +00007812 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007813 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007814 if (!EvaluateComplex(SubExpr, C, Info))
7815 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007816 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007817 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007818
Eli Friedmanc757de22011-03-25 00:43:55 +00007819 case CK_FloatingToIntegral: {
7820 APFloat F(0.0);
7821 if (!EvaluateFloat(SubExpr, F, Info))
7822 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007823
Richard Smith357362d2011-12-13 06:39:58 +00007824 APSInt Value;
7825 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7826 return false;
7827 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007828 }
7829 }
Mike Stump11289f42009-09-09 15:08:12 +00007830
Eli Friedmanc757de22011-03-25 00:43:55 +00007831 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007832}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007833
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007834bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7835 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007836 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007837 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7838 return false;
7839 if (!LV.isComplexInt())
7840 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007841 return Success(LV.getComplexIntReal(), E);
7842 }
7843
7844 return Visit(E->getSubExpr());
7845}
7846
Eli Friedman4e7a2412009-02-27 04:45:43 +00007847bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007848 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007849 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007850 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7851 return false;
7852 if (!LV.isComplexInt())
7853 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007854 return Success(LV.getComplexIntImag(), E);
7855 }
7856
Richard Smith4a678122011-10-24 18:44:57 +00007857 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007858 return Success(0, E);
7859}
7860
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007861bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7862 return Success(E->getPackLength(), E);
7863}
7864
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007865bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7866 return Success(E->getValue(), E);
7867}
7868
Chris Lattner05706e882008-07-11 18:11:29 +00007869//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007870// Float Evaluation
7871//===----------------------------------------------------------------------===//
7872
7873namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007874class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007875 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007876 APFloat &Result;
7877public:
7878 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007879 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007880
Richard Smith2e312c82012-03-03 22:46:17 +00007881 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007882 Result = V.getFloat();
7883 return true;
7884 }
Eli Friedman24c01542008-08-22 00:06:13 +00007885
Richard Smithfddd3842011-12-30 21:15:51 +00007886 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007887 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7888 return true;
7889 }
7890
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007891 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007892
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007893 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007894 bool VisitBinaryOperator(const BinaryOperator *E);
7895 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007896 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007897
John McCallb1fb0d32010-05-07 22:08:54 +00007898 bool VisitUnaryReal(const UnaryOperator *E);
7899 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007900
Richard Smithfddd3842011-12-30 21:15:51 +00007901 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007902};
7903} // end anonymous namespace
7904
7905static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007906 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007907 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007908}
7909
Jay Foad39c79802011-01-12 09:06:06 +00007910static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007911 QualType ResultTy,
7912 const Expr *Arg,
7913 bool SNaN,
7914 llvm::APFloat &Result) {
7915 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7916 if (!S) return false;
7917
7918 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7919
7920 llvm::APInt fill;
7921
7922 // Treat empty strings as if they were zero.
7923 if (S->getString().empty())
7924 fill = llvm::APInt(32, 0);
7925 else if (S->getString().getAsInteger(0, fill))
7926 return false;
7927
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007928 if (Context.getTargetInfo().isNan2008()) {
7929 if (SNaN)
7930 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7931 else
7932 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7933 } else {
7934 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7935 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7936 // a different encoding to what became a standard in 2008, and for pre-
7937 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7938 // sNaN. This is now known as "legacy NaN" encoding.
7939 if (SNaN)
7940 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7941 else
7942 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7943 }
7944
John McCall16291492010-02-28 13:00:19 +00007945 return true;
7946}
7947
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007948bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007949 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007950 default:
7951 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7952
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007953 case Builtin::BI__builtin_huge_val:
7954 case Builtin::BI__builtin_huge_valf:
7955 case Builtin::BI__builtin_huge_vall:
7956 case Builtin::BI__builtin_inf:
7957 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007958 case Builtin::BI__builtin_infl: {
7959 const llvm::fltSemantics &Sem =
7960 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007961 Result = llvm::APFloat::getInf(Sem);
7962 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007963 }
Mike Stump11289f42009-09-09 15:08:12 +00007964
John McCall16291492010-02-28 13:00:19 +00007965 case Builtin::BI__builtin_nans:
7966 case Builtin::BI__builtin_nansf:
7967 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007968 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7969 true, Result))
7970 return Error(E);
7971 return true;
John McCall16291492010-02-28 13:00:19 +00007972
Chris Lattner0b7282e2008-10-06 06:31:58 +00007973 case Builtin::BI__builtin_nan:
7974 case Builtin::BI__builtin_nanf:
7975 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007976 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007977 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007978 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7979 false, Result))
7980 return Error(E);
7981 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007982
7983 case Builtin::BI__builtin_fabs:
7984 case Builtin::BI__builtin_fabsf:
7985 case Builtin::BI__builtin_fabsl:
7986 if (!EvaluateFloat(E->getArg(0), Result, Info))
7987 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007988
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007989 if (Result.isNegative())
7990 Result.changeSign();
7991 return true;
7992
Richard Smith8889a3d2013-06-13 06:26:32 +00007993 // FIXME: Builtin::BI__builtin_powi
7994 // FIXME: Builtin::BI__builtin_powif
7995 // FIXME: Builtin::BI__builtin_powil
7996
Mike Stump11289f42009-09-09 15:08:12 +00007997 case Builtin::BI__builtin_copysign:
7998 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007999 case Builtin::BI__builtin_copysignl: {
8000 APFloat RHS(0.);
8001 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8002 !EvaluateFloat(E->getArg(1), RHS, Info))
8003 return false;
8004 Result.copySign(RHS);
8005 return true;
8006 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008007 }
8008}
8009
John McCallb1fb0d32010-05-07 22:08:54 +00008010bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008011 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8012 ComplexValue CV;
8013 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8014 return false;
8015 Result = CV.FloatReal;
8016 return true;
8017 }
8018
8019 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008020}
8021
8022bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008023 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8024 ComplexValue CV;
8025 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8026 return false;
8027 Result = CV.FloatImag;
8028 return true;
8029 }
8030
Richard Smith4a678122011-10-24 18:44:57 +00008031 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008032 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8033 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008034 return true;
8035}
8036
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008037bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008038 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008039 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008040 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008041 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008042 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008043 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8044 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008045 Result.changeSign();
8046 return true;
8047 }
8048}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008049
Eli Friedman24c01542008-08-22 00:06:13 +00008050bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008051 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8052 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008053
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008054 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008055 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8056 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008057 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008058 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8059 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008060}
8061
8062bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8063 Result = E->getValue();
8064 return true;
8065}
8066
Peter Collingbournee9200682011-05-13 03:29:01 +00008067bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8068 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008069
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008070 switch (E->getCastKind()) {
8071 default:
Richard Smith11562c52011-10-28 17:51:58 +00008072 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008073
8074 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008075 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008076 return EvaluateInteger(SubExpr, IntResult, Info) &&
8077 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8078 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008079 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008080
8081 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008082 if (!Visit(SubExpr))
8083 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008084 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8085 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008086 }
John McCalld7646252010-11-14 08:17:51 +00008087
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008088 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008089 ComplexValue V;
8090 if (!EvaluateComplex(SubExpr, V, Info))
8091 return false;
8092 Result = V.getComplexFloatReal();
8093 return true;
8094 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008095 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008096}
8097
Eli Friedman24c01542008-08-22 00:06:13 +00008098//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008099// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008100//===----------------------------------------------------------------------===//
8101
8102namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008103class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008104 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008105 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008106
Anders Carlsson537969c2008-11-16 20:27:53 +00008107public:
John McCall93d91dc2010-05-07 17:22:02 +00008108 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008109 : ExprEvaluatorBaseTy(info), Result(Result) {}
8110
Richard Smith2e312c82012-03-03 22:46:17 +00008111 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008112 Result.setFrom(V);
8113 return true;
8114 }
Mike Stump11289f42009-09-09 15:08:12 +00008115
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008116 bool ZeroInitialization(const Expr *E);
8117
Anders Carlsson537969c2008-11-16 20:27:53 +00008118 //===--------------------------------------------------------------------===//
8119 // Visitor Methods
8120 //===--------------------------------------------------------------------===//
8121
Peter Collingbournee9200682011-05-13 03:29:01 +00008122 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008123 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008124 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008125 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008126 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008127};
8128} // end anonymous namespace
8129
John McCall93d91dc2010-05-07 17:22:02 +00008130static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8131 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008132 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008133 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008134}
8135
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008136bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008137 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008138 if (ElemTy->isRealFloatingType()) {
8139 Result.makeComplexFloat();
8140 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8141 Result.FloatReal = Zero;
8142 Result.FloatImag = Zero;
8143 } else {
8144 Result.makeComplexInt();
8145 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8146 Result.IntReal = Zero;
8147 Result.IntImag = Zero;
8148 }
8149 return true;
8150}
8151
Peter Collingbournee9200682011-05-13 03:29:01 +00008152bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8153 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008154
8155 if (SubExpr->getType()->isRealFloatingType()) {
8156 Result.makeComplexFloat();
8157 APFloat &Imag = Result.FloatImag;
8158 if (!EvaluateFloat(SubExpr, Imag, Info))
8159 return false;
8160
8161 Result.FloatReal = APFloat(Imag.getSemantics());
8162 return true;
8163 } else {
8164 assert(SubExpr->getType()->isIntegerType() &&
8165 "Unexpected imaginary literal.");
8166
8167 Result.makeComplexInt();
8168 APSInt &Imag = Result.IntImag;
8169 if (!EvaluateInteger(SubExpr, Imag, Info))
8170 return false;
8171
8172 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8173 return true;
8174 }
8175}
8176
Peter Collingbournee9200682011-05-13 03:29:01 +00008177bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008178
John McCallfcef3cf2010-12-14 17:51:41 +00008179 switch (E->getCastKind()) {
8180 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008181 case CK_BaseToDerived:
8182 case CK_DerivedToBase:
8183 case CK_UncheckedDerivedToBase:
8184 case CK_Dynamic:
8185 case CK_ToUnion:
8186 case CK_ArrayToPointerDecay:
8187 case CK_FunctionToPointerDecay:
8188 case CK_NullToPointer:
8189 case CK_NullToMemberPointer:
8190 case CK_BaseToDerivedMemberPointer:
8191 case CK_DerivedToBaseMemberPointer:
8192 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008193 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008194 case CK_ConstructorConversion:
8195 case CK_IntegralToPointer:
8196 case CK_PointerToIntegral:
8197 case CK_PointerToBoolean:
8198 case CK_ToVoid:
8199 case CK_VectorSplat:
8200 case CK_IntegralCast:
8201 case CK_IntegralToBoolean:
8202 case CK_IntegralToFloating:
8203 case CK_FloatingToIntegral:
8204 case CK_FloatingToBoolean:
8205 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008206 case CK_CPointerToObjCPointerCast:
8207 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008208 case CK_AnyPointerToBlockPointerCast:
8209 case CK_ObjCObjectLValueCast:
8210 case CK_FloatingComplexToReal:
8211 case CK_FloatingComplexToBoolean:
8212 case CK_IntegralComplexToReal:
8213 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008214 case CK_ARCProduceObject:
8215 case CK_ARCConsumeObject:
8216 case CK_ARCReclaimReturnedObject:
8217 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008218 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008219 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008220 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008221 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008222 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008223 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008224
John McCallfcef3cf2010-12-14 17:51:41 +00008225 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008226 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008227 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008228 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008229
8230 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008231 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008232 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008233 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008234
8235 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008236 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008237 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008238 return false;
8239
John McCallfcef3cf2010-12-14 17:51:41 +00008240 Result.makeComplexFloat();
8241 Result.FloatImag = APFloat(Real.getSemantics());
8242 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008243 }
8244
John McCallfcef3cf2010-12-14 17:51:41 +00008245 case CK_FloatingComplexCast: {
8246 if (!Visit(E->getSubExpr()))
8247 return false;
8248
8249 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8250 QualType From
8251 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8252
Richard Smith357362d2011-12-13 06:39:58 +00008253 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8254 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008255 }
8256
8257 case CK_FloatingComplexToIntegralComplex: {
8258 if (!Visit(E->getSubExpr()))
8259 return false;
8260
8261 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8262 QualType From
8263 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8264 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008265 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8266 To, Result.IntReal) &&
8267 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8268 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008269 }
8270
8271 case CK_IntegralRealToComplex: {
8272 APSInt &Real = Result.IntReal;
8273 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8274 return false;
8275
8276 Result.makeComplexInt();
8277 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8278 return true;
8279 }
8280
8281 case CK_IntegralComplexCast: {
8282 if (!Visit(E->getSubExpr()))
8283 return false;
8284
8285 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8286 QualType From
8287 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8288
Richard Smith911e1422012-01-30 22:27:01 +00008289 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8290 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008291 return true;
8292 }
8293
8294 case CK_IntegralComplexToFloatingComplex: {
8295 if (!Visit(E->getSubExpr()))
8296 return false;
8297
Ted Kremenek28831752012-08-23 20:46:57 +00008298 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008299 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008300 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008301 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008302 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8303 To, Result.FloatReal) &&
8304 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8305 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008306 }
8307 }
8308
8309 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008310}
8311
John McCall93d91dc2010-05-07 17:22:02 +00008312bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008313 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008314 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8315
Chandler Carrutha216cad2014-10-11 00:57:18 +00008316 // Track whether the LHS or RHS is real at the type system level. When this is
8317 // the case we can simplify our evaluation strategy.
8318 bool LHSReal = false, RHSReal = false;
8319
8320 bool LHSOK;
8321 if (E->getLHS()->getType()->isRealFloatingType()) {
8322 LHSReal = true;
8323 APFloat &Real = Result.FloatReal;
8324 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8325 if (LHSOK) {
8326 Result.makeComplexFloat();
8327 Result.FloatImag = APFloat(Real.getSemantics());
8328 }
8329 } else {
8330 LHSOK = Visit(E->getLHS());
8331 }
Richard Smith253c2a32012-01-27 01:14:48 +00008332 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008333 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008334
John McCall93d91dc2010-05-07 17:22:02 +00008335 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008336 if (E->getRHS()->getType()->isRealFloatingType()) {
8337 RHSReal = true;
8338 APFloat &Real = RHS.FloatReal;
8339 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8340 return false;
8341 RHS.makeComplexFloat();
8342 RHS.FloatImag = APFloat(Real.getSemantics());
8343 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008344 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008345
Chandler Carrutha216cad2014-10-11 00:57:18 +00008346 assert(!(LHSReal && RHSReal) &&
8347 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008348 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008349 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008350 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008351 if (Result.isComplexFloat()) {
8352 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8353 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008354 if (LHSReal)
8355 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8356 else if (!RHSReal)
8357 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8358 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008359 } else {
8360 Result.getComplexIntReal() += RHS.getComplexIntReal();
8361 Result.getComplexIntImag() += RHS.getComplexIntImag();
8362 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008363 break;
John McCalle3027922010-08-25 11:45:40 +00008364 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008365 if (Result.isComplexFloat()) {
8366 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8367 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008368 if (LHSReal) {
8369 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8370 Result.getComplexFloatImag().changeSign();
8371 } else if (!RHSReal) {
8372 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8373 APFloat::rmNearestTiesToEven);
8374 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008375 } else {
8376 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8377 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8378 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008379 break;
John McCalle3027922010-08-25 11:45:40 +00008380 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008381 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008382 // This is an implementation of complex multiplication according to the
8383 // constraints laid out in C11 Annex G. The implemantion uses the
8384 // following naming scheme:
8385 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008386 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008387 APFloat &A = LHS.getComplexFloatReal();
8388 APFloat &B = LHS.getComplexFloatImag();
8389 APFloat &C = RHS.getComplexFloatReal();
8390 APFloat &D = RHS.getComplexFloatImag();
8391 APFloat &ResR = Result.getComplexFloatReal();
8392 APFloat &ResI = Result.getComplexFloatImag();
8393 if (LHSReal) {
8394 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8395 ResR = A * C;
8396 ResI = A * D;
8397 } else if (RHSReal) {
8398 ResR = C * A;
8399 ResI = C * B;
8400 } else {
8401 // In the fully general case, we need to handle NaNs and infinities
8402 // robustly.
8403 APFloat AC = A * C;
8404 APFloat BD = B * D;
8405 APFloat AD = A * D;
8406 APFloat BC = B * C;
8407 ResR = AC - BD;
8408 ResI = AD + BC;
8409 if (ResR.isNaN() && ResI.isNaN()) {
8410 bool Recalc = false;
8411 if (A.isInfinity() || B.isInfinity()) {
8412 A = APFloat::copySign(
8413 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8414 B = APFloat::copySign(
8415 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8416 if (C.isNaN())
8417 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8418 if (D.isNaN())
8419 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8420 Recalc = true;
8421 }
8422 if (C.isInfinity() || D.isInfinity()) {
8423 C = APFloat::copySign(
8424 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8425 D = APFloat::copySign(
8426 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8427 if (A.isNaN())
8428 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8429 if (B.isNaN())
8430 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8431 Recalc = true;
8432 }
8433 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8434 AD.isInfinity() || BC.isInfinity())) {
8435 if (A.isNaN())
8436 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8437 if (B.isNaN())
8438 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8439 if (C.isNaN())
8440 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8441 if (D.isNaN())
8442 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8443 Recalc = true;
8444 }
8445 if (Recalc) {
8446 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8447 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8448 }
8449 }
8450 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008451 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008452 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008453 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008454 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8455 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008456 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008457 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8458 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8459 }
8460 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008461 case BO_Div:
8462 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008463 // This is an implementation of complex division according to the
8464 // constraints laid out in C11 Annex G. The implemantion uses the
8465 // following naming scheme:
8466 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008467 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008468 APFloat &A = LHS.getComplexFloatReal();
8469 APFloat &B = LHS.getComplexFloatImag();
8470 APFloat &C = RHS.getComplexFloatReal();
8471 APFloat &D = RHS.getComplexFloatImag();
8472 APFloat &ResR = Result.getComplexFloatReal();
8473 APFloat &ResI = Result.getComplexFloatImag();
8474 if (RHSReal) {
8475 ResR = A / C;
8476 ResI = B / C;
8477 } else {
8478 if (LHSReal) {
8479 // No real optimizations we can do here, stub out with zero.
8480 B = APFloat::getZero(A.getSemantics());
8481 }
8482 int DenomLogB = 0;
8483 APFloat MaxCD = maxnum(abs(C), abs(D));
8484 if (MaxCD.isFinite()) {
8485 DenomLogB = ilogb(MaxCD);
8486 C = scalbn(C, -DenomLogB);
8487 D = scalbn(D, -DenomLogB);
8488 }
8489 APFloat Denom = C * C + D * D;
8490 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8491 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8492 if (ResR.isNaN() && ResI.isNaN()) {
8493 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8494 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8495 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8496 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8497 D.isFinite()) {
8498 A = APFloat::copySign(
8499 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8500 B = APFloat::copySign(
8501 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8502 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8503 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8504 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8505 C = APFloat::copySign(
8506 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8507 D = APFloat::copySign(
8508 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8509 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8510 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8511 }
8512 }
8513 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008514 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008515 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8516 return Error(E, diag::note_expr_divide_by_zero);
8517
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008518 ComplexValue LHS = Result;
8519 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8520 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8521 Result.getComplexIntReal() =
8522 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8523 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8524 Result.getComplexIntImag() =
8525 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8526 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8527 }
8528 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008529 }
8530
John McCall93d91dc2010-05-07 17:22:02 +00008531 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008532}
8533
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008534bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8535 // Get the operand value into 'Result'.
8536 if (!Visit(E->getSubExpr()))
8537 return false;
8538
8539 switch (E->getOpcode()) {
8540 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008541 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008542 case UO_Extension:
8543 return true;
8544 case UO_Plus:
8545 // The result is always just the subexpr.
8546 return true;
8547 case UO_Minus:
8548 if (Result.isComplexFloat()) {
8549 Result.getComplexFloatReal().changeSign();
8550 Result.getComplexFloatImag().changeSign();
8551 }
8552 else {
8553 Result.getComplexIntReal() = -Result.getComplexIntReal();
8554 Result.getComplexIntImag() = -Result.getComplexIntImag();
8555 }
8556 return true;
8557 case UO_Not:
8558 if (Result.isComplexFloat())
8559 Result.getComplexFloatImag().changeSign();
8560 else
8561 Result.getComplexIntImag() = -Result.getComplexIntImag();
8562 return true;
8563 }
8564}
8565
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008566bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8567 if (E->getNumInits() == 2) {
8568 if (E->getType()->isComplexType()) {
8569 Result.makeComplexFloat();
8570 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8571 return false;
8572 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8573 return false;
8574 } else {
8575 Result.makeComplexInt();
8576 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8577 return false;
8578 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8579 return false;
8580 }
8581 return true;
8582 }
8583 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8584}
8585
Anders Carlsson537969c2008-11-16 20:27:53 +00008586//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008587// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8588// implicit conversion.
8589//===----------------------------------------------------------------------===//
8590
8591namespace {
8592class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008593 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008594 APValue &Result;
8595public:
8596 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8597 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8598
8599 bool Success(const APValue &V, const Expr *E) {
8600 Result = V;
8601 return true;
8602 }
8603
8604 bool ZeroInitialization(const Expr *E) {
8605 ImplicitValueInitExpr VIE(
8606 E->getType()->castAs<AtomicType>()->getValueType());
8607 return Evaluate(Result, Info, &VIE);
8608 }
8609
8610 bool VisitCastExpr(const CastExpr *E) {
8611 switch (E->getCastKind()) {
8612 default:
8613 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8614 case CK_NonAtomicToAtomic:
8615 return Evaluate(Result, Info, E->getSubExpr());
8616 }
8617 }
8618};
8619} // end anonymous namespace
8620
8621static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8622 assert(E->isRValue() && E->getType()->isAtomicType());
8623 return AtomicExprEvaluator(Info, Result).Visit(E);
8624}
8625
8626//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008627// Void expression evaluation, primarily for a cast to void on the LHS of a
8628// comma operator
8629//===----------------------------------------------------------------------===//
8630
8631namespace {
8632class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008633 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008634public:
8635 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8636
Richard Smith2e312c82012-03-03 22:46:17 +00008637 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008638
8639 bool VisitCastExpr(const CastExpr *E) {
8640 switch (E->getCastKind()) {
8641 default:
8642 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8643 case CK_ToVoid:
8644 VisitIgnoredValue(E->getSubExpr());
8645 return true;
8646 }
8647 }
Hal Finkela8443c32014-07-17 14:49:58 +00008648
8649 bool VisitCallExpr(const CallExpr *E) {
8650 switch (E->getBuiltinCallee()) {
8651 default:
8652 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8653 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008654 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008655 // The argument is not evaluated!
8656 return true;
8657 }
8658 }
Richard Smith42d3af92011-12-07 00:43:50 +00008659};
8660} // end anonymous namespace
8661
8662static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8663 assert(E->isRValue() && E->getType()->isVoidType());
8664 return VoidExprEvaluator(Info).Visit(E);
8665}
8666
8667//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008668// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008669//===----------------------------------------------------------------------===//
8670
Richard Smith2e312c82012-03-03 22:46:17 +00008671static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008672 // In C, function designators are not lvalues, but we evaluate them as if they
8673 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008674 QualType T = E->getType();
8675 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008676 LValue LV;
8677 if (!EvaluateLValue(E, LV, Info))
8678 return false;
8679 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008680 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008681 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008682 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008683 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008684 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008685 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008686 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008687 LValue LV;
8688 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008689 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008690 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008691 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008692 llvm::APFloat F(0.0);
8693 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008694 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008695 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008696 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008697 ComplexValue C;
8698 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008699 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008700 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008701 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008702 MemberPtr P;
8703 if (!EvaluateMemberPointer(E, P, Info))
8704 return false;
8705 P.moveInto(Result);
8706 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008707 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008708 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008709 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008710 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8711 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008712 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008713 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008714 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008715 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008716 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008717 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8718 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008719 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008720 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008721 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008722 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008723 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008724 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008725 if (!EvaluateVoid(E, Info))
8726 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008727 } else if (T->isAtomicType()) {
8728 if (!EvaluateAtomic(E, Result, Info))
8729 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008730 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008731 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008732 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008733 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008734 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008735 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008736 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008737
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008738 return true;
8739}
8740
Richard Smithb228a862012-02-15 02:18:13 +00008741/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8742/// cases, the in-place evaluation is essential, since later initializers for
8743/// an object can indirectly refer to subobjects which were initialized earlier.
8744static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008745 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008746 assert(!E->isValueDependent());
8747
Richard Smith7525ff62013-05-09 07:14:00 +00008748 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008749 return false;
8750
8751 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008752 // Evaluate arrays and record types in-place, so that later initializers can
8753 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008754 if (E->getType()->isArrayType())
8755 return EvaluateArray(E, This, Result, Info);
8756 else if (E->getType()->isRecordType())
8757 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008758 }
8759
8760 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008761 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008762}
8763
Richard Smithf57d8cb2011-12-09 22:58:01 +00008764/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8765/// lvalue-to-rvalue cast if it is an lvalue.
8766static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008767 if (E->getType().isNull())
8768 return false;
8769
Richard Smithfddd3842011-12-30 21:15:51 +00008770 if (!CheckLiteralType(Info, E))
8771 return false;
8772
Richard Smith2e312c82012-03-03 22:46:17 +00008773 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008774 return false;
8775
8776 if (E->isGLValue()) {
8777 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008778 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008779 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008780 return false;
8781 }
8782
Richard Smith2e312c82012-03-03 22:46:17 +00008783 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008784 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008785}
Richard Smith11562c52011-10-28 17:51:58 +00008786
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008787static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8788 const ASTContext &Ctx, bool &IsConst) {
8789 // Fast-path evaluations of integer literals, since we sometimes see files
8790 // containing vast quantities of these.
8791 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8792 Result.Val = APValue(APSInt(L->getValue(),
8793 L->getType()->isUnsignedIntegerType()));
8794 IsConst = true;
8795 return true;
8796 }
James Dennett0492ef02014-03-14 17:44:10 +00008797
8798 // This case should be rare, but we need to check it before we check on
8799 // the type below.
8800 if (Exp->getType().isNull()) {
8801 IsConst = false;
8802 return true;
8803 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008804
8805 // FIXME: Evaluating values of large array and record types can cause
8806 // performance problems. Only do so in C++11 for now.
8807 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8808 Exp->getType()->isRecordType()) &&
8809 !Ctx.getLangOpts().CPlusPlus11) {
8810 IsConst = false;
8811 return true;
8812 }
8813 return false;
8814}
8815
8816
Richard Smith7b553f12011-10-29 00:50:52 +00008817/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008818/// any crazy technique (that has nothing to do with language standards) that
8819/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008820/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8821/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008822bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008823 bool IsConst;
8824 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8825 return IsConst;
8826
Richard Smith6d4c6582013-11-05 22:18:15 +00008827 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008828 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008829}
8830
Jay Foad39c79802011-01-12 09:06:06 +00008831bool Expr::EvaluateAsBooleanCondition(bool &Result,
8832 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008833 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008834 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008835 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008836}
8837
Richard Smith5fab0c92011-12-28 19:48:30 +00008838bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8839 SideEffectsKind AllowSideEffects) const {
8840 if (!getType()->isIntegralOrEnumerationType())
8841 return false;
8842
Richard Smith11562c52011-10-28 17:51:58 +00008843 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008844 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8845 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008846 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008847
Richard Smith11562c52011-10-28 17:51:58 +00008848 Result = ExprResult.Val.getInt();
8849 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008850}
8851
Jay Foad39c79802011-01-12 09:06:06 +00008852bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008853 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008854
John McCall45d55e42010-05-07 21:00:08 +00008855 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008856 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8857 !CheckLValueConstantExpression(Info, getExprLoc(),
8858 Ctx.getLValueReferenceType(getType()), LV))
8859 return false;
8860
Richard Smith2e312c82012-03-03 22:46:17 +00008861 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008862 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008863}
8864
Richard Smithd0b4dd62011-12-19 06:19:21 +00008865bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8866 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008867 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008868 // FIXME: Evaluating initializers for large array and record types can cause
8869 // performance problems. Only do so in C++11 for now.
8870 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008871 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008872 return false;
8873
Richard Smithd0b4dd62011-12-19 06:19:21 +00008874 Expr::EvalStatus EStatus;
8875 EStatus.Diag = &Notes;
8876
Richard Smith0c6124b2015-12-03 01:36:22 +00008877 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
8878 ? EvalInfo::EM_ConstantExpression
8879 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008880 InitInfo.setEvaluatingDecl(VD, Value);
8881
8882 LValue LVal;
8883 LVal.set(VD);
8884
Richard Smithfddd3842011-12-30 21:15:51 +00008885 // C++11 [basic.start.init]p2:
8886 // Variables with static storage duration or thread storage duration shall be
8887 // zero-initialized before any other initialization takes place.
8888 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008889 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008890 !VD->getType()->isReferenceType()) {
8891 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008892 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008893 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008894 return false;
8895 }
8896
Richard Smith7525ff62013-05-09 07:14:00 +00008897 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8898 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008899 EStatus.HasSideEffects)
8900 return false;
8901
8902 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8903 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008904}
8905
Richard Smith7b553f12011-10-29 00:50:52 +00008906/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8907/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008908bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008909 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008910 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008911}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008912
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008913APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008914 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008915 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008916 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008917 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008918 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008919 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008920 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008921
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008922 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008923}
John McCall864e3962010-05-07 05:32:02 +00008924
Richard Smithe9ff7702013-11-05 22:23:30 +00008925void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008926 bool IsConst;
8927 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008928 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008929 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008930 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8931 }
8932}
8933
Richard Smithe6c01442013-06-05 00:46:14 +00008934bool Expr::EvalResult::isGlobalLValue() const {
8935 assert(Val.isLValue());
8936 return IsGlobalLValue(Val.getLValueBase());
8937}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008938
8939
John McCall864e3962010-05-07 05:32:02 +00008940/// isIntegerConstantExpr - this recursive routine will test if an expression is
8941/// an integer constant expression.
8942
8943/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8944/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008945
8946// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008947// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8948// and a (possibly null) SourceLocation indicating the location of the problem.
8949//
John McCall864e3962010-05-07 05:32:02 +00008950// Note that to reduce code duplication, this helper does no evaluation
8951// itself; the caller checks whether the expression is evaluatable, and
8952// in the rare cases where CheckICE actually cares about the evaluated
8953// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008954
Dan Gohman28ade552010-07-26 21:25:24 +00008955namespace {
8956
Richard Smith9e575da2012-12-28 13:25:52 +00008957enum ICEKind {
8958 /// This expression is an ICE.
8959 IK_ICE,
8960 /// This expression is not an ICE, but if it isn't evaluated, it's
8961 /// a legal subexpression for an ICE. This return value is used to handle
8962 /// the comma operator in C99 mode, and non-constant subexpressions.
8963 IK_ICEIfUnevaluated,
8964 /// This expression is not an ICE, and is not a legal subexpression for one.
8965 IK_NotICE
8966};
8967
John McCall864e3962010-05-07 05:32:02 +00008968struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008969 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008970 SourceLocation Loc;
8971
Richard Smith9e575da2012-12-28 13:25:52 +00008972 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008973};
8974
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008975}
Dan Gohman28ade552010-07-26 21:25:24 +00008976
Richard Smith9e575da2012-12-28 13:25:52 +00008977static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8978
8979static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008980
Craig Toppera31a8822013-08-22 07:09:37 +00008981static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008982 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008983 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008984 !EVResult.Val.isInt())
8985 return ICEDiag(IK_NotICE, E->getLocStart());
8986
John McCall864e3962010-05-07 05:32:02 +00008987 return NoDiag();
8988}
8989
Craig Toppera31a8822013-08-22 07:09:37 +00008990static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008991 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008992 if (!E->getType()->isIntegralOrEnumerationType())
8993 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008994
8995 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008996#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008997#define STMT(Node, Base) case Expr::Node##Class:
8998#define EXPR(Node, Base)
8999#include "clang/AST/StmtNodes.inc"
9000 case Expr::PredefinedExprClass:
9001 case Expr::FloatingLiteralClass:
9002 case Expr::ImaginaryLiteralClass:
9003 case Expr::StringLiteralClass:
9004 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009005 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009006 case Expr::MemberExprClass:
9007 case Expr::CompoundAssignOperatorClass:
9008 case Expr::CompoundLiteralExprClass:
9009 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009010 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009011 case Expr::NoInitExprClass:
9012 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009013 case Expr::ImplicitValueInitExprClass:
9014 case Expr::ParenListExprClass:
9015 case Expr::VAArgExprClass:
9016 case Expr::AddrLabelExprClass:
9017 case Expr::StmtExprClass:
9018 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009019 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009020 case Expr::CXXDynamicCastExprClass:
9021 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009022 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009023 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009024 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009025 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009026 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009027 case Expr::CXXThisExprClass:
9028 case Expr::CXXThrowExprClass:
9029 case Expr::CXXNewExprClass:
9030 case Expr::CXXDeleteExprClass:
9031 case Expr::CXXPseudoDestructorExprClass:
9032 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009033 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009034 case Expr::DependentScopeDeclRefExprClass:
9035 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009036 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009037 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009038 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009039 case Expr::CXXTemporaryObjectExprClass:
9040 case Expr::CXXUnresolvedConstructExprClass:
9041 case Expr::CXXDependentScopeMemberExprClass:
9042 case Expr::UnresolvedMemberExprClass:
9043 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009044 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009045 case Expr::ObjCArrayLiteralClass:
9046 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009047 case Expr::ObjCEncodeExprClass:
9048 case Expr::ObjCMessageExprClass:
9049 case Expr::ObjCSelectorExprClass:
9050 case Expr::ObjCProtocolExprClass:
9051 case Expr::ObjCIvarRefExprClass:
9052 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009053 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009054 case Expr::ObjCIsaExprClass:
9055 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009056 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009057 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009058 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009059 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009060 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009061 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009062 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009063 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009064 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009065 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009066 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009067 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009068 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009069 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009070 case Expr::CoawaitExprClass:
9071 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009072 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009073
Richard Smithf137f932014-01-25 20:50:08 +00009074 case Expr::InitListExprClass: {
9075 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9076 // form "T x = { a };" is equivalent to "T x = a;".
9077 // Unless we're initializing a reference, T is a scalar as it is known to be
9078 // of integral or enumeration type.
9079 if (E->isRValue())
9080 if (cast<InitListExpr>(E)->getNumInits() == 1)
9081 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9082 return ICEDiag(IK_NotICE, E->getLocStart());
9083 }
9084
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009085 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009086 case Expr::GNUNullExprClass:
9087 // GCC considers the GNU __null value to be an integral constant expression.
9088 return NoDiag();
9089
John McCall7c454bb2011-07-15 05:09:51 +00009090 case Expr::SubstNonTypeTemplateParmExprClass:
9091 return
9092 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9093
John McCall864e3962010-05-07 05:32:02 +00009094 case Expr::ParenExprClass:
9095 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009096 case Expr::GenericSelectionExprClass:
9097 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009098 case Expr::IntegerLiteralClass:
9099 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009100 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009101 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009102 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009103 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009104 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009105 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009106 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009107 return NoDiag();
9108 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009109 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009110 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9111 // constant expressions, but they can never be ICEs because an ICE cannot
9112 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009113 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009114 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009115 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009116 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009117 }
Richard Smith6365c912012-02-24 22:12:32 +00009118 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009119 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9120 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009121 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009122 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009123 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009124 // Parameter variables are never constants. Without this check,
9125 // getAnyInitializer() can find a default argument, which leads
9126 // to chaos.
9127 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009128 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009129
9130 // C++ 7.1.5.1p2
9131 // A variable of non-volatile const-qualified integral or enumeration
9132 // type initialized by an ICE can be used in ICEs.
9133 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009134 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009135 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009136
Richard Smithd0b4dd62011-12-19 06:19:21 +00009137 const VarDecl *VD;
9138 // Look for a declaration of this variable that has an initializer, and
9139 // check whether it is an ICE.
9140 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9141 return NoDiag();
9142 else
Richard Smith9e575da2012-12-28 13:25:52 +00009143 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009144 }
9145 }
Richard Smith9e575da2012-12-28 13:25:52 +00009146 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009147 }
John McCall864e3962010-05-07 05:32:02 +00009148 case Expr::UnaryOperatorClass: {
9149 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9150 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009151 case UO_PostInc:
9152 case UO_PostDec:
9153 case UO_PreInc:
9154 case UO_PreDec:
9155 case UO_AddrOf:
9156 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009157 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009158 // C99 6.6/3 allows increment and decrement within unevaluated
9159 // subexpressions of constant expressions, but they can never be ICEs
9160 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009161 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009162 case UO_Extension:
9163 case UO_LNot:
9164 case UO_Plus:
9165 case UO_Minus:
9166 case UO_Not:
9167 case UO_Real:
9168 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009169 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009170 }
Richard Smith9e575da2012-12-28 13:25:52 +00009171
John McCall864e3962010-05-07 05:32:02 +00009172 // OffsetOf falls through here.
9173 }
9174 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009175 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9176 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9177 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9178 // compliance: we should warn earlier for offsetof expressions with
9179 // array subscripts that aren't ICEs, and if the array subscripts
9180 // are ICEs, the value of the offsetof must be an integer constant.
9181 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009182 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009183 case Expr::UnaryExprOrTypeTraitExprClass: {
9184 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9185 if ((Exp->getKind() == UETT_SizeOf) &&
9186 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009187 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009188 return NoDiag();
9189 }
9190 case Expr::BinaryOperatorClass: {
9191 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9192 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009193 case BO_PtrMemD:
9194 case BO_PtrMemI:
9195 case BO_Assign:
9196 case BO_MulAssign:
9197 case BO_DivAssign:
9198 case BO_RemAssign:
9199 case BO_AddAssign:
9200 case BO_SubAssign:
9201 case BO_ShlAssign:
9202 case BO_ShrAssign:
9203 case BO_AndAssign:
9204 case BO_XorAssign:
9205 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009206 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9207 // constant expressions, but they can never be ICEs because an ICE cannot
9208 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009209 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009210
John McCalle3027922010-08-25 11:45:40 +00009211 case BO_Mul:
9212 case BO_Div:
9213 case BO_Rem:
9214 case BO_Add:
9215 case BO_Sub:
9216 case BO_Shl:
9217 case BO_Shr:
9218 case BO_LT:
9219 case BO_GT:
9220 case BO_LE:
9221 case BO_GE:
9222 case BO_EQ:
9223 case BO_NE:
9224 case BO_And:
9225 case BO_Xor:
9226 case BO_Or:
9227 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009228 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9229 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009230 if (Exp->getOpcode() == BO_Div ||
9231 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009232 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009233 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009234 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009235 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009236 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009237 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009238 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009239 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009240 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009241 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009242 }
9243 }
9244 }
John McCalle3027922010-08-25 11:45:40 +00009245 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009246 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009247 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9248 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009249 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9250 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009251 } else {
9252 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009253 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009254 }
9255 }
Richard Smith9e575da2012-12-28 13:25:52 +00009256 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009257 }
John McCalle3027922010-08-25 11:45:40 +00009258 case BO_LAnd:
9259 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009260 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9261 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009262 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009263 // Rare case where the RHS has a comma "side-effect"; we need
9264 // to actually check the condition to see whether the side
9265 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009266 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009267 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009268 return RHSResult;
9269 return NoDiag();
9270 }
9271
Richard Smith9e575da2012-12-28 13:25:52 +00009272 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009273 }
9274 }
9275 }
9276 case Expr::ImplicitCastExprClass:
9277 case Expr::CStyleCastExprClass:
9278 case Expr::CXXFunctionalCastExprClass:
9279 case Expr::CXXStaticCastExprClass:
9280 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009281 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009282 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009283 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009284 if (isa<ExplicitCastExpr>(E)) {
9285 if (const FloatingLiteral *FL
9286 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9287 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9288 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9289 APSInt IgnoredVal(DestWidth, !DestSigned);
9290 bool Ignored;
9291 // If the value does not fit in the destination type, the behavior is
9292 // undefined, so we are not required to treat it as a constant
9293 // expression.
9294 if (FL->getValue().convertToInteger(IgnoredVal,
9295 llvm::APFloat::rmTowardZero,
9296 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009297 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009298 return NoDiag();
9299 }
9300 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009301 switch (cast<CastExpr>(E)->getCastKind()) {
9302 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009303 case CK_AtomicToNonAtomic:
9304 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009305 case CK_NoOp:
9306 case CK_IntegralToBoolean:
9307 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009308 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009309 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009310 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009311 }
John McCall864e3962010-05-07 05:32:02 +00009312 }
John McCallc07a0c72011-02-17 10:25:35 +00009313 case Expr::BinaryConditionalOperatorClass: {
9314 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9315 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009316 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009317 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009318 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9319 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9320 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009321 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009322 return FalseResult;
9323 }
John McCall864e3962010-05-07 05:32:02 +00009324 case Expr::ConditionalOperatorClass: {
9325 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9326 // If the condition (ignoring parens) is a __builtin_constant_p call,
9327 // then only the true side is actually considered in an integer constant
9328 // expression, and it is fully evaluated. This is an important GNU
9329 // extension. See GCC PR38377 for discussion.
9330 if (const CallExpr *CallCE
9331 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009332 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009333 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009334 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009335 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009336 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009337
Richard Smithf57d8cb2011-12-09 22:58:01 +00009338 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9339 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009340
Richard Smith9e575da2012-12-28 13:25:52 +00009341 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009342 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009343 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009344 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009345 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009346 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009347 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009348 return NoDiag();
9349 // Rare case where the diagnostics depend on which side is evaluated
9350 // Note that if we get here, CondResult is 0, and at least one of
9351 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009352 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009353 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009354 return TrueResult;
9355 }
9356 case Expr::CXXDefaultArgExprClass:
9357 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009358 case Expr::CXXDefaultInitExprClass:
9359 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009360 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009361 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009362 }
9363 }
9364
David Blaikiee4d798f2012-01-20 21:50:17 +00009365 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009366}
9367
Richard Smithf57d8cb2011-12-09 22:58:01 +00009368/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009369static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009370 const Expr *E,
9371 llvm::APSInt *Value,
9372 SourceLocation *Loc) {
9373 if (!E->getType()->isIntegralOrEnumerationType()) {
9374 if (Loc) *Loc = E->getExprLoc();
9375 return false;
9376 }
9377
Richard Smith66e05fe2012-01-18 05:21:49 +00009378 APValue Result;
9379 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009380 return false;
9381
Richard Smith98710fc2014-11-13 23:03:19 +00009382 if (!Result.isInt()) {
9383 if (Loc) *Loc = E->getExprLoc();
9384 return false;
9385 }
9386
Richard Smith66e05fe2012-01-18 05:21:49 +00009387 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009388 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009389}
9390
Craig Toppera31a8822013-08-22 07:09:37 +00009391bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9392 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009393 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009394 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009395
Richard Smith9e575da2012-12-28 13:25:52 +00009396 ICEDiag D = CheckICE(this, Ctx);
9397 if (D.Kind != IK_ICE) {
9398 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009399 return false;
9400 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009401 return true;
9402}
9403
Craig Toppera31a8822013-08-22 07:09:37 +00009404bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009405 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009406 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009407 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9408
9409 if (!isIntegerConstantExpr(Ctx, Loc))
9410 return false;
9411 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009412 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009413 return true;
9414}
Richard Smith66e05fe2012-01-18 05:21:49 +00009415
Craig Toppera31a8822013-08-22 07:09:37 +00009416bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009417 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009418}
9419
Craig Toppera31a8822013-08-22 07:09:37 +00009420bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009421 SourceLocation *Loc) const {
9422 // We support this checking in C++98 mode in order to diagnose compatibility
9423 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009424 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009425
Richard Smith98a0a492012-02-14 21:38:30 +00009426 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009427 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009428 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009429 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009430 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009431
9432 APValue Scratch;
9433 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9434
9435 if (!Diags.empty()) {
9436 IsConstExpr = false;
9437 if (Loc) *Loc = Diags[0].first;
9438 } else if (!IsConstExpr) {
9439 // FIXME: This shouldn't happen.
9440 if (Loc) *Loc = getExprLoc();
9441 }
9442
9443 return IsConstExpr;
9444}
Richard Smith253c2a32012-01-27 01:14:48 +00009445
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009446bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9447 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009448 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009449 Expr::EvalStatus Status;
9450 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9451
9452 ArgVector ArgValues(Args.size());
9453 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9454 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009455 if ((*I)->isValueDependent() ||
9456 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009457 // If evaluation fails, throw away the argument entirely.
9458 ArgValues[I - Args.begin()] = APValue();
9459 if (Info.EvalStatus.HasSideEffects)
9460 return false;
9461 }
9462
9463 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009464 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009465 ArgValues.data());
9466 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9467}
9468
Richard Smith253c2a32012-01-27 01:14:48 +00009469bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009470 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009471 PartialDiagnosticAt> &Diags) {
9472 // FIXME: It would be useful to check constexpr function templates, but at the
9473 // moment the constant expression evaluator cannot cope with the non-rigorous
9474 // ASTs which we build for dependent expressions.
9475 if (FD->isDependentContext())
9476 return true;
9477
9478 Expr::EvalStatus Status;
9479 Status.Diag = &Diags;
9480
Richard Smith6d4c6582013-11-05 22:18:15 +00009481 EvalInfo Info(FD->getASTContext(), Status,
9482 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009483
9484 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009485 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009486
Richard Smith7525ff62013-05-09 07:14:00 +00009487 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009488 // is a temporary being used as the 'this' pointer.
9489 LValue This;
9490 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009491 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009492
Richard Smith253c2a32012-01-27 01:14:48 +00009493 ArrayRef<const Expr*> Args;
9494
9495 SourceLocation Loc = FD->getLocation();
9496
Richard Smith2e312c82012-03-03 22:46:17 +00009497 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009498 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9499 // Evaluate the call as a constant initializer, to allow the construction
9500 // of objects of non-literal types.
9501 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009502 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009503 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009504 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009505 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009506
9507 return Diags.empty();
9508}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009509
9510bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9511 const FunctionDecl *FD,
9512 SmallVectorImpl<
9513 PartialDiagnosticAt> &Diags) {
9514 Expr::EvalStatus Status;
9515 Status.Diag = &Diags;
9516
9517 EvalInfo Info(FD->getASTContext(), Status,
9518 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9519
9520 // Fabricate a call stack frame to give the arguments a plausible cover story.
9521 ArrayRef<const Expr*> Args;
9522 ArgVector ArgValues(0);
9523 bool Success = EvaluateArgs(Args, ArgValues, Info);
9524 (void)Success;
9525 assert(Success &&
9526 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009527 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009528
9529 APValue ResultScratch;
9530 Evaluate(ResultScratch, Info, E);
9531 return Diags.empty();
9532}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009533
9534bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9535 unsigned Type) const {
9536 if (!getType()->isPointerType())
9537 return false;
9538
9539 Expr::EvalStatus Status;
9540 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9541 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9542}